Skip to main content

rustc_codegen_llvm/
llvm_util.rs

1use std::collections::VecDeque;
2use std::ffi::{CStr, CString};
3use std::fmt::Write;
4use std::path::Path;
5use std::sync::Once;
6use std::{ptr, slice, str};
7
8use libc::c_int;
9use rustc_codegen_ssa::base::wants_wasm_eh;
10use rustc_codegen_ssa::target_features::cfg_target_feature;
11use rustc_codegen_ssa::{TargetConfig, target_features};
12use rustc_data_structures::fx::FxHashSet;
13use rustc_data_structures::small_c_str::SmallCStr;
14use rustc_fs_util::path_to_c_string;
15use rustc_middle::bug;
16use rustc_session::Session;
17use rustc_session::config::{PrintKind, PrintRequest};
18use rustc_target::spec::{
19    Arch, CfgAbi, Env, MergeFunctions, Os, PanicStrategy, SmallDataThresholdSupport,
20};
21use smallvec::{SmallVec, smallvec};
22
23use crate::back::write::create_informational_target_machine;
24use crate::{errors, llvm};
25
26static INIT: Once = Once::new();
27
28pub(crate) fn init(sess: &Session) {
29    unsafe {
30        // Before we touch LLVM, make sure that multithreading is enabled.
31        if !llvm::LLVMIsMultithreaded().is_true() {
32            ::rustc_middle::util::bug::bug_fmt(format_args!("LLVM compiled without support for threads"));bug!("LLVM compiled without support for threads");
33        }
34        INIT.call_once(|| {
35            configure_llvm(sess);
36        });
37    }
38}
39
40fn require_inited() {
41    if !INIT.is_completed() {
42        ::rustc_middle::util::bug::bug_fmt(format_args!("LLVM is not initialized"));bug!("LLVM is not initialized");
43    }
44}
45
46unsafe fn configure_llvm(sess: &Session) {
47    let n_args = sess.opts.cg.llvm_args.len() + sess.target.llvm_args.len();
48    let mut llvm_c_strs = Vec::with_capacity(n_args + 1);
49    let mut llvm_args = Vec::with_capacity(n_args + 1);
50
51    unsafe {
52        llvm::LLVMRustInstallErrorHandlers();
53    }
54    // On Windows, an LLVM assertion will open an Abort/Retry/Ignore dialog
55    // box for the purpose of launching a debugger. However, on CI this will
56    // cause it to hang until it times out, which can take several hours.
57    if std::env::var_os("CI").is_some() {
58        unsafe {
59            llvm::LLVMRustDisableSystemDialogsOnCrash();
60        }
61    }
62
63    fn llvm_arg_to_arg_name(full_arg: &str) -> &str {
64        full_arg.trim().split(|c: char| c == '=' || c.is_whitespace()).next().unwrap_or("")
65    }
66
67    let cg_opts = sess.opts.cg.llvm_args.iter().map(AsRef::as_ref);
68    let tg_opts = sess.target.llvm_args.iter().map(AsRef::as_ref);
69    // Target-spec args are passed to LLVM before user `-Cllvm-args`. LLVM's
70    // `cl::opt` parser is last-wins, so this lets `-Cllvm-args=...` override
71    // a value already set in the target spec (e.g. `-wasm-use-legacy-eh`).
72    let sess_args = tg_opts.chain(cg_opts);
73
74    let user_specified_args: FxHashSet<_> =
75        sess_args.clone().map(|s| llvm_arg_to_arg_name(s)).filter(|s| !s.is_empty()).collect();
76
77    {
78        // This adds the given argument to LLVM. Unless `force` is true
79        // user specified arguments are *not* overridden.
80        let mut add = |arg: &str, force: bool| {
81            if force || !user_specified_args.contains(llvm_arg_to_arg_name(arg)) {
82                let s = CString::new(arg).unwrap();
83                llvm_args.push(s.as_ptr());
84                llvm_c_strs.push(s);
85            }
86        };
87        // Set the llvm "program name" to make usage and invalid argument messages more clear.
88        add("rustc -Cllvm-args=\"...\" with", true);
89        if sess.opts.unstable_opts.time_llvm_passes {
90            add("-time-passes", false);
91        }
92        if sess.opts.unstable_opts.print_llvm_passes {
93            add("-debug-pass=Structure", false);
94        }
95        if sess.target.generate_arange_section
96            && !sess.opts.unstable_opts.no_generate_arange_section
97        {
98            add("-generate-arange-section", false);
99        }
100
101        match sess.opts.unstable_opts.merge_functions.unwrap_or(sess.target.merge_functions) {
102            MergeFunctions::Disabled | MergeFunctions::Trampolines => {}
103            MergeFunctions::Aliases => {
104                add("-mergefunc-use-aliases", false);
105            }
106        }
107
108        if wants_wasm_eh(sess) {
109            add("-wasm-enable-eh", false);
110        }
111
112        if sess.target.os == Os::Emscripten
113            && !sess.opts.unstable_opts.emscripten_wasm_eh
114            && sess.panic_strategy().unwinds()
115        {
116            add("-enable-emscripten-cxx-exceptions", false);
117        }
118
119        // HACK(eddyb) LLVM inserts `llvm.assume` calls to preserve align attributes
120        // during inlining. Unfortunately these may block other optimizations.
121        add("-preserve-alignment-assumptions-during-inlining=false", false);
122
123        // Use non-zero `import-instr-limit` multiplier for cold callsites.
124        add("-import-cold-multiplier=0.1", false);
125
126        if sess.print_llvm_stats() || sess.print_llvm_stats_json().is_some() {
127            add("-stats", false);
128        }
129
130        for arg in sess_args {
131            add(&(*arg), true);
132        }
133
134        match (
135            sess.opts.unstable_opts.small_data_threshold,
136            sess.target.small_data_threshold_support(),
137        ) {
138            // Set up the small-data optimization limit for architectures that use
139            // an LLVM argument to control this.
140            (Some(threshold), SmallDataThresholdSupport::LlvmArg(arg)) => {
141                add(&::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("--{0}={1}", arg, threshold))
    })format!("--{arg}={threshold}"), false)
142            }
143            _ => (),
144        };
145    }
146
147    if sess.opts.unstable_opts.llvm_time_trace {
148        unsafe { llvm::LLVMRustTimeTraceProfilerInitialize() };
149    }
150
151    rustc_llvm::initialize_available_targets();
152
153    unsafe { llvm::LLVMRustSetLLVMOptions(llvm_args.len() as c_int, llvm_args.as_ptr()) };
154}
155
156pub(crate) fn time_trace_profiler_finish(file_name: &Path) {
157    unsafe {
158        let file_name = path_to_c_string(file_name);
159        llvm::LLVMRustTimeTraceProfilerFinish(file_name.as_ptr());
160    }
161}
162
163enum TargetFeatureFoldStrength<'a> {
164    // The feature is only tied when enabling the feature, disabling
165    // this feature shouldn't disable the tied feature.
166    EnableOnly(&'a str),
167    // The feature is tied for both enabling and disabling this feature.
168    Both(&'a str),
169}
170
171impl<'a> TargetFeatureFoldStrength<'a> {
172    fn as_str(&self) -> &'a str {
173        match self {
174            TargetFeatureFoldStrength::EnableOnly(feat) => feat,
175            TargetFeatureFoldStrength::Both(feat) => feat,
176        }
177    }
178}
179
180pub(crate) struct LLVMFeature<'a> {
181    llvm_feature_name: &'a str,
182    dependencies: SmallVec<[TargetFeatureFoldStrength<'a>; 1]>,
183}
184
185impl<'a> LLVMFeature<'a> {
186    fn new(llvm_feature_name: &'a str) -> Self {
187        Self { llvm_feature_name, dependencies: SmallVec::new() }
188    }
189
190    fn with_dependencies(
191        llvm_feature_name: &'a str,
192        dependencies: SmallVec<[TargetFeatureFoldStrength<'a>; 1]>,
193    ) -> Self {
194        Self { llvm_feature_name, dependencies }
195    }
196}
197
198impl<'a> IntoIterator for LLVMFeature<'a> {
199    type Item = &'a str;
200    type IntoIter = impl Iterator<Item = &'a str>;
201
202    fn into_iter(self) -> Self::IntoIter {
203        let dependencies = self.dependencies.into_iter().map(|feat| feat.as_str());
204        std::iter::once(self.llvm_feature_name).chain(dependencies)
205    }
206}
207
208/// Convert a Rust feature name to an LLVM feature name. Returning `None` means the
209/// feature should be skipped, usually because it is not supported by the current
210/// LLVM version.
211///
212/// WARNING: the features after applying `to_llvm_features` must be known
213/// to LLVM or the feature detection code will walk past the end of the feature
214/// array, leading to crashes.
215///
216/// To find a list of LLVM's names, see llvm-project/llvm/lib/Target/{ARCH}/*.td
217/// where `{ARCH}` is the architecture name. Look for instances of `SubtargetFeature`.
218///
219/// Check the current rustc fork of LLVM in the repo at
220/// <https://github.com/rust-lang/llvm-project/>. The commit in use can be found via the
221/// `llvm-project` submodule in <https://github.com/rust-lang/rust/tree/HEAD/src> Though note that
222/// Rust can also be build with an external precompiled version of LLVM which might lead to failures
223/// if the oldest tested / supported LLVM version doesn't yet support the relevant intrinsics.
224pub(crate) fn to_llvm_features<'a>(sess: &Session, s: &'a str) -> Option<LLVMFeature<'a>> {
225    let (major, _, _) = get_version();
226    match sess.target.arch {
227        Arch::AArch64 | Arch::Arm64EC => {
228            match s {
229                "rcpc2" => Some(LLVMFeature::new("rcpc-immo")),
230                "dpb" => Some(LLVMFeature::new("ccpp")),
231                "dpb2" => Some(LLVMFeature::new("ccdp")),
232                "frintts" => Some(LLVMFeature::new("fptoint")),
233                "fcma" => Some(LLVMFeature::new("complxnum")),
234                "pmuv3" => Some(LLVMFeature::new("perfmon")),
235                "paca" => Some(LLVMFeature::new("pauth")),
236                "pacg" => Some(LLVMFeature::new("pauth")),
237                "flagm2" => Some(LLVMFeature::new("altnzcv")),
238                // Rust ties fp and neon together.
239                "neon" => Some(LLVMFeature::with_dependencies(
240                    "neon",
241                    {
    let count = 0usize + 1usize;
    let mut vec = ::smallvec::SmallVec::new();
    if count <= vec.inline_size() {
        vec.push(TargetFeatureFoldStrength::Both("fp-armv8"));
        vec
    } else {
        ::smallvec::SmallVec::from_vec(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                    [TargetFeatureFoldStrength::Both("fp-armv8")])))
    }
}smallvec![TargetFeatureFoldStrength::Both("fp-armv8")],
242                )),
243                // In LLVM neon implicitly enables fp, but we manually enable
244                // neon when a feature only implicitly enables fp
245                "fhm" => Some(LLVMFeature::new("fp16fml")),
246                "fp16" => Some(LLVMFeature::new("fullfp16")),
247                // Filter out features that are not supported by the current LLVM version
248                "fpmr" => None, // only existed in 18
249                // Withdrawn by ARM; removed from LLVM in 22
250                "tme" if major >= 22 => None,
251                s => Some(LLVMFeature::new(s)),
252            }
253        }
254        Arch::Arm => match s {
255            "fp16" => Some(LLVMFeature::new("fullfp16")),
256            s => Some(LLVMFeature::new(s)),
257        },
258        Arch::Bpf => match s {
259            "allows-misaligned-mem-access" if major < 22 => None,
260            s => Some(LLVMFeature::new(s)),
261        },
262        // Filter out features that are not supported by the current LLVM version
263        Arch::PowerPC | Arch::PowerPC64 => match s {
264            "power8-crypto" => Some(LLVMFeature::new("crypto")),
265            s => Some(LLVMFeature::new(s)),
266        },
267        Arch::RiscV32 | Arch::RiscV64 => match s {
268            // Filter out Rust-specific *virtual* target feature
269            "zkne_or_zknd" => None,
270            s => Some(LLVMFeature::new(s)),
271        },
272        Arch::Sparc | Arch::Sparc64 => match s {
273            "leoncasa" => Some(LLVMFeature::new("hasleoncasa")),
274            s => Some(LLVMFeature::new(s)),
275        },
276        Arch::Wasm32 | Arch::Wasm64 => match s {
277            "gc" if major < 22 => None,
278            s => Some(LLVMFeature::new(s)),
279        },
280        Arch::X86 | Arch::X86_64 => {
281            match s {
282                "sse4.2" => Some(LLVMFeature::with_dependencies(
283                    "sse4.2",
284                    {
    let count = 0usize + 1usize;
    let mut vec = ::smallvec::SmallVec::new();
    if count <= vec.inline_size() {
        vec.push(TargetFeatureFoldStrength::EnableOnly("crc32"));
        vec
    } else {
        ::smallvec::SmallVec::from_vec(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                    [TargetFeatureFoldStrength::EnableOnly("crc32")])))
    }
}smallvec![TargetFeatureFoldStrength::EnableOnly("crc32")],
285                )),
286                "pclmulqdq" => Some(LLVMFeature::new("pclmul")),
287                "rdrand" => Some(LLVMFeature::new("rdrnd")),
288                "bmi1" => Some(LLVMFeature::new("bmi")),
289                "cmpxchg16b" => Some(LLVMFeature::new("cx16")),
290                "lahfsahf" => Some(LLVMFeature::new("sahf")),
291                // Enable the evex512 target feature if an avx512 target feature is enabled.
292                s if s.starts_with("avx512") && major < 22 => Some(LLVMFeature::with_dependencies(
293                    s,
294                    {
    let count = 0usize + 1usize;
    let mut vec = ::smallvec::SmallVec::new();
    if count <= vec.inline_size() {
        vec.push(TargetFeatureFoldStrength::EnableOnly("evex512"));
        vec
    } else {
        ::smallvec::SmallVec::from_vec(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                    [TargetFeatureFoldStrength::EnableOnly("evex512")])))
    }
}smallvec![TargetFeatureFoldStrength::EnableOnly("evex512")],
295                )),
296                "avx10.1" if major < 22 => Some(LLVMFeature::new("avx10.1-512")),
297                "avx10.2" if major < 22 => Some(LLVMFeature::new("avx10.2-512")),
298                "apxf" => Some(LLVMFeature::with_dependencies(
299                    "egpr",
300                    {
    let count =
        0usize + 1usize + 1usize + 1usize + 1usize + 1usize + 1usize + 1usize;
    let mut vec = ::smallvec::SmallVec::new();
    if count <= vec.inline_size() {
        vec.push(TargetFeatureFoldStrength::Both("push2pop2"));
        vec.push(TargetFeatureFoldStrength::Both("ppx"));
        vec.push(TargetFeatureFoldStrength::Both("ndd"));
        vec.push(TargetFeatureFoldStrength::Both("ccmp"));
        vec.push(TargetFeatureFoldStrength::Both("cf"));
        vec.push(TargetFeatureFoldStrength::Both("nf"));
        vec.push(TargetFeatureFoldStrength::Both("zu"));
        vec
    } else {
        ::smallvec::SmallVec::from_vec(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                    [TargetFeatureFoldStrength::Both("push2pop2"),
                            TargetFeatureFoldStrength::Both("ppx"),
                            TargetFeatureFoldStrength::Both("ndd"),
                            TargetFeatureFoldStrength::Both("ccmp"),
                            TargetFeatureFoldStrength::Both("cf"),
                            TargetFeatureFoldStrength::Both("nf"),
                            TargetFeatureFoldStrength::Both("zu")])))
    }
}smallvec![
301                        TargetFeatureFoldStrength::Both("push2pop2"),
302                        TargetFeatureFoldStrength::Both("ppx"),
303                        TargetFeatureFoldStrength::Both("ndd"),
304                        TargetFeatureFoldStrength::Both("ccmp"),
305                        TargetFeatureFoldStrength::Both("cf"),
306                        TargetFeatureFoldStrength::Both("nf"),
307                        TargetFeatureFoldStrength::Both("zu"),
308                    ],
309                )),
310                s => Some(LLVMFeature::new(s)),
311            }
312        }
313        _ => Some(LLVMFeature::new(s)),
314    }
315}
316
317/// Used to generate cfg variables and apply features.
318/// Must express features in the way Rust understands them.
319///
320/// We do not have to worry about RUSTC_SPECIFIC_FEATURES here, those are handled outside codegen.
321pub(crate) fn target_config(sess: &Session) -> TargetConfig {
322    let target_machine = create_informational_target_machine(sess, true);
323
324    let (unstable_target_features, target_features) = cfg_target_feature(
325        sess,
326        |feature| {
327            to_llvm_features(sess, feature)
328                .map(|f| SmallVec::<[&str; 2]>::from_iter(f.into_iter()))
329                .unwrap_or_default()
330        },
331        |feature| {
332            // This closure determines whether the target CPU has the feature according to LLVM. We do
333            // *not* consider the `-Ctarget-feature`s here, as that will be handled later in
334            // `cfg_target_feature`.
335            if let Some(feat) = to_llvm_features(sess, feature) {
336                // All the LLVM features this expands to must be enabled.
337                for llvm_feature in feat {
338                    let cstr = SmallCStr::new(llvm_feature);
339                    // `LLVMRustHasFeature` is moderately expensive. On targets with many
340                    // features (e.g. x86) these calls take a non-trivial fraction of runtime
341                    // when compiling very small programs.
342                    if !unsafe { llvm::LLVMRustHasFeature(target_machine.raw(), cstr.as_ptr()) } {
343                        return false;
344                    }
345                }
346                true
347            } else {
348                false
349            }
350        },
351    );
352
353    let mut cfg = TargetConfig {
354        target_features,
355        unstable_target_features,
356        has_reliable_f16: true,
357        has_reliable_f16_math: true,
358        has_reliable_f128: true,
359        has_reliable_f128_math: true,
360    };
361
362    update_target_reliable_float_cfg(sess, &mut cfg);
363    cfg
364}
365
366/// Determine whether or not experimental float types are reliable based on known bugs.
367fn update_target_reliable_float_cfg(sess: &Session, cfg: &mut TargetConfig) {
368    let target_arch = &sess.target.arch;
369    let target_os = &sess.target.options.os;
370    let target_env = &sess.target.options.env;
371    let target_abi = &sess.target.options.cfg_abi;
372    let target_pointer_width = sess.target.pointer_width;
373    let version = get_version();
374    let (major, _, _) = version;
375
376    cfg.has_reliable_f16 = match (target_arch, target_os) {
377        // Unsupported <https://github.com/llvm/llvm-project/issues/94434> (fixed in llvm22)
378        (Arch::Arm64EC, _) if major < 22 => false,
379        // MinGW ABI bugs <https://gcc.gnu.org/bugzilla/show_bug.cgi?id=115054>
380        (Arch::X86_64, Os::Windows) if *target_env == Env::Gnu && *target_abi != CfgAbi::Llvm => {
381            false
382        }
383        // Infinite recursion <https://github.com/llvm/llvm-project/issues/97981>
384        (Arch::CSky, _) if major < 22 => false, // (fixed in llvm22)
385        (Arch::PowerPC | Arch::PowerPC64, _) if major < 22 => false, // (fixed in llvm22)
386        (Arch::Sparc | Arch::Sparc64, _) if major < 22 => false, // (fixed in llvm22)
387        (Arch::Wasm32 | Arch::Wasm64, _) if major < 22 => false, // (fixed in llvm22)
388        // `f16` support only requires that symbols converting to and from `f32` are available. We
389        // provide these in `compiler-builtins`, so `f16` should be available on all platforms that
390        // do not have other ABI issues or LLVM crashes.
391        _ => true,
392    };
393
394    cfg.has_reliable_f128 = match (target_arch, target_os) {
395        // Unsupported https://github.com/llvm/llvm-project/issues/121122
396        (Arch::AmdGpu, _) => false,
397        // Unsupported <https://github.com/llvm/llvm-project/issues/94434>
398        (Arch::Arm64EC, _) => false,
399        // Selection bug <https://github.com/llvm/llvm-project/issues/95471>. This issue is closed
400        // but basic math still does not work.
401        (Arch::Nvptx64, _) => false,
402        // ABI bugs <https://github.com/rust-lang/rust/issues/125109> et al. (full
403        // list at <https://github.com/rust-lang/rust/issues/116909>)
404        (Arch::PowerPC | Arch::PowerPC64, _) => false,
405        // ABI unsupported  <https://github.com/llvm/llvm-project/issues/41838> (fixed in llvm22)
406        (Arch::Sparc, _) if major < 22 => false,
407        // MinGW ABI bugs <https://gcc.gnu.org/bugzilla/show_bug.cgi?id=115054>
408        (Arch::X86_64, Os::Windows) if *target_env == Env::Gnu && *target_abi != CfgAbi::Llvm => {
409            false
410        }
411        // There are no known problems on other platforms, so the only requirement is that symbols
412        // are available. `compiler-builtins` provides all symbols required for core `f128`
413        // support, so this should work for everything else.
414        _ => true,
415    };
416
417    // Assume that working `f16` means working `f16` math for most platforms, since
418    // operations just go through `f32`.
419    cfg.has_reliable_f16_math = cfg.has_reliable_f16;
420
421    cfg.has_reliable_f128_math = match (target_arch, target_os) {
422        // LLVM lowers `fp128` math to `long double` symbols even on platforms where
423        // `long double` is not IEEE binary128. See
424        // <https://github.com/llvm/llvm-project/issues/44744>.
425        //
426        // This rules out anything that doesn't have `long double` = `binary128`; <= 32 bits
427        // (ld is `f64`), anything other than Linux (Windows and MacOS use `f64`), and `x86`
428        // (ld is 80-bit extended precision).
429        //
430        // musl does not implement the symbols required for f128 math at all.
431        _ if *target_env == Env::Musl => false,
432        (Arch::X86_64, _) => false,
433        (_, Os::Linux) if target_pointer_width == 64 => true,
434        _ => false,
435    } && cfg.has_reliable_f128;
436}
437
438pub(crate) fn print_version() {
439    let (major, minor, patch) = get_version();
440    {
    ::std::io::_print(format_args!("LLVM version: {0}.{1}.{2}\n", major,
            minor, patch));
};println!("LLVM version: {major}.{minor}.{patch}");
441}
442
443pub(crate) fn get_version() -> (u32, u32, u32) {
444    // Can be called without initializing LLVM
445    unsafe {
446        (llvm::LLVMRustVersionMajor(), llvm::LLVMRustVersionMinor(), llvm::LLVMRustVersionPatch())
447    }
448}
449
450pub(crate) fn print_passes() {
451    // Can be called without initializing LLVM
452    unsafe {
453        llvm::LLVMRustPrintPasses();
454    }
455}
456
457fn llvm_target_features(tm: &llvm::TargetMachine) -> Vec<(&str, &str)> {
458    let len = unsafe { llvm::LLVMRustGetTargetFeaturesCount(tm) };
459    let mut ret = Vec::with_capacity(len);
460    for i in 0..len {
461        unsafe {
462            let mut feature = ptr::null();
463            let mut desc = ptr::null();
464            llvm::LLVMRustGetTargetFeature(tm, i, &mut feature, &mut desc);
465            if feature.is_null() || desc.is_null() {
466                ::rustc_middle::util::bug::bug_fmt(format_args!("LLVM returned a `null` target feature string"));bug!("LLVM returned a `null` target feature string");
467            }
468            let feature = CStr::from_ptr(feature).to_str().unwrap_or_else(|e| {
469                ::rustc_middle::util::bug::bug_fmt(format_args!("LLVM returned a non-utf8 feature string: {0}",
        e));bug!("LLVM returned a non-utf8 feature string: {}", e);
470            });
471            let desc = CStr::from_ptr(desc).to_str().unwrap_or_else(|e| {
472                ::rustc_middle::util::bug::bug_fmt(format_args!("LLVM returned a non-utf8 feature string: {0}",
        e));bug!("LLVM returned a non-utf8 feature string: {}", e);
473            });
474            ret.push((feature, desc));
475        }
476    }
477    ret
478}
479
480pub(crate) fn print(req: &PrintRequest, out: &mut String, sess: &Session) {
481    require_inited();
482    let tm = create_informational_target_machine(sess, false);
483    match req.kind {
484        PrintKind::TargetCPUs => print_target_cpus(sess, tm.raw(), out),
485        PrintKind::TargetFeatures => print_target_features(sess, tm.raw(), out),
486        _ => ::rustc_middle::util::bug::bug_fmt(format_args!("rustc_codegen_llvm can\'t handle print request: {0:?}",
        req))bug!("rustc_codegen_llvm can't handle print request: {:?}", req),
487    }
488}
489
490fn print_target_cpus(sess: &Session, tm: &llvm::TargetMachine, out: &mut String) {
491    let cpu_names = llvm::build_string(|s| unsafe {
492        llvm::LLVMRustPrintTargetCPUs(&tm, s);
493    })
494    .unwrap();
495
496    struct Cpu<'a> {
497        cpu_name: &'a str,
498        remark: String,
499    }
500    // Compare CPU against current target to label the default.
501    let target_cpu = handle_native(&sess.target.cpu);
502    let make_remark = |cpu_name| {
503        if cpu_name == target_cpu {
504            // FIXME(#132514): This prints the LLVM target string, which can be
505            // different from the Rust target string. Is that intended?
506            let target = &sess.target.llvm_target;
507            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(" - This is the default target CPU for the current build target (currently {0}).",
                target))
    })format!(
508                " - This is the default target CPU for the current build target (currently {target})."
509            )
510        } else {
511            "".to_owned()
512        }
513    };
514    let mut cpus = cpu_names
515        .lines()
516        .filter(|cpu_name| {
517            !sess.target.unsupported_cpus.contains(&std::borrow::Cow::Borrowed(*cpu_name))
518        })
519        .map(|cpu_name| Cpu { cpu_name, remark: make_remark(cpu_name) })
520        .collect::<VecDeque<_>>();
521
522    // Only print the "native" entry when host and target are the same arch,
523    // since otherwise it could be wrong or misleading.
524    if sess.host.arch == sess.target.arch {
525        let host = get_host_cpu_name();
526        cpus.push_front(Cpu {
527            cpu_name: "native",
528            remark: ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(" - Select the CPU of the current host (currently {0}).",
                host))
    })format!(" - Select the CPU of the current host (currently {host})."),
