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};
78use libc::c_int;
9use rustc_codegen_ssa::back::versioned_llvm_target;
10use rustc_codegen_ssa::base::wants_wasm_eh;
11use rustc_codegen_ssa::target_features::internal_target_features;
12use rustc_codegen_ssa::{TargetConfig, target_features};
13use rustc_data_structures::fx::FxHashSet;
14use rustc_data_structures::small_c_str::SmallCStr;
15use rustc_fs_util::path_to_c_string;
16use rustc_session::config::{NATIVE_CPU, PrintKind, PrintRequest};
17use rustc_session::{EarlySession, Session};
18use rustc_span::bug;
19use rustc_target::spec::{
20Arch, CfgAbi, Env, MergeFunctions, Os, PanicStrategy, SmallDataThresholdSupport, Target,
21};
22use smallvec::{SmallVec, smallvec};
2324use crate::back::owned_mc_subtarget_info::OwnedMCSubtargetInfo;
25use crate::back::write::{create_informational_target_machine, llvm_err};
26use crate::{diagnostics, llvm};
2728static INIT: Once = Once::new();
2930pub(crate) fn init(sess: &EarlySession) {
31unsafe {
32// Before we touch LLVM, make sure that multithreading is enabled.
33if !llvm::LLVMIsMultithreaded().is_true() {
34bug_impl(None, format_args!("LLVM compiled without support for threads"),
Location::caller());bug!("LLVM compiled without support for threads");
35 }
36INIT.call_once(|| {
37configure_llvm(sess);
38 });
39 }
40}
4142fn require_inited() {
43if !INIT.is_completed() {
44bug_impl(None, format_args!("LLVM is not initialized"), Location::caller());bug!("LLVM is not initialized");
45 }
46}
4748unsafe fn configure_llvm(sess: &EarlySession) {
49let n_args = sess.opts.cg.llvm_args.len() + sess.target.llvm_args.len();
50let mut llvm_c_strs = Vec::with_capacity(n_args + 1);
51let mut llvm_args = Vec::with_capacity(n_args + 1);
5253// Check to ensure we're running against the correct LLVM version.
54unsafe {
55let (llvm_major, llvm_minor, llvm_patch) = get_version();
56let expected_version = llvm::LLVMRustVersionMajor();
57if llvm_major != expected_version {
58sess.dcx().emit_fatal(diagnostics::LlvmVersionMismatch {
59expected_version,
60llvm_major,
61llvm_minor,
62llvm_patch,
63 dll_loc: &match rustc_session::filesearch::dll_path(llvm::LLVMGetVersionas *mut _)
64 {
65Ok(path) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" at {0}", path.display()))
})format!(" at {}", path.display()),
66Err(_) => String::new(),
67 },
68 })
69 }
70 }
7172unsafe {
73 llvm::LLVMRustInstallErrorHandlers();
74 }
75// On Windows, an LLVM assertion will open an Abort/Retry/Ignore dialog
76 // box for the purpose of launching a debugger. However, on CI this will
77 // cause it to hang until it times out, which can take several hours.
78if std::env::var_os("CI").is_some() {
79unsafe {
80 llvm::LLVMRustDisableSystemDialogsOnCrash();
81 }
82 }
8384fn llvm_arg_to_arg_name(full_arg: &str) -> &str {
85full_arg.trim().split(|c: char| c == '=' || c.is_whitespace()).next().unwrap_or("")
86 }
8788let cg_opts = sess.opts.cg.llvm_args.iter().map(AsRef::as_ref);
89let tg_opts = sess.target.llvm_args.iter().map(AsRef::as_ref);
90// Target-spec args are passed to LLVM before user `-Cllvm-args`. LLVM's
91 // `cl::opt` parser is last-wins, so this lets `-Cllvm-args=...` override
92 // a value already set in the target spec (e.g. `-wasm-use-legacy-eh`).
93let sess_args = tg_opts.chain(cg_opts);
9495let user_specified_args: FxHashSet<_> =
96sess_args.clone().map(|s| llvm_arg_to_arg_name(s)).filter(|s| !s.is_empty()).collect();
9798 {
99// This adds the given argument to LLVM. Unless `force` is true
100 // user specified arguments are *not* overridden.
101let mut add = |arg: &str, force: bool| {
102if force || !user_specified_args.contains(llvm_arg_to_arg_name(arg)) {
103let s = CString::new(arg).unwrap();
104llvm_args.push(s.as_ptr());
105llvm_c_strs.push(s);
106 }
107 };
108// Set the llvm "program name" to make usage and invalid argument messages more clear.
109add("rustc -Cllvm-args=\"...\" with", true);
110if sess.opts.unstable_opts.time_llvm_passes {
111add("-time-passes", false);
112 }
113if sess.opts.unstable_opts.print_llvm_passes {
114add("-debug-pass=Structure", false);
115 }
116if sess.target.generate_arange_section
117 && !sess.opts.unstable_opts.no_generate_arange_section
118 {
119add("-generate-arange-section", false);
120 }
121122match sess.opts.unstable_opts.merge_functions.unwrap_or(sess.target.merge_functions) {
123 MergeFunctions::Disabled | MergeFunctions::Trampolines => {}
124 MergeFunctions::Aliases => {
125add("-mergefunc-use-aliases", false);
126 }
127 }
128129if wants_wasm_eh(&sess.target) {
130add("-wasm-enable-eh", false);
131 }
132133// HACK(eddyb) LLVM inserts `llvm.assume` calls to preserve align attributes
134 // during inlining. Unfortunately these may block other optimizations.
135add("-preserve-alignment-assumptions-during-inlining=false", false);
136137// Use non-zero `import-instr-limit` multiplier for cold callsites.
138add("-import-cold-multiplier=0.1", false);
139140if sess.print_llvm_stats() || sess.print_llvm_stats_json().is_some() {
141add("-stats", false);
142 }
143144for arg in sess_args {
145 add(&(*arg), true);
146 }
147148match (
149sess.opts.unstable_opts.small_data_threshold,
150sess.target.small_data_threshold_support(),
151 ) {
152// Set up the small-data optimization limit for architectures that use
153 // an LLVM argument to control this.
154(Some(threshold), SmallDataThresholdSupport::LlvmArg(arg)) => {
155add(&::alloc::__export::must_use({
::alloc::fmt::format(format_args!("--{0}={1}", arg, threshold))
})format!("--{arg}={threshold}"), false)
156 }
157_ => (),
158 };
159 }
160161if sess.opts.unstable_opts.llvm_time_trace {
162unsafe { llvm::LLVMRustTimeTraceProfilerInitialize() };
163 }
164165 rustc_llvm::initialize_available_targets();
166167unsafe { llvm::LLVMRustSetLLVMOptions(llvm_args.len() as c_int, llvm_args.as_ptr()) };
168}
169170pub(crate) fn time_trace_profiler_finish(file_name: &Path) {
171unsafe {
172let file_name = path_to_c_string(file_name);
173 llvm::LLVMRustTimeTraceProfilerFinish(file_name.as_ptr());
174 }
175}
176177enum TargetFeatureFoldStrength<'a> {
178// The feature is only tied when enabling the feature, disabling
179 // this feature shouldn't disable the tied feature.
180EnableOnly(&'a str),
181// The feature is tied for both enabling and disabling this feature.
182Both(&'a str),
183}
184185impl<'a> TargetFeatureFoldStrength<'a> {
186fn as_str(&self) -> &'a str {
187match self {
188 TargetFeatureFoldStrength::EnableOnly(feat) => feat,
189 TargetFeatureFoldStrength::Both(feat) => feat,
190 }
191 }
192}
193194pub(crate) struct LLVMFeature<'a> {
195 llvm_feature_name: &'a str,
196 dependencies: SmallVec<[TargetFeatureFoldStrength<'a>; 1]>,
197}
198199impl<'a> LLVMFeature<'a> {
200fn new(llvm_feature_name: &'a str) -> Self {
201Self { llvm_feature_name, dependencies: SmallVec::new() }
202 }
203204fn with_dependencies(
205 llvm_feature_name: &'a str,
206 dependencies: SmallVec<[TargetFeatureFoldStrength<'a>; 1]>,
207 ) -> Self {
208Self { llvm_feature_name, dependencies }
209 }
210}
211212impl<'a> IntoIteratorfor LLVMFeature<'a> {
213type Item = &'a str;
214type IntoIter = impl Iterator<Item = &'a str>;
215216fn into_iter(self) -> Self::IntoIter {
217let dependencies = self.dependencies.into_iter().map(|feat| feat.as_str());
218 std::iter::once(self.llvm_feature_name).chain(dependencies)
219 }
220}
221222/// Convert a Rust feature name to an LLVM feature name. Returning `None` means the
223/// feature should be skipped, usually because it is not supported by the current
224/// LLVM version.
225///
226/// WARNING: the features after applying `to_llvm_features` must be known
227/// to LLVM or the feature detection code will walk past the end of the feature
228/// array, leading to crashes.
229///
230/// To find a list of LLVM's names, see llvm-project/llvm/lib/Target/{ARCH}/*.td
231/// where `{ARCH}` is the architecture name. Look for instances of `SubtargetFeature`.
232///
233/// Check the current rustc fork of LLVM in the repo at
234/// <https://github.com/rust-lang/llvm-project/>. The commit in use can be found via the
235/// `llvm-project` submodule in <https://github.com/rust-lang/rust/tree/HEAD/src> Though note that
236/// Rust can also be build with an external precompiled version of LLVM which might lead to failures
237/// if the oldest tested / supported LLVM version doesn't yet support the relevant intrinsics.
238pub(crate) fn to_llvm_features<'a>(target: &Target, s: &'a str) -> Option<LLVMFeature<'a>> {
239let (major, _, _) = get_version();
240match target.arch {
241 Arch::AArch64 | Arch::Arm64EC => {
242match s {
243"rcpc2" => Some(LLVMFeature::new("rcpc-immo")),
244"dpb" => Some(LLVMFeature::new("ccpp")),
245"dpb2" => Some(LLVMFeature::new("ccdp")),
246"frintts" => Some(LLVMFeature::new("fptoint")),
247"fcma" => Some(LLVMFeature::new("complxnum")),
248"pmuv3" => Some(LLVMFeature::new("perfmon")),
249"paca" => Some(LLVMFeature::new("pauth")),
250"pacg" => Some(LLVMFeature::new("pauth")),
251"flagm2" => Some(LLVMFeature::new("altnzcv")),
252// Rust ties fp and neon together.
253"neon" => Some(LLVMFeature::with_dependencies(
254"neon",
255{
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")],
256 )),
257// In LLVM neon implicitly enables fp, but we manually enable
258 // neon when a feature only implicitly enables fp
259"fhm" => Some(LLVMFeature::new("fp16fml")),
260"fp16" => Some(LLVMFeature::new("fullfp16")),
261// Filter out features that are not supported by the current LLVM version
262"fpmr" => None, // only existed in 18
263 // Withdrawn by ARM; removed from LLVM in 22
264"tme" if major >= 22 => None,
265 s => Some(LLVMFeature::new(s)),
266 }
267 }
268 Arch::Arm => match s {
269"fp16" => Some(LLVMFeature::new("fullfp16")),
270 s => Some(LLVMFeature::new(s)),
271 },
272 Arch::Bpf => match s {
273"allows-misaligned-mem-access" if major < 22 => None,
274 s => Some(LLVMFeature::new(s)),
275 },
276 Arch::Nvptx64 => match s {
277"sm_101" if major >= 24 => Some(LLVMFeature::new("sm_110")),
278"sm_101a" if major >= 24 => Some(LLVMFeature::new("sm_110a")),
279"sm_101f" if major >= 24 => Some(LLVMFeature::new("sm_110f")),
280 s => Some(LLVMFeature::new(s)),
281 },
282// Filter out features that are not supported by the current LLVM version
283Arch::PowerPC | Arch::PowerPC64 => match s {
284"power8-crypto" => Some(LLVMFeature::new("crypto")),
285 s => Some(LLVMFeature::new(s)),
286 },
287 Arch::RiscV32 | Arch::RiscV64 => match s {
288// Filter out Rust-specific *virtual* target feature
289"zkne_or_zknd" => None,
290 s => Some(LLVMFeature::new(s)),
291 },
292 Arch::Sparc | Arch::Sparc64 => match s {
293"leoncasa" => Some(LLVMFeature::new("hasleoncasa")),
294 s => Some(LLVMFeature::new(s)),
295 },
296 Arch::Wasm32 | Arch::Wasm64 => match s {
297"gc" if major < 22 => None,
298 s => Some(LLVMFeature::new(s)),
299 },
300 Arch::X86 | Arch::X86_64 => {
301match s {
302"sse4.2" => Some(LLVMFeature::with_dependencies(
303"sse4.2",
304{
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")],
305 )),
306"pclmulqdq" => Some(LLVMFeature::new("pclmul")),
307"rdrand" => Some(LLVMFeature::new("rdrnd")),
308"bmi1" => Some(LLVMFeature::new("bmi")),
309"cmpxchg16b" => Some(LLVMFeature::new("cx16")),
310"lahfsahf" => Some(LLVMFeature::new("sahf")),
311// Enable the evex512 target feature if an avx512 target feature is enabled.
312s if s.starts_with("avx512") && major < 22 => Some(LLVMFeature::with_dependencies(
313s,
314{
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")],
315 )),
316"avx10.1" if major < 22 => Some(LLVMFeature::new("avx10.1-512")),
317"avx10.2" if major < 22 => Some(LLVMFeature::new("avx10.2-512")),
318"apxf" => Some(LLVMFeature::with_dependencies(
319"egpr",
320{
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![
321 TargetFeatureFoldStrength::Both("push2pop2"),
322 TargetFeatureFoldStrength::Both("ppx"),
323 TargetFeatureFoldStrength::Both("ndd"),
324 TargetFeatureFoldStrength::Both("ccmp"),
325 TargetFeatureFoldStrength::Both("cf"),
326 TargetFeatureFoldStrength::Both("nf"),
327 TargetFeatureFoldStrength::Both("zu"),
328 ],
329 )),
330 s => Some(LLVMFeature::new(s)),
331 }
332 }
333_ => Some(LLVMFeature::new(s)),
334 }
335}
336337/// Used to generate cfg variables and apply features.
338/// Must express features in the way Rust understands them.
339///
340/// We do not have to worry about RUSTC_SPECIFIC_FEATURES here, those are handled outside codegen.
341pub(crate) fn target_config(sess: &EarlySession) -> TargetConfig {
342require_inited();
343let target_features = global_llvm_features(sess, /* for_cfg */ true);
344345let triple = SmallCStr::new(&versioned_llvm_target(sess));
346let cpu = SmallCStr::new(target_cpu(sess));
347let features = CString::new(target_features.join(",")).unwrap();
348let mc_subtarget_info = OwnedMCSubtargetInfo::new(&triple, &cpu, &features)
349 .unwrap_or_else(|err| llvm_err(sess.dcx(), err));
350351let internal_target_features = internal_target_features(
352sess,
353 |feature| {
354to_llvm_features(&sess.target, feature)
355 .map(|f| SmallVec::<[&str; 2]>::from_iter(f.into_iter()))
356 .unwrap_or_default()
357 },
358 |feature| {
359// This closure determines whether the target CPU has the feature according to LLVM. We
360 // do *not* consider the `-Ctarget-feature`s here (that's why we passed `for_cfg: true`
361 // to `global_llvm_features` above) because that will be handled later in
362 // `internal_target_features`.
363if let Some(feat) = to_llvm_features(&sess.target, feature) {
364// All the LLVM features this expands to must be enabled.
365for llvm_feature in feat {
366let cstr = SmallCStr::new(llvm_feature);
367// `has_feature` is moderately expensive. On targets with many
368 // features (e.g. x86) these calls take a non-trivial fraction of runtime
369 // when compiling very small programs.
370if !mc_subtarget_info.has_feature(&cstr) {
371return false;
372 }
373 }
374true
375} else {
376false
377}
378 },
379 );
380381let mut cfg = TargetConfig {
382internal_target_features,
383 has_reliable_f16: true,
384 has_reliable_f16_math: true,
385 has_reliable_f128: true,
386 has_reliable_f128_math: true,
387 };
388389update_target_reliable_float_cfg(&sess.target, &mut cfg);
390cfg391}
392393/// Determine whether or not experimental float types are reliable based on known bugs.
394fn update_target_reliable_float_cfg(target: &Target, cfg: &mut TargetConfig) {
395let target_arch = &target.arch;
396let target_os = &target.options.os;
397let target_env = &target.options.env;
398let target_abi = &target.options.cfg_abi;
399let target_pointer_width = target.pointer_width;
400let version = get_version();
401let (major, _, _) = version;
402403cfg.has_reliable_f16 = match (target_arch, target_os) {
404// Unsupported <https://github.com/llvm/llvm-project/issues/94434> (fixed in llvm22)
405(Arch::Arm64EC, _) if major < 22 => false,
406// MinGW ABI bugs <https://gcc.gnu.org/bugzilla/show_bug.cgi?id=115054> resolved in GCC 16
407 // but our toolchain hasn't been updated.
408(Arch::X86_64, Os::Windows) if *target_env == Env::Gnu && *target_abi != CfgAbi::Llvm => {
409false
410}
411// Infinite recursion <https://github.com/llvm/llvm-project/issues/97981>
412(Arch::CSky, _) if major < 22 => false, // (fixed in llvm22)
413(Arch::PowerPC | Arch::PowerPC64, _) if major < 22 => false, // (fixed in llvm22)
414(Arch::Sparc | Arch::Sparc64, _) if major < 22 => false, // (fixed in llvm22)
415(Arch::Wasm32 | Arch::Wasm64, _) if major < 22 => false, // (fixed in llvm22)
416 // `f16` support only requires that symbols converting to and from `f32` are available. We
417 // provide these in `compiler-builtins`, so `f16` should be available on all platforms that
418 // do not have other ABI issues or LLVM crashes.
419_ => true,
420 };
421422cfg.has_reliable_f128 = match (target_arch, target_os) {
423// Unsupported https://github.com/llvm/llvm-project/issues/121122
424(Arch::AmdGpu, _) => false,
425 (Arch::Arm64EC, _) if major < 23 => false, // (fixed in llvm23)
426 // Selection bug <https://github.com/llvm/llvm-project/issues/95471>. This issue is closed
427 // but basic math still does not work.
428(Arch::Nvptx64, _) => false,
429// ABI bugs <https://github.com/rust-lang/rust/issues/125109> et al. (full
430 // list at <https://github.com/rust-lang/rust/issues/116909>)
431(Arch::PowerPC | Arch::PowerPC64, _) => false,
432// ABI unsupported <https://github.com/llvm/llvm-project/issues/41838> (fixed in llvm22)
433(Arch::Sparc, _) if major < 22 => false,
434// MinGW ABI bugs <https://gcc.gnu.org/bugzilla/show_bug.cgi?id=115054> (fixed in llvm23)
435(Arch::X86_64, Os::Windows)
436if *target_env == Env::Gnu && *target_abi != CfgAbi::Llvm && major < 23 =>
437 {
438false
439}
440// There are no known problems on other platforms, so the only requirement is that symbols
441 // are available. `compiler-builtins` provides all symbols required for core `f128`
442 // support, so this should work for everything else.
443_ => true,
444 };
445446// Assume that working `f16` means working `f16` math for most platforms, since
447 // operations just go through `f32`.
448cfg.has_reliable_f16_math = cfg.has_reliable_f16;
449450cfg.has_reliable_f128_math = match (target_arch, target_os) {
451// LLVM lowers `fp128` math to `long double` symbols even on platforms where
452 // `long double` is not IEEE binary128. See
453 // <https://github.com/llvm/llvm-project/issues/44744>.
454 //
455 // This rules out anything that doesn't have `long double` = `binary128`; <= 32 bits
456 // (ld is `f64`), anything other than Linux (Windows and MacOS use `f64`), and `x86`
457 // (ld is 80-bit extended precision).
458 //
459 // musl does not implement the symbols required for f128 math at all.
460_ if *target_env == Env::Musl => false,
461 (Arch::X86_64, _) => false,
462 (_, Os::Linux) if target_pointer_width == 64 => true,
463_ => false,
464 } && cfg.has_reliable_f128;
465}
466467pub(crate) fn print_version() {
468let (major, minor, patch) = get_version();
469{
::std::io::_print(format_args!("LLVM version: {0}.{1}.{2}\n", major,
minor, patch));
};println!("LLVM version: {major}.{minor}.{patch}");
470}
471472/// Returns the version of LLVM that we are actually linked to at runtime.
473pub(crate) fn get_version() -> (u32, u32, u32) {
474let mut llvm_major = 0;
475let mut llvm_minor = 0;
476let mut llvm_patch = 0;
477 llvm::LLVMGetVersion(&mut llvm_major, &mut llvm_minor, &mut llvm_patch);
478 (llvm_major, llvm_minor, llvm_patch)
479}
480481pub(crate) fn print_passes() {
482// Can be called without initializing LLVM
483unsafe {
484 llvm::LLVMRustPrintPasses();
485 }
486}
487488fn llvm_target_features(tm: &llvm::TargetMachine) -> Vec<(&str, &str)> {
489let len = unsafe { llvm::LLVMRustGetTargetFeaturesCount(tm) };
490let mut ret = Vec::with_capacity(len);
491for i in 0..len {
492unsafe {
493let mut feature = ptr::null();
494let mut desc = ptr::null();
495 llvm::LLVMRustGetTargetFeature(tm, i, &mut feature, &mut desc);
496if feature.is_null() || desc.is_null() {
497bug_impl(None, format_args!("LLVM returned a `null` target feature string"),
Location::caller());bug!("LLVM returned a `null` target feature string");
498 }
499let feature = CStr::from_ptr(feature).to_str().unwrap_or_else(|e| {
500bug_impl(None,
format_args!("LLVM returned a non-utf8 feature string: {0}", e),
Location::caller());bug!("LLVM returned a non-utf8 feature string: {}", e);
501 });
502let desc = CStr::from_ptr(desc).to_str().unwrap_or_else(|e| {
503bug_impl(None,
format_args!("LLVM returned a non-utf8 feature string: {0}", e),
Location::caller());bug!("LLVM returned a non-utf8 feature string: {}", e);
504 });
505 ret.push((feature, desc));
506 }
507 }
508ret509}
510511pub(crate) fn print(req: &PrintRequest, out: &mut String, sess: &Session) {
512require_inited();
513let tm = create_informational_target_machine(sess);
514match req.kind {
515 PrintKind::TargetCPUs => print_target_cpus(sess, tm.raw(), out),
516 PrintKind::TargetFeatures => print_target_features(sess, tm.raw(), out),
517_ => bug_impl(None,
format_args!("rustc_codegen_llvm can\'t handle print request: {0:?}",
req), Location::caller())bug!("rustc_codegen_llvm can't handle print request: {:?}", req),
518 }
519}
520521fn print_target_cpus(sess: &Session, tm: &llvm::TargetMachine, out: &mut String) {
522let cpu_names = llvm::build_string(|s| unsafe {
523 llvm::LLVMRustPrintTargetCPUs(&tm, s);
524 })
525 .unwrap();
526527struct Cpu<'a> {
528 cpu_name: &'a str,
529 remark: String,
530 }
531// Compare CPU against current target to label the default. Do not print it if
532 // `need_explicit_cpu` is set, because in that case the concept of default makes less sense.
533let target_cpu = handle_native(&sess.target.cpu);
534let make_remark = |cpu_name| {
535if cpu_name == target_cpu && !sess.target.need_explicit_cpu {
536// FIXME(#132514): This prints the LLVM target string, which can be
537 // different from the Rust target string. Is that intended?
538let target = &sess.target.llvm_target;
539::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" - This is the default target CPU for the current build target (currently {0}).",
target))
})format!(
540" - This is the default target CPU for the current build target (currently {target})."
541)542 } else {
543"".to_owned()
544 }
545 };
546let mut cpus = cpu_names547 .lines()
548 .filter(|cpu_name| {
549 !sess.target.unsupported_cpus.contains(&std::borrow::Cow::Borrowed(*cpu_name))
550 })
551 .map(|cpu_name| Cpu { cpu_name, remark: make_remark(cpu_name) })
552 .collect::<VecDeque<_>>();
553554// Only print the "native" entry when host and target are the same arch,
555 // since otherwise it could be wrong or misleading.
556 // Also do not print it if `requires_consistent_cpu` is set, because in this case
557 // "native" would be rejected.
558if sess.host.arch == sess.target.arch && !sess.target.requires_consistent_cpu {
559let host = get_host_cpu_name();
560cpus.push_front(Cpu {
561 cpu_name: NATIVE_CPU,
562 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})."),
563 });
564 }
565566let max_name_width = cpus.iter().map(|cpu| cpu.cpu_name.len()).max().unwrap_or(0);
567out.write_fmt(format_args!("Available CPUs for this target:\n"))writeln!(out, "Available CPUs for this target:").unwrap();
568for Cpu { cpu_name, remark } in cpus {
569// Only pad the CPU name if there's a remark to print after it.
570let width = if remark.is_empty() { 0 } else { max_name_width };
571out.write_fmt(format_args!(" {0:<1$}{2}\n", cpu_name, width, remark))writeln!(out, " {cpu_name:<width$}{remark}").unwrap();
572 }
573}
574575fn print_target_features(sess: &Session, tm: &llvm::TargetMachine, out: &mut String) {
576let mut llvm_target_features = llvm_target_features(tm);
577let mut known_llvm_target_features = FxHashSet::<&'static str>::default();
578let mut rustc_target_features = sess579 .target
580 .rust_target_features()
581 .iter()
582 .filter_map(|(feature, gate, _implied)| {
583if !gate.in_cfg() {
584// Only list (experimentally) supported features.
585return None;
586 }
587// LLVM asserts that these are sorted. LLVM and Rust both use byte comparison for these
588 // strings.
589let llvm_feature = to_llvm_features(&sess.target, *feature)?.llvm_feature_name;
590let desc =
591match llvm_target_features.binary_search_by_key(&llvm_feature, |(f, _d)| f).ok() {
592Some(index) => {
593known_llvm_target_features.insert(llvm_feature);
594llvm_target_features[index].1
595}
596None => "",
597 };
598599Some((*feature, desc))
600 })
601 .collect::<Vec<_>>();
602603// Since we add this at the end ...
604rustc_target_features.extend_from_slice(&[(
605"crt-static",
606"Enables C Run-time Libraries to be statically linked",
607 )]);
608// ... we need to sort the list again.
609rustc_target_features.sort();
610611llvm_target_features.retain(|(f, _d)| !known_llvm_target_features.contains(f));
612613let max_feature_len = llvm_target_features614 .iter()
615 .chain(rustc_target_features.iter())
616 .map(|(feature, _desc)| feature.len())
617 .max()
618 .unwrap_or(0);
619620out.write_fmt(format_args!("Features supported by rustc for this target:\n"))writeln!(out, "Features supported by rustc for this target:").unwrap();
621for (feature, desc) in &rustc_target_features {
622out.write_fmt(format_args!(" {0:1$} - {2}.\n", feature, max_feature_len,
desc))writeln!(out, " {feature:max_feature_len$} - {desc}.").unwrap();
623 }
624out.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();
625for (feature, desc) in &llvm_target_features {
626out.write_fmt(format_args!(" {0:1$} - {2}.\n", feature, max_feature_len,
desc))writeln!(out, " {feature:max_feature_len$} - {desc}.").unwrap();
627 }
628if llvm_target_features.is_empty() {
629out.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.")630 .unwrap();
631 }
632out.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();
633out.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")634 .unwrap();
635out.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();
636out.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();
637}
638639/// Returns the host CPU name, according to LLVM.
640fn get_host_cpu_name() -> &'static str {
641let mut len = 0;
642// SAFETY: The underlying C++ global function returns a `StringRef` that
643 // isn't tied to any particular backing buffer, so it must be 'static.
644let slice: &'static [u8] = unsafe {
645let ptr = llvm::LLVMRustGetHostCPUName(&mut len);
646if !!ptr.is_null() {
::core::panicking::panic("assertion failed: !ptr.is_null()")
};assert!(!ptr.is_null());
647 slice::from_raw_parts(ptr, len)
648 };
649 str::from_utf8(slice).expect("host CPU name should be UTF-8")
650}
651652/// If the given string is `"native"`, returns the host CPU name according to
653/// LLVM. Otherwise, the string is returned as-is.
654fn handle_native(cpu_name: &str) -> &str {
655match cpu_name {
656NATIVE_CPU => get_host_cpu_name(),
657_ => cpu_name,
658 }
659}
660661pub(crate) fn target_cpu(sess: &EarlySession) -> &str {
662let cpu_name = sess.opts.cg.target_cpu.as_deref().unwrap_or_else(|| &sess.target.cpu);
663handle_native(cpu_name)
664}
665666/// The target features for compiler flags other than `-Ctarget-features`.
667fn llvm_features_by_flags(sess: &EarlySession, features: &mut Vec<String>) {
668if wants_wasm_eh(&sess.target) && sess.panic_strategy() == PanicStrategy::Unwind {
669features.push("+exception-handling".into());
670 }
671672 target_features::retpoline_features_by_flags(sess, features);
673 target_features::sanitizer_features_by_flags(sess, features);
674675// -Zfixed-x18
676if sess.opts.unstable_opts.fixed_x18 {
677if sess.target.arch != Arch::AArch64 {
678sess.dcx()
679 .emit_fatal(diagnostics::FixedX18InvalidArch { arch: sess.target.arch.desc() });
680 } else {
681features.push("+reserve-x18".into());
682 }
683 }
684}
685686/// The list of LLVM features computed from CLI flags (`-Ctarget-cpu`, `-Ctarget-feature`,
687/// `--target` and similar).
688///
689/// If `for_cfg` is `true` then we are assembling the feature list for the purpose of populating
690/// [`rustc_codegen_ssa::TargetConfig`] based on what LLVM actually enables in this configuration.
691/// `-Ctarget-feature` should be ignored in that case since it is already processed separately.
692pub(crate) fn global_llvm_features(sess: &EarlySession, for_cfg: bool) -> Vec<String> {
693// Features that come earlier are overridden by conflicting features later in the string.
694 // Typically we'll want more explicit settings to override the implicit ones, so:
695 //
696 // * Features from -Ctarget-cpu=*; are overridden by [^1]
697 // * Features implied by --target; are overridden by
698 // * Features from -Ctarget-feature; are overridden by
699 // * function specific features.
700 //
701 // [^1]: target-cpu=native is handled here, other target-cpu values are handled implicitly
702 // through LLVM TargetMachine implementation.
703 //
704 // FIXME(nagisa): it isn't clear what's the best interaction between features implied by
705 // `-Ctarget-cpu` and `--target` are. On one hand, you'd expect CLI arguments to always
706 // override anything that's implicit, so e.g. when there's no `--target` flag, features implied
707 // the host target are overridden by `-Ctarget-cpu=*`. On the other hand, what about when both
708 // `--target` and `-Ctarget-cpu=*` are specified? Both then imply some target features and both
709 // flags are specified by the user on the CLI. It isn't as clear-cut which order of precedence
710 // should be taken in cases like these.
711let mut features = ::alloc::vec::Vec::new()vec![];
712713// -Ctarget-cpu=native
714match sess.opts.cg.target_cpu {
715Some(ref s) if s == NATIVE_CPU => {
716// We have already figured out the actual CPU name with `LLVMRustGetHostCPUName` and set
717 // that for LLVM, so the features implied by that CPU name will be available everywhere.
718 // However, that is not sufficient: e.g. `skylake` alone is not sufficient to tell if
719 // some of the instructions are available or not. So we have to also explicitly ask for
720 // the exact set of features available on the host, and enable all of them.
721let features_string = unsafe {
722let ptr = llvm::LLVMGetHostCPUFeatures();
723let features_string = if !ptr.is_null() {
724CStr::from_ptr(ptr)
725 .to_str()
726 .unwrap_or_else(|e| {
727bug_impl(None,
format_args!("LLVM returned a non-utf8 features string: {0}", e),
Location::caller());bug!("LLVM returned a non-utf8 features string: {}", e);
728 })
729 .to_owned()
730 } else {
731bug_impl(None,
format_args!("could not allocate host CPU features, LLVM returned a `null` string"),
Location::caller());bug!("could not allocate host CPU features, LLVM returned a `null` string");
732 };
733734 llvm::LLVMDisposeMessage(ptr);
735736features_string737 };
738if !features_string.is_empty() {
739features.extend(features_string.split(',').map(String::from));
740 }
741 }
742Some(_) | None => {}
743 };
744745let mut extend_backend_features = |feature: &str, enable: bool| {
746let enable_disable = if enable { '+' } else { '-' };
747// We run through `to_llvm_features` when
748 // passing requests down to LLVM. This means that all in-language
749 // features also work on the command line instead of having two
750 // different names when the LLVM name and the Rust name differ.
751let Some(llvm_feature) = to_llvm_features(&sess.target, feature) else { return };
752753features.extend(
754 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(
755llvm_feature.dependencies.into_iter().filter_map(move |feat| {
756match (enable, feat) {
757 (_, TargetFeatureFoldStrength::Both(f))
758 | (true, TargetFeatureFoldStrength::EnableOnly(f)) => {
759Some(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1}", enable_disable, f))
})format!("{enable_disable}{f}"))
760 }
761_ => None,
762 }
763 }),
764 ),
765 );
766 };
767768// Features implied by an implicit or explicit `--target`.
769target_features::target_spec_to_backend_features(sess, &mut extend_backend_features);
770771// -Ctarget-features. Skipped for `cfg` as there we parse -Ctarget-features directly instead of
772 // going via an LLVM target machine (which avoids accidentally picking up LLVM-level target
773 // feature implications that we do not want).
774if !for_cfg {
775 target_features::flag_to_backend_features(sess, extend_backend_features);
776 }
777778// `-C` flags that map to LLVM target features.
779 // We need to include them even with `only_base_features` as this is used to populate
780 // `sess.internal_target_features` where we very much want them to be present (e.g. the inline
781 // asm logic uses that to check which registers may be used).
782llvm_features_by_flags(sess, &mut features);
783784// `-Zllvm-target-features`, all the way at the end to overwrite everything.
785 // Should be picked up by `cfg` (e.g. if someone enables AVX this way).
786for feature in sess.opts.unstable_opts.llvm_target_feature.split(',') {
787if feature.is_empty() {
788continue;
789 }
790if feature.starts_with('+') || feature.starts_with('-') {
791 features.push(feature.to_owned());
792 } else {
793// LLVM seems to silently ignore entries without leading `+`/`-`. Let's emit a warning
794 // to avoid confusion. But only emit this warning once, under `for_cfg`.
795if for_cfg {
796 sess.dcx().emit_warn(diagnostics::UnknownLlvmTargetFeaturePrefix { feature });
797 }
798 }
799 }
800801features802}
803804pub(crate) fn tune_cpu(sess: &Session) -> Option<&str> {
805let name = sess.opts.unstable_opts.tune_cpu.as_ref()?;
806Some(handle_native(name))
807}
808809pub(crate) fn target_has_mnemonic(sess: &Session, mnemonic: &str) -> bool {
810require_inited();
811let tm = create_informational_target_machine(sess);
812let cstr = SmallCStr::new(mnemonic);
813unsafe { llvm::LLVMRustTargetHasMnemonic(tm.raw(), cstr.as_ptr()) }
814}