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_abi::Endian;
10use rustc_codegen_ssa::back::versioned_llvm_target;
11use rustc_codegen_ssa::base::wants_wasm_eh;
12use rustc_codegen_ssa::target_features::internal_target_features;
13use rustc_codegen_ssa::{TargetConfig, target_features};
14use rustc_data_structures::fx::FxHashSet;
15use rustc_data_structures::small_c_str::SmallCStr;
16use rustc_fs_util::path_to_c_string;
17use rustc_session::config::{NATIVE_CPU, PrintKind, PrintRequest};
18use rustc_session::{EarlySession, Session};
19use rustc_span::{bug, sym};
20use rustc_target::spec::{
21Arch, CfgAbi, Env, MergeFunctions, Os, PanicStrategy, SmallDataThresholdSupport, Target,
22};
23use smallvec::{SmallVec, smallvec};
2425use crate::back::owned_mc_subtarget_info::OwnedMCSubtargetInfo;
26use crate::back::write::{create_informational_target_machine, llvm_err};
27use crate::{diagnostics, llvm};
2829static INIT: Once = Once::new();
3031pub(crate) fn init(sess: &EarlySession) {
32unsafe {
33// Before we touch LLVM, make sure that multithreading is enabled.
34if !llvm::LLVMIsMultithreaded().is_true() {
35::rustc_span::macros::bug_impl(None,
format_args!("LLVM compiled without support for threads"),
Location::caller());bug!("LLVM compiled without support for threads");
36 }
37INIT.call_once(|| {
38configure_llvm(sess);
39 });
40 }
41}
4243fn require_inited() {
44if !INIT.is_completed() {
45::rustc_span::macros::bug_impl(None, format_args!("LLVM is not initialized"),
Location::caller());bug!("LLVM is not initialized");
46 }
47}
4849unsafe fn configure_llvm(sess: &EarlySession) {
50let n_args = sess.opts.cg.llvm_args.len() + sess.target.llvm_args.len();
51let mut llvm_c_strs = Vec::with_capacity(n_args + 1);
52let mut llvm_args = Vec::with_capacity(n_args + 1);
5354// Check to ensure we're running against the correct LLVM version.
55unsafe {
56let (llvm_major, llvm_minor, llvm_patch) = get_version();
57let expected_version = llvm::LLVMRustVersionMajor();
58if llvm_major != expected_version {
59sess.dcx().emit_fatal(diagnostics::LlvmVersionMismatch {
60expected_version,
61llvm_major,
62llvm_minor,
63llvm_patch,
64 dll_loc: &match rustc_session::filesearch::dll_path(llvm::LLVMGetVersionas *mut _)
65 {
66Ok(path) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" at {0}", path.display()))
})format!(" at {}", path.display()),
67Err(_) => String::new(),
68 },
69 })
70 }
71 }
7273unsafe {
74 llvm::LLVMRustInstallErrorHandlers();
75 }
76// On Windows, an LLVM assertion will open an Abort/Retry/Ignore dialog
77 // box for the purpose of launching a debugger. However, on CI this will
78 // cause it to hang until it times out, which can take several hours.
79if std::env::var_os("CI").is_some() {
80unsafe {
81 llvm::LLVMRustDisableSystemDialogsOnCrash();
82 }
83 }
8485fn llvm_arg_to_arg_name(full_arg: &str) -> &str {
86full_arg.trim().split(|c: char| c == '=' || c.is_whitespace()).next().unwrap_or("")
87 }
8889let cg_opts = sess.opts.cg.llvm_args.iter().map(AsRef::as_ref);
90let tg_opts = sess.target.llvm_args.iter().map(AsRef::as_ref);
91// Target-spec args are passed to LLVM before user `-Cllvm-args`. LLVM's
92 // `cl::opt` parser is last-wins, so this lets `-Cllvm-args=...` override
93 // a value already set in the target spec (e.g. `-wasm-use-legacy-eh`).
94let sess_args = tg_opts.chain(cg_opts);
9596let user_specified_args: FxHashSet<_> =
97sess_args.clone().map(|s| llvm_arg_to_arg_name(s)).filter(|s| !s.is_empty()).collect();
9899 {
100// This adds the given argument to LLVM. Unless `force` is true
101 // user specified arguments are *not* overridden.
102let mut add = |arg: &str, force: bool| {
103if force || !user_specified_args.contains(llvm_arg_to_arg_name(arg)) {
104let s = CString::new(arg).unwrap();
105llvm_args.push(s.as_ptr());
106llvm_c_strs.push(s);
107 }
108 };
109// Set the llvm "program name" to make usage and invalid argument messages more clear.
110add("rustc -Cllvm-args=\"...\" with", true);
111if sess.opts.unstable_opts.time_llvm_passes {
112add("-time-passes", false);
113 }
114if sess.opts.unstable_opts.print_llvm_passes {
115add("-debug-pass=Structure", false);
116 }
117if sess.target.generate_arange_section
118 && !sess.opts.unstable_opts.no_generate_arange_section
119 {
120add("-generate-arange-section", false);
121 }
122123match sess.merge_functions() {
124 MergeFunctions::Disabled | MergeFunctions::Trampolines => {}
125 MergeFunctions::Aliases => {
126add("-mergefunc-use-aliases", false);
127 }
128 }
129130if get_version() < (24, 0, 0) && wants_wasm_eh(&sess.target) {
131add("-wasm-enable-eh", false);
132 }
133134// HACK(eddyb) LLVM inserts `llvm.assume` calls to preserve align attributes
135 // during inlining. Unfortunately these may block other optimizations.
136add("-preserve-alignment-assumptions-during-inlining=false", false);
137138// Use non-zero `import-instr-limit` multiplier for cold callsites.
139add("-import-cold-multiplier=0.1", false);
140141if sess.print_llvm_stats() || sess.print_llvm_stats_json().is_some() {
142add("-stats", false);
143 }
144145for arg in sess_args {
146 add(&(*arg), true);
147 }
148149match (
150sess.opts.unstable_opts.small_data_threshold,
151sess.target.small_data_threshold_support(),
152 ) {
153// Set up the small-data optimization limit for architectures that use
154 // an LLVM argument to control this.
155(Some(threshold), SmallDataThresholdSupport::LlvmArg(arg)) => {
156add(&::alloc::__export::must_use({
::alloc::fmt::format(format_args!("--{0}={1}", arg, threshold))
})format!("--{arg}={threshold}"), false)
157 }
158_ => (),
159 };
160 }
161162if sess.opts.unstable_opts.llvm_time_trace {
163unsafe { llvm::LLVMRustTimeTraceProfilerInitialize() };
164 }
165166 rustc_llvm::initialize_available_targets();
167168unsafe { llvm::LLVMRustSetLLVMOptions(llvm_args.len() as c_int, llvm_args.as_ptr()) };
169}
170171pub(crate) fn time_trace_profiler_finish(file_name: &Path) {
172unsafe {
173let file_name = path_to_c_string(file_name);
174 llvm::LLVMRustTimeTraceProfilerFinish(file_name.as_ptr());
175 }
176}
177178enum TargetFeatureFoldStrength<'a> {
179// The feature is only tied when enabling the feature, disabling
180 // this feature shouldn't disable the tied feature.
181EnableOnly(&'a str),
182// The feature is tied for both enabling and disabling this feature.
183Both(&'a str),
184}
185186impl<'a> TargetFeatureFoldStrength<'a> {
187fn as_str(&self) -> &'a str {
188match self {
189 TargetFeatureFoldStrength::EnableOnly(feat) => feat,
190 TargetFeatureFoldStrength::Both(feat) => feat,
191 }
192 }
193}
194195pub(crate) struct LLVMFeature<'a> {
196 llvm_feature_name: &'a str,
197 dependencies: SmallVec<[TargetFeatureFoldStrength<'a>; 1]>,
198}
199200impl<'a> LLVMFeature<'a> {
201fn new(llvm_feature_name: &'a str) -> Self {
202Self { llvm_feature_name, dependencies: SmallVec::new() }
203 }
204205fn with_dependencies(
206 llvm_feature_name: &'a str,
207 dependencies: SmallVec<[TargetFeatureFoldStrength<'a>; 1]>,
208 ) -> Self {
209Self { llvm_feature_name, dependencies }
210 }
211}
212213impl<'a> IntoIteratorfor LLVMFeature<'a> {
214type Item = &'a str;
215type IntoIter = impl Iterator<Item = &'a str>;
216217fn into_iter(self) -> Self::IntoIter {
218let dependencies = self.dependencies.into_iter().map(|feat| feat.as_str());
219 std::iter::once(self.llvm_feature_name).chain(dependencies)
220 }
221}
222223/// Convert a Rust feature name to an LLVM feature name. Returning `None` means the
224/// feature should be skipped, usually because it is not supported by the current
225/// LLVM version.
226///
227/// WARNING: the features after applying `to_llvm_features` must be known
228/// to LLVM or the feature detection code will walk past the end of the feature
229/// array, leading to crashes.
230///
231/// To find a list of LLVM's names, see llvm-project/llvm/lib/Target/{ARCH}/*.td
232/// where `{ARCH}` is the architecture name. Look for instances of `SubtargetFeature`.
233///
234/// Check the current rustc fork of LLVM in the repo at
235/// <https://github.com/rust-lang/llvm-project/>. The commit in use can be found via the
236/// `llvm-project` submodule in <https://github.com/rust-lang/rust/tree/HEAD/src> Though note that
237/// Rust can also be build with an external precompiled version of LLVM which might lead to failures
238/// if the oldest tested / supported LLVM version doesn't yet support the relevant intrinsics.
239pub(crate) fn to_llvm_features<'a>(target: &Target, s: &'a str) -> Option<LLVMFeature<'a>> {
240let (major, _, _) = get_version();
241match target.arch {
242 Arch::AArch64 | Arch::Arm64EC => {
243match s {
244"rcpc2" => Some(LLVMFeature::new("rcpc-immo")),
245"dpb" => Some(LLVMFeature::new("ccpp")),
246"dpb2" => Some(LLVMFeature::new("ccdp")),
247"frintts" => Some(LLVMFeature::new("fptoint")),
248"fcma" => Some(LLVMFeature::new("complxnum")),
249"pmuv3" => Some(LLVMFeature::new("perfmon")),
250"paca" => Some(LLVMFeature::new("pauth")),
251"pacg" => Some(LLVMFeature::new("pauth")),
252"flagm2" => Some(LLVMFeature::new("altnzcv")),
253// Rust ties fp and neon together.
254"neon" => Some(LLVMFeature::with_dependencies(
255"neon",
256{
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")],
257 )),
258// In LLVM neon implicitly enables fp, but we manually enable
259 // neon when a feature only implicitly enables fp
260"fhm" => Some(LLVMFeature::new("fp16fml")),
261"fp16" => Some(LLVMFeature::new("fullfp16")),
262// Filter out features that are not supported by the current LLVM version
263"fpmr" => None, // only existed in 18
264 // Withdrawn by ARM; removed from LLVM in 22
265"tme" if major >= 22 => None,
266 s => Some(LLVMFeature::new(s)),
267 }
268 }
269 Arch::Arm => match s {
270"fp16" => Some(LLVMFeature::new("fullfp16")),
271 s => Some(LLVMFeature::new(s)),
272 },
273 Arch::Bpf => match s {
274"allows-misaligned-mem-access" if major < 22 => None,
275 s => Some(LLVMFeature::new(s)),
276 },
277 Arch::Nvptx64 => match s {
278"sm_101" if major >= 24 => Some(LLVMFeature::new("sm_110")),
279"sm_101a" if major >= 24 => Some(LLVMFeature::new("sm_110a")),
280"sm_101f" if major >= 24 => Some(LLVMFeature::new("sm_110f")),
281 s => Some(LLVMFeature::new(s)),
282 },
283// Filter out features that are not supported by the current LLVM version
284Arch::PowerPC | Arch::PowerPC64 => match s {
285"power8-crypto" => Some(LLVMFeature::new("crypto")),
286 s => Some(LLVMFeature::new(s)),
287 },
288 Arch::RiscV32 | Arch::RiscV64 => match s {
289// Filter out Rust-specific *virtual* target feature
290"zkne_or_zknd" => None,
291 s => Some(LLVMFeature::new(s)),
292 },
293 Arch::Sparc | Arch::Sparc64 => match s {
294"leoncasa" => Some(LLVMFeature::new("hasleoncasa")),
295 s => Some(LLVMFeature::new(s)),
296 },
297 Arch::Wasm32 | Arch::Wasm64 => match s {
298"gc" if major < 22 => None,
299 s => Some(LLVMFeature::new(s)),
300 },
301 Arch::X86 | Arch::X86_64 => {
302match s {
303"sse4.2" => Some(LLVMFeature::with_dependencies(
304"sse4.2",
305{
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")],
306 )),
307"pclmulqdq" => Some(LLVMFeature::new("pclmul")),
308"rdrand" => Some(LLVMFeature::new("rdrnd")),
309"bmi1" => Some(LLVMFeature::new("bmi")),
310"cmpxchg16b" => Some(LLVMFeature::new("cx16")),
311"lahfsahf" => Some(LLVMFeature::new("sahf")),
312// Enable the evex512 target feature if an avx512 target feature is enabled.
313s if s.starts_with("avx512") && major < 22 => Some(LLVMFeature::with_dependencies(
314s,
315{
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")],
316 )),
317"avx10.1" if major < 22 => Some(LLVMFeature::new("avx10.1-512")),
318"avx10.2" if major < 22 => Some(LLVMFeature::new("avx10.2-512")),
319"apxf" => Some(LLVMFeature::with_dependencies(
320"egpr",
321{
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![
322 TargetFeatureFoldStrength::Both("push2pop2"),
323 TargetFeatureFoldStrength::Both("ppx"),
324 TargetFeatureFoldStrength::Both("ndd"),
325 TargetFeatureFoldStrength::Both("ccmp"),
326 TargetFeatureFoldStrength::Both("cf"),
327 TargetFeatureFoldStrength::Both("nf"),
328 TargetFeatureFoldStrength::Both("zu"),
329 ],
330 )),
331 s => Some(LLVMFeature::new(s)),
332 }
333 }
334_ => Some(LLVMFeature::new(s)),
335 }
336}
337338/// Used to generate cfg variables and apply features.
339/// Must express features in the way Rust understands them.
340///
341/// We do not have to worry about RUSTC_SPECIFIC_FEATURES here, those are handled outside codegen.
342pub(crate) fn target_config(sess: &EarlySession) -> TargetConfig {
343require_inited();
344let target_features = global_llvm_features(sess, /* for_cfg */ true);
345346let triple = SmallCStr::new(&versioned_llvm_target(sess));
347let cpu = SmallCStr::new(target_cpu(sess));
348let features = CString::new(target_features.join(",")).unwrap();
349let mc_subtarget_info = OwnedMCSubtargetInfo::new(&triple, &cpu, &features)
350 .unwrap_or_else(|err| llvm_err(sess.dcx(), err));
351352let internal_target_features = internal_target_features(
353sess,
354 |feature| {
355to_llvm_features(&sess.target, feature)
356 .map(|f| SmallVec::<[&str; 2]>::from_iter(f.into_iter()))
357 .unwrap_or_default()
358 },
359 |feature| {
360// This closure determines whether the target CPU has the feature according to LLVM. We
361 // do *not* consider the `-Ctarget-feature`s here (that's why we passed `for_cfg: true`
362 // to `global_llvm_features` above) because that will be handled later in
363 // `internal_target_features`.
364if let Some(feat) = to_llvm_features(&sess.target, feature)
365 && mc_subtarget_info.has_features(feat)
366 {
367true
368} else {
369false
370}
371 },
372 );
373374let mut cfg = TargetConfig {
375internal_target_features,
376 has_reliable_f16: true,
377 has_reliable_f16_math: true,
378 has_reliable_f16b: true,
379 has_reliable_f128: true,
380 has_reliable_f128_math: true,
381 };
382383update_target_reliable_float_cfg(&sess.target, &mut cfg);
384cfg385}
386387/// Determine whether or not experimental float types are reliable based on known bugs.
388fn update_target_reliable_float_cfg(target: &Target, cfg: &mut TargetConfig) {
389let target_arch = &target.arch;
390let target_os = &target.options.os;
391let target_endian = &target.options.endian;
392let target_env = &target.options.env;
393let target_abi = &target.options.cfg_abi;
394let target_pointer_width = target.pointer_width;
395let version = get_version();
396let (major, _, _) = version;
397398cfg.has_reliable_f16 = match (target_arch, target_os) {
399// Unsupported <https://github.com/llvm/llvm-project/issues/94434> (fixed in llvm22)
400(Arch::Arm64EC, _) if major < 22 => false,
401// MinGW ABI bugs <https://gcc.gnu.org/bugzilla/show_bug.cgi?id=115054> resolved in GCC 16
402 // but our toolchain hasn't been updated.
403(Arch::X86_64, Os::Windows) if *target_env == Env::Gnu && *target_abi != CfgAbi::Llvm => {
404false
405}
406// Infinite recursion <https://github.com/llvm/llvm-project/issues/97981>
407(Arch::CSky, _) if major < 22 => false, // (fixed in llvm22)
408(Arch::PowerPC | Arch::PowerPC64, _) if major < 22 => false, // (fixed in llvm22)
409(Arch::Sparc | Arch::Sparc64, _) if major < 22 => false, // (fixed in llvm22)
410(Arch::Wasm32 | Arch::Wasm64, _) if major < 22 => false, // (fixed in llvm22)
411 // `f16` support only requires that symbols converting to and from `f32` are available. We
412 // provide these in `compiler-builtins`, so `f16` should be available on all platforms that
413 // do not have other ABI issues or LLVM crashes.
414_ => true,
415 };
416417// The heuristic for evaluating to true is twofold, namely;
418 //
419 // 1. Can LLVM compile an IR snippet containing `fpext bfloat %<var> to float`
420 // 2. Does the documentation indicate `bf16` support, can be seen in the
421 // tracking issue; <https://github.com/rust-lang/rust/issues/160630>
422cfg.has_reliable_f16b = match (target_arch, target_os) {
423// This is similar to <https://github.com/llvm/llvm-project/issues/94434>, however
424 // does not work until LLVM 23 on Windows.
425(Arch::Arm64EC, _) => major >= 23,
426 (Arch::AArch64, _) => true,
427// FIXME(f16b) until <https://github.com/llvm/llvm-project/issues/97896>
428 // is resolved the below do not have a reliable `f16b`, on a widening
429 // path a call to `__truncsfbf2` is emitted. Or when using architectural
430 // extensions a non-portable narrowing instruction is emitted.
431(Arch::X86_64 | Arch::RiscV64 | Arch::LoongArch64, _) => false,
432_ => false,
433 };
434435cfg.has_reliable_f128 = match (target_arch, target_os) {
436// Unsupported https://github.com/llvm/llvm-project/issues/121122
437(Arch::AmdGpu, _) => false,
438 (Arch::Arm64EC, _) if major < 23 => false, // (fixed in llvm23)
439 // Selection bug <https://github.com/llvm/llvm-project/issues/95471>. This issue is closed
440 // but basic math still does not work.
441(Arch::Nvptx64, _) => false,
442// ABI/LLVM bugs:
443 // - with +vsx <https://github.com/llvm/llvm-project/pull/216613>
444 // - without +vsx <https://github.com/rust-lang/rust/issues/125109>
445(Arch::PowerPC, _) => false,
446// AIX does not support f128.
447(Arch::PowerPC64, Os::Aix) => false,
448// ABI bugs on BE without +vsx <https://github.com/rust-lang/rust/issues/125109>.
449(Arch::PowerPC64, _) => cfg.internal_target_features.contains(&sym::vsx),
450// ABI unsupported <https://github.com/llvm/llvm-project/issues/41838> (fixed in llvm22)
451(Arch::Sparc, _) if major < 22 => false,
452// MinGW ABI bugs <https://gcc.gnu.org/bugzilla/show_bug.cgi?id=115054> (fixed in llvm23)
453(Arch::X86_64, Os::Windows)
454if *target_env == Env::Gnu && *target_abi != CfgAbi::Llvm && major < 23 =>
455 {
456false
457}
458// There are no known problems on other platforms, so the only requirement is that symbols
459 // are available. `compiler-builtins` provides all symbols required for core `f128`
460 // support, so this should work for everything else.
461_ => true,
462 };
463464// Assume that working `f16` means working `f16` math for most platforms, since
465 // operations just go through `f32`.
466cfg.has_reliable_f16_math = cfg.has_reliable_f16;
467468cfg.has_reliable_f128_math = match (target_arch, target_os) {
469// LLVM lowers `fp128` math to `long double` symbols even on platforms where
470 // `long double` is not IEEE binary128. See
471 // <https://github.com/llvm/llvm-project/issues/44744>.
472 //
473 // This rules out anything that doesn't have `long double` = `binary128`; <= 32 bits
474 // (ld is `f64`), anything other than Linux (Windows and MacOS use `f64`), and `x86`
475 // (ld is 80-bit extended precision).
476 //
477 // On big-endian powerpc the symbol selection is correct, despite __ibmf128 being
478 // long double on the target, but the f128 symbols are not defined.
479 //
480 // musl does not implement the symbols required for f128 math at all.
481_ if *target_env == Env::Musl => false,
482 (Arch::X86_64, _) => false,
483 (Arch::PowerPC | Arch::PowerPC64, _) if *target_endian == Endian::Big => false,
484 (_, Os::Linux) if target_pointer_width == 64 => true,
485_ => false,
486 } && cfg.has_reliable_f128;
487}
488489pub(crate) fn print_version() {
490let (major, minor, patch) = get_version();
491{
::std::io::_print(format_args!("LLVM version: {0}.{1}.{2}\n", major,
minor, patch));
};println!("LLVM version: {major}.{minor}.{patch}");
492}
493494/// Returns the version of LLVM that we are actually linked to at runtime.
495pub(crate) fn get_version() -> (u32, u32, u32) {
496let mut llvm_major = 0;
497let mut llvm_minor = 0;
498let mut llvm_patch = 0;
499 llvm::LLVMGetVersion(&mut llvm_major, &mut llvm_minor, &mut llvm_patch);
500 (llvm_major, llvm_minor, llvm_patch)
501}
502503pub(crate) fn print_passes() {
504// Can be called without initializing LLVM
505unsafe {
506 llvm::LLVMRustPrintPasses();
507 }
508}
509510fn llvm_target_features(tm: &llvm::TargetMachine) -> Vec<(&str, &str)> {
511let len = unsafe { llvm::LLVMRustGetTargetFeaturesCount(tm) };
512let mut ret = Vec::with_capacity(len);
513for i in 0..len {
514unsafe {
515let mut feature = ptr::null();
516let mut desc = ptr::null();
517 llvm::LLVMRustGetTargetFeature(tm, i, &mut feature, &mut desc);
518if feature.is_null() || desc.is_null() {
519::rustc_span::macros::bug_impl(None,
format_args!("LLVM returned a `null` target feature string"),
Location::caller());bug!("LLVM returned a `null` target feature string");
520 }
521let feature = CStr::from_ptr(feature).to_str().unwrap_or_else(|e| {
522::rustc_span::macros::bug_impl(None,
format_args!("LLVM returned a non-utf8 feature string: {0}", e),
Location::caller());bug!("LLVM returned a non-utf8 feature string: {}", e);
523 });
524let desc = CStr::from_ptr(desc).to_str().unwrap_or_else(|e| {
525::rustc_span::macros::bug_impl(None,
format_args!("LLVM returned a non-utf8 feature string: {0}", e),
Location::caller());bug!("LLVM returned a non-utf8 feature string: {}", e);
526 });
527 ret.push((feature, desc));
528 }
529 }
530ret531}
532533pub(crate) fn print(req: &PrintRequest, out: &mut String, sess: &Session) {
534require_inited();
535let tm = create_informational_target_machine(sess);
536match req.kind {
537 PrintKind::TargetCPUs => print_target_cpus(sess, tm.raw(), out),
538 PrintKind::TargetFeatures => print_target_features(sess, tm.raw(), out),
539_ => ::rustc_span::macros::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),
540 }
541}
542543fn print_target_cpus(sess: &Session, tm: &llvm::TargetMachine, out: &mut String) {
544let cpu_names = llvm::build_string(|s| unsafe {
545 llvm::LLVMRustPrintTargetCPUs(&tm, s);
546 })
547 .unwrap();
548549struct Cpu<'a> {
550 cpu_name: &'a str,
551 remark: String,
552 }
553// Compare CPU against current target to label the default. Do not print it if
554 // `need_explicit_cpu` is set, because in that case the concept of default makes less sense.
555let target_cpu = handle_native(&sess.target.cpu);
556let make_remark = |cpu_name| {
557if cpu_name == target_cpu && !sess.target.need_explicit_cpu {
558// FIXME(#132514): This prints the LLVM target string, which can be
559 // different from the Rust target string. Is that intended?
560let target = &sess.target.llvm_target;
561::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" - This is the default target CPU for the current build target (currently {0}).",
target))
})format!(
562" - This is the default target CPU for the current build target (currently {target})."
563)564 } else {
565"".to_owned()
566 }
567 };
568let mut cpus = cpu_names569 .lines()
570 .filter(|cpu_name| {
571 !sess.target.unsupported_cpus.contains(&std::borrow::Cow::Borrowed(*cpu_name))
572 })
573 .map(|cpu_name| Cpu { cpu_name, remark: make_remark(cpu_name) })
574 .collect::<VecDeque<_>>();
575576// Only print the "native" entry when host and target are the same arch,
577 // since otherwise it could be wrong or misleading.
578 // Also do not print it if `requires_consistent_cpu` is set, because in this case
579 // "native" would be rejected.
580if sess.host.arch == sess.target.arch && !sess.target.requires_consistent_cpu {
581let host = get_host_cpu_name();
582cpus.push_front(Cpu {
583 cpu_name: NATIVE_CPU,
584 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})."),
585 });
586 }
587588let max_name_width = cpus.iter().map(|cpu| cpu.cpu_name.len()).max().unwrap_or(0);
589out.write_fmt(format_args!("Available CPUs for this target:\n"))writeln!(out, "Available CPUs for this target:").unwrap();
590for Cpu { cpu_name, remark } in cpus {
591// Only pad the CPU name if there's a remark to print after it.
592let width = if remark.is_empty() { 0 } else { max_name_width };
593out.write_fmt(format_args!(" {0:<1$}{2}\n", cpu_name, width, remark))writeln!(out, " {cpu_name:<width$}{remark}").unwrap();
594 }
595}
596597fn print_target_features(sess: &Session, tm: &llvm::TargetMachine, out: &mut String) {
598let mut llvm_target_features = llvm_target_features(tm);
599let mut known_llvm_target_features = FxHashSet::<&'static str>::default();
600let mut rustc_target_features = sess601 .target
602 .rust_target_features()
603 .iter()
604 .filter_map(|(feature, gate, _implied)| {
605if !gate.in_cfg() {
606// Only list (experimentally) supported features.
607return None;
608 }
609// LLVM asserts that these are sorted. LLVM and Rust both use byte comparison for these
610 // strings.
611let llvm_feature = to_llvm_features(&sess.target, *feature)?.llvm_feature_name;
612let desc =
613match llvm_target_features.binary_search_by_key(&llvm_feature, |(f, _d)| f).ok() {
614Some(index) => {
615known_llvm_target_features.insert(llvm_feature);
616llvm_target_features[index].1
617}
618None => "",
619 };
620621Some((*feature, desc))
622 })
623 .collect::<Vec<_>>();
624625// Since we add this at the end ...
626rustc_target_features.extend_from_slice(&[(
627"crt-static",
628"Enables C Run-time Libraries to be statically linked",
629 )]);
630// ... we need to sort the list again.
631rustc_target_features.sort();
632633llvm_target_features.retain(|(f, _d)| !known_llvm_target_features.contains(f));
634635let max_feature_len = llvm_target_features636 .iter()
637 .chain(rustc_target_features.iter())
638 .map(|(feature, _desc)| feature.len())
639 .max()
640 .unwrap_or(0);
641642out.write_fmt(format_args!("Features supported by rustc for this target:\n"))writeln!(out, "Features supported by rustc for this target:").unwrap();
643for (feature, desc) in &rustc_target_features {
644out.write_fmt(format_args!(" {0:1$} - {2}.\n", feature, max_feature_len,
desc))writeln!(out, " {feature:max_feature_len$} - {desc}.").unwrap();
645 }
646out.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();
647for (feature, desc) in &llvm_target_features {
648out.write_fmt(format_args!(" {0:1$} - {2}.\n", feature, max_feature_len,
desc))writeln!(out, " {feature:max_feature_len$} - {desc}.").unwrap();
649 }
650if llvm_target_features.is_empty() {
651out.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.")652 .unwrap();
653 }
654out.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();
655out.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")656 .unwrap();
657out.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();
658out.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();
659}
660661/// Returns the host CPU name, according to LLVM.
662fn get_host_cpu_name() -> &'static str {
663let mut len = 0;
664// SAFETY: The underlying C++ global function returns a `StringRef` that
665 // isn't tied to any particular backing buffer, so it must be 'static.
666let slice: &'static [u8] = unsafe {
667let ptr = llvm::LLVMRustGetHostCPUName(&mut len);
668if !!ptr.is_null() {
::core::panicking::panic("assertion failed: !ptr.is_null()")
};assert!(!ptr.is_null());
669 slice::from_raw_parts(ptr, len)
670 };
671 str::from_utf8(slice).expect("host CPU name should be UTF-8")
672}
673674/// If the given string is `"native"`, returns the host CPU name according to
675/// LLVM. Otherwise, the string is returned as-is.
676fn handle_native(cpu_name: &str) -> &str {
677match cpu_name {
678NATIVE_CPU => get_host_cpu_name(),
679_ => cpu_name,
680 }
681}
682683pub(crate) fn target_cpu(sess: &EarlySession) -> &str {
684let cpu_name = sess.opts.cg.target_cpu.as_deref().unwrap_or_else(|| &sess.target.cpu);
685handle_native(cpu_name)
686}
687688/// The target features for compiler flags other than `-Ctarget-features`.
689fn llvm_features_by_flags(sess: &EarlySession, features: &mut Vec<String>) {
690if wants_wasm_eh(&sess.target) && sess.panic_strategy() == PanicStrategy::Unwind {
691features.push("+exception-handling".into());
692 }
693694 target_features::retpoline_features_by_flags(sess, features);
695 target_features::sanitizer_features_by_flags(sess, features);
696697// -Zfixed-x18
698if sess.opts.unstable_opts.fixed_x18 {
699if sess.target.arch != Arch::AArch64 {
700sess.dcx()
701 .emit_fatal(diagnostics::FixedX18InvalidArch { arch: sess.target.arch.desc() });
702 } else {
703features.push("+reserve-x18".into());
704 }
705 }
706}
707708/// The list of LLVM features computed from CLI flags (`-Ctarget-cpu`, `-Ctarget-feature`,
709/// `--target` and similar).
710///
711/// If `for_cfg` is `true` then we are assembling the feature list for the purpose of populating
712/// [`rustc_codegen_ssa::TargetConfig`] based on what LLVM actually enables in this configuration.
713/// `-Ctarget-feature` should be ignored in that case since it is already processed separately.
714pub(crate) fn global_llvm_features(sess: &EarlySession, for_cfg: bool) -> Vec<String> {
715// Features that come earlier are overridden by conflicting features later in the string.
716 // Typically we'll want more explicit settings to override the implicit ones, so:
717 //
718 // * Features from -Ctarget-cpu=*; are overridden by [^1]
719 // * Features implied by --target; are overridden by
720 // * Features from -Ctarget-feature; are overridden by
721 // * function specific features.
722 //
723 // [^1]: target-cpu=native is handled here, other target-cpu values are handled implicitly
724 // through LLVM TargetMachine implementation.
725 //
726 // FIXME(nagisa): it isn't clear what's the best interaction between features implied by
727 // `-Ctarget-cpu` and `--target` are. On one hand, you'd expect CLI arguments to always
728 // override anything that's implicit, so e.g. when there's no `--target` flag, features implied
729 // the host target are overridden by `-Ctarget-cpu=*`. On the other hand, what about when both
730 // `--target` and `-Ctarget-cpu=*` are specified? Both then imply some target features and both
731 // flags are specified by the user on the CLI. It isn't as clear-cut which order of precedence
732 // should be taken in cases like these.
733let mut features = ::alloc::vec::Vec::new()vec![];
734735// -Ctarget-cpu=native
736match sess.opts.cg.target_cpu {
737Some(ref s) if s == NATIVE_CPU => {
738// We have already figured out the actual CPU name with `LLVMRustGetHostCPUName` and set
739 // that for LLVM, so the features implied by that CPU name will be available everywhere.
740 // However, that is not sufficient: e.g. `skylake` alone is not sufficient to tell if
741 // some of the instructions are available or not. So we have to also explicitly ask for
742 // the exact set of features available on the host, and enable all of them.
743let features_string = unsafe {
744let ptr = llvm::LLVMGetHostCPUFeatures();
745let features_string = if !ptr.is_null() {
746CStr::from_ptr(ptr)
747 .to_str()
748 .unwrap_or_else(|e| {
749::rustc_span::macros::bug_impl(None,
format_args!("LLVM returned a non-utf8 features string: {0}", e),
Location::caller());bug!("LLVM returned a non-utf8 features string: {}", e);
750 })
751 .to_owned()
752 } else {
753::rustc_span::macros::bug_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");
754 };
755756 llvm::LLVMDisposeMessage(ptr);
757758features_string759 };
760if !features_string.is_empty() {
761features.extend(features_string.split(',').map(String::from));
762 }
763 }
764Some(_) | None => {}
765 };
766767let mut extend_backend_features = |feature: &str, enable: bool| {
768let enable_disable = if enable { '+' } else { '-' };
769// We run through `to_llvm_features` when
770 // passing requests down to LLVM. This means that all in-language
771 // features also work on the command line instead of having two
772 // different names when the LLVM name and the Rust name differ.
773let Some(llvm_feature) = to_llvm_features(&sess.target, feature) else { return };
774775features.extend(
776 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(
777llvm_feature.dependencies.into_iter().filter_map(move |feat| {
778match (enable, feat) {
779 (_, TargetFeatureFoldStrength::Both(f))
780 | (true, TargetFeatureFoldStrength::EnableOnly(f)) => {
781Some(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1}", enable_disable, f))
})format!("{enable_disable}{f}"))
782 }
783_ => None,
784 }
785 }),
786 ),
787 );
788 };
789790// Features implied by an implicit or explicit `--target`.
791target_features::target_spec_to_backend_features(sess, &mut extend_backend_features);
792793// -Ctarget-features. Skipped for `cfg` as there we parse -Ctarget-features directly instead of
794 // going via an LLVM target machine (which avoids accidentally picking up LLVM-level target
795 // feature implications that we do not want).
796if !for_cfg {
797 target_features::flag_to_backend_features(sess, extend_backend_features);
798 }
799800// `-C` flags that map to LLVM target features.
801 // We need to include them even with `only_base_features` as this is used to populate
802 // `sess.internal_target_features` where we very much want them to be present (e.g. the inline
803 // asm logic uses that to check which registers may be used).
804llvm_features_by_flags(sess, &mut features);
805806// `-Zllvm-target-features`, all the way at the end to overwrite everything.
807 // Should be picked up by `cfg` (e.g. if someone enables AVX this way).
808for feature in sess.opts.unstable_opts.llvm_target_feature.split(',') {
809if feature.is_empty() {
810continue;
811 }
812if feature.starts_with('+') || feature.starts_with('-') {
813 features.push(feature.to_owned());
814 } else {
815// LLVM seems to silently ignore entries without leading `+`/`-`. Let's emit a warning
816 // to avoid confusion. But only emit this warning once, under `for_cfg`.
817if for_cfg {
818 sess.dcx().emit_warn(diagnostics::UnknownLlvmTargetFeaturePrefix { feature });
819 }
820 }
821 }
822823features824}
825826pub(crate) fn tune_cpu(sess: &Session) -> Option<&str> {
827let name = sess.opts.unstable_opts.tune_cpu.as_ref()?;
828Some(handle_native(name))
829}
830831pub(crate) fn target_has_mnemonic(sess: &Session, mnemonic: &str) -> bool {
832require_inited();
833let tm = create_informational_target_machine(sess);
834let cstr = SmallCStr::new(mnemonic);
835unsafe { llvm::LLVMRustTargetHasMnemonic(tm.raw(), cstr.as_ptr()) }
836}