529        });
530    }
531
532    let max_name_width = cpus.iter().map(|cpu| cpu.cpu_name.len()).max().unwrap_or(0);
533    out.write_fmt(format_args!("Available CPUs for this target:\n"))writeln!(out, "Available CPUs for this target:").unwrap();
534    for Cpu { cpu_name, remark } in cpus {
535        // Only pad the CPU name if there's a remark to print after it.
536        let width = if remark.is_empty() { 0 } else { max_name_width };
537        out.write_fmt(format_args!("    {0:<1$}{2}\n", cpu_name, width, remark))writeln!(out, "    {cpu_name:<width$}{remark}").unwrap();
538    }
539}
540
541fn print_target_features(sess: &Session, tm: &llvm::TargetMachine, out: &mut String) {
542    let mut llvm_target_features = llvm_target_features(tm);
543    let mut known_llvm_target_features = FxHashSet::<&'static str>::default();
544    let mut rustc_target_features = sess
545        .target
546        .rust_target_features()
547        .iter()
548        .filter_map(|(feature, gate, _implied)| {
549            if !gate.in_cfg() {
550                // Only list (experimentally) supported features.
551                return None;
552            }
553            // LLVM asserts that these are sorted. LLVM and Rust both use byte comparison for these
554            // strings.
555            let llvm_feature = to_llvm_features(sess, *feature)?.llvm_feature_name;
556            let desc =
557                match llvm_target_features.binary_search_by_key(&llvm_feature, |(f, _d)| f).ok() {
558                    Some(index) => {
559                        known_llvm_target_features.insert(llvm_feature);
560                        llvm_target_features[index].1
561                    }
562                    None => "",
563                };
564
565            Some((*feature, desc))
566        })
567        .collect::<Vec<_>>();
568
569    // Since we add this at the end ...
570    rustc_target_features.extend_from_slice(&[(
571        "crt-static",
572        "Enables C Run-time Libraries to be statically linked",
573    )]);
574    // ... we need to sort the list again.
575    rustc_target_features.sort();
576
577    llvm_target_features.retain(|(f, _d)| !known_llvm_target_features.contains(f));
578
579    let max_feature_len = llvm_target_features
580        .iter()
581        .chain(rustc_target_features.iter())
582        .map(|(feature, _desc)| feature.len())
583        .max()
584        .unwrap_or(0);
585
586    out.write_fmt(format_args!("Features supported by rustc for this target:\n"))writeln!(out, "Features supported by rustc for this target:").unwrap();
587    for (feature, desc) in &rustc_target_features {
588        out.write_fmt(format_args!("    {0:1$} - {2}.\n", feature, max_feature_len,
        desc))writeln!(out, "    {feature:max_feature_len$} - {desc}.").unwrap();
589    }
590    out.write_fmt(format_args!("\nCode-generation features supported by LLVM for this target:\n"))writeln!(out, "\nCode-generation features supported by LLVM for this target:").unwrap();
591    for (feature, desc) in &llvm_target_features {
592        out.write_fmt(format_args!("    {0:1$} - {2}.\n", feature, max_feature_len,
        desc))writeln!(out, "    {feature:max_feature_len$} - {desc}.").unwrap();
593    }
594    if llvm_target_features.is_empty() {
595        out.write_fmt(format_args!("    Target features listing is not supported by this LLVM version.\n"))writeln!(out, "    Target features listing is not supported by this LLVM version.")
596            .unwrap();
597    }
598    out.write_fmt(format_args!("\nUse +feature to enable a feature, or -feature to disable it.\n"))writeln!(out, "\nUse +feature to enable a feature, or -feature to disable it.").unwrap();
599    out.write_fmt(format_args!("For example, rustc -C target-cpu=mycpu -C target-feature=+feature1,-feature2\n\n"))writeln!(out, "For example, rustc -C target-cpu=mycpu -C target-feature=+feature1,-feature2\n")
600        .unwrap();
601    out.write_fmt(format_args!("Code-generation features cannot be used in cfg or #[target_feature],\n"))writeln!(out, "Code-generation features cannot be used in cfg or #[target_feature],").unwrap();
602    out.write_fmt(format_args!("and may be renamed or removed in a future version of LLVM or rustc.\n\n"))writeln!(out, "and may be renamed or removed in a future version of LLVM or rustc.\n").unwrap();
603}
604
605/// Returns the host CPU name, according to LLVM.
606fn get_host_cpu_name() -> &'static str {
607    let mut len = 0;
608    // SAFETY: The underlying C++ global function returns a `StringRef` that
609    // isn't tied to any particular backing buffer, so it must be 'static.
610    let slice: &'static [u8] = unsafe {
611        let ptr = llvm::LLVMRustGetHostCPUName(&mut len);
612        if !!ptr.is_null() {
    ::core::panicking::panic("assertion failed: !ptr.is_null()")
};assert!(!ptr.is_null());
613        slice::from_raw_parts(ptr, len)
614    };
615    str::from_utf8(slice).expect("host CPU name should be UTF-8")
616}
617
618/// If the given string is `"native"`, returns the host CPU name according to
619/// LLVM. Otherwise, the string is returned as-is.
620fn handle_native(cpu_name: &str) -> &str {
621    match cpu_name {
622        "native" => get_host_cpu_name(),
623        _ => cpu_name,
624    }
625}
626
627pub(crate) fn target_cpu(sess: &Session) -> &str {
628    let cpu_name = sess.opts.cg.target_cpu.as_deref().unwrap_or_else(|| &sess.target.cpu);
629    handle_native(cpu_name)
630}
631
632/// The target features for compiler flags other than `-Ctarget-features`.
633fn llvm_features_by_flags(sess: &Session, features: &mut Vec<String>) {
634    if wants_wasm_eh(sess) && sess.panic_strategy() == PanicStrategy::Unwind {
635        features.push("+exception-handling".into());
636    }
637
638    target_features::retpoline_features_by_flags(sess, features);
639    target_features::sanitizer_features_by_flags(sess, features);
640
641    // -Zfixed-x18
642    if sess.opts.unstable_opts.fixed_x18 {
643        if sess.target.arch != Arch::AArch64 {
644            sess.dcx().emit_fatal(errors::FixedX18InvalidArch { arch: sess.target.arch.desc() });
645        } else {
646            features.push("+reserve-x18".into());
647        }
648    }
649}
650
651/// The list of LLVM features computed from CLI flags (`-Ctarget-cpu`, `-Ctarget-feature`,
652/// `--target` and similar).
653pub(crate) fn global_llvm_features(sess: &Session, only_base_features: bool) -> Vec<String> {
654    // Features that come earlier are overridden by conflicting features later in the string.
655    // Typically we'll want more explicit settings to override the implicit ones, so:
656    //
657    // * Features from -Ctarget-cpu=*; are overridden by [^1]
658    // * Features implied by --target; are overridden by
659    // * Features from -Ctarget-feature; are overridden by
660    // * function specific features.
661    //
662    // [^1]: target-cpu=native is handled here, other target-cpu values are handled implicitly
663    // through LLVM TargetMachine implementation.
664    //
665    // FIXME(nagisa): it isn't clear what's the best interaction between features implied by
666    // `-Ctarget-cpu` and `--target` are. On one hand, you'd expect CLI arguments to always
667    // override anything that's implicit, so e.g. when there's no `--target` flag, features implied
668    // the host target are overridden by `-Ctarget-cpu=*`. On the other hand, what about when both
669    // `--target` and `-Ctarget-cpu=*` are specified? Both then imply some target features and both
670    // flags are specified by the user on the CLI. It isn't as clear-cut which order of precedence
671    // should be taken in cases like these.
672    let mut features = ::alloc::vec::Vec::new()vec![];
673
674    // -Ctarget-cpu=native
675    match sess.opts.cg.target_cpu {
676        Some(ref s) if s == "native" => {
677            // We have already figured out the actual CPU name with `LLVMRustGetHostCPUName` and set
678            // that for LLVM, so the features implied by that CPU name will be available everywhere.
679            // However, that is not sufficient: e.g. `skylake` alone is not sufficient to tell if
680            // some of the instructions are available or not. So we have to also explicitly ask for
681            // the exact set of features available on the host, and enable all of them.
682            let features_string = unsafe {
683                let ptr = llvm::LLVMGetHostCPUFeatures();
684                let features_string = if !ptr.is_null() {
685                    CStr::from_ptr(ptr)
686                        .to_str()
687                        .unwrap_or_else(|e| {
688                            ::rustc_middle::util::bug::bug_fmt(format_args!("LLVM returned a non-utf8 features string: {0}",
        e));bug!("LLVM returned a non-utf8 features string: {}", e);
689                        })
690                        .to_owned()
691                } else {
692                    ::rustc_middle::util::bug::bug_fmt(format_args!("could not allocate host CPU features, LLVM returned a `null` string"));bug!("could not allocate host CPU features, LLVM returned a `null` string");
693                };
694
695                llvm::LLVMDisposeMessage(ptr);
696
697                features_string
698            };
699            if !features_string.is_empty() {
700                features.extend(features_string.split(',').map(String::from));
701            }
702        }
703        Some(_) | None => {}
704    };
705
706    let mut extend_backend_features = |feature: &str, enable: bool| {
707        let enable_disable = if enable { '+' } else { '-' };
708        // We run through `to_llvm_features` when
709        // passing requests down to LLVM. This means that all in-language
710        // features also work on the command line instead of having two
711        // different names when the LLVM name and the Rust name differ.
712        let Some(llvm_feature) = to_llvm_features(sess, feature) else { return };
713
714        features.extend(
715            std::iter::once(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}{1}", enable_disable,
                llvm_feature.llvm_feature_name))
    })format!("{}{}", enable_disable, llvm_feature.llvm_feature_name)).chain(
716                llvm_feature.dependencies.into_iter().filter_map(move |feat| {
717                    match (enable, feat) {
718                        (_, TargetFeatureFoldStrength::Both(f))
719                        | (true, TargetFeatureFoldStrength::EnableOnly(f)) => {
720                            Some(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}{1}", enable_disable, f))
    })format!("{enable_disable}{f}"))
721                        }
722                        _ => None,
723                    }
724                }),
725            ),
726        );
727    };
728
729    // Features implied by an implicit or explicit `--target`.
730    target_features::target_spec_to_backend_features(sess, &mut extend_backend_features);
731
732    // -Ctarget-features
733    if !only_base_features {
734        target_features::flag_to_backend_features(sess, extend_backend_features);
735    }
736
737    // We add this in the "base target" so that these show up in `sess.unstable_target_features`.
738    llvm_features_by_flags(sess, &mut features);
739
740    features
741}
742
743pub(crate) fn tune_cpu(sess: &Session) -> Option<&str> {
744    let name = sess.opts.unstable_opts.tune_cpu.as_ref()?;
745    Some(handle_native(name))
746}
747
748pub(crate) fn target_has_mnemonic(sess: &Session, mnemonic: &str) -> bool {
749    require_inited();
750    let tm = create_informational_target_machine(sess, false);
751    let cstr = SmallCStr::new(mnemonic);
752    unsafe { llvm::LLVMRustTargetHasMnemonic(tm.raw(), cstr.as_ptr()) }
753}