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 Abi, Arch, 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 if !llvm::LLVMIsMultithreaded().is_true() {
32 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 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 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 let sess_args = cg_opts.chain(tg_opts);
70
71 let user_specified_args: FxHashSet<_> =
72 sess_args.clone().map(|s| llvm_arg_to_arg_name(s)).filter(|s| !s.is_empty()).collect();
73
74 {
75 let mut add = |arg: &str, force: bool| {
78 if force || !user_specified_args.contains(llvm_arg_to_arg_name(arg)) {
79 let s = CString::new(arg).unwrap();
80 llvm_args.push(s.as_ptr());
81 llvm_c_strs.push(s);
82 }
83 };
84 add("rustc -Cllvm-args=\"...\" with", true);
86 if sess.opts.unstable_opts.time_llvm_passes {
87 add("-time-passes", false);
88 }
89 if sess.opts.unstable_opts.print_llvm_passes {
90 add("-debug-pass=Structure", false);
91 }
92 if sess.target.generate_arange_section
93 && !sess.opts.unstable_opts.no_generate_arange_section
94 {
95 add("-generate-arange-section", false);
96 }
97
98 match sess.opts.unstable_opts.merge_functions.unwrap_or(sess.target.merge_functions) {
99 MergeFunctions::Disabled | MergeFunctions::Trampolines => {}
100 MergeFunctions::Aliases => {
101 add("-mergefunc-use-aliases", false);
102 }
103 }
104
105 if wants_wasm_eh(sess) {
106 add("-wasm-enable-eh", false);
107 }
108
109 if sess.target.os == Os::Emscripten
110 && !sess.opts.unstable_opts.emscripten_wasm_eh
111 && sess.panic_strategy().unwinds()
112 {
113 add("-enable-emscripten-cxx-exceptions", false);
114 }
115
116 add("-preserve-alignment-assumptions-during-inlining=false", false);
119
120 add("-import-cold-multiplier=0.1", false);
122
123 if sess.print_llvm_stats() {
124 add("-stats", false);
125 }
126
127 for arg in sess_args {
128 add(&(*arg), true);
129 }
130
131 match (
132 sess.opts.unstable_opts.small_data_threshold,
133 sess.target.small_data_threshold_support(),
134 ) {
135 (Some(threshold), SmallDataThresholdSupport::LlvmArg(arg)) => {
138 add(&format!("--{arg}={threshold}"), false)
139 }
140 _ => (),
141 };
142 }
143
144 if sess.opts.unstable_opts.llvm_time_trace {
145 unsafe { llvm::LLVMRustTimeTraceProfilerInitialize() };
146 }
147
148 rustc_llvm::initialize_available_targets();
149
150 unsafe { llvm::LLVMRustSetLLVMOptions(llvm_args.len() as c_int, llvm_args.as_ptr()) };
151}
152
153pub(crate) fn time_trace_profiler_finish(file_name: &Path) {
154 unsafe {
155 let file_name = path_to_c_string(file_name);
156 llvm::LLVMRustTimeTraceProfilerFinish(file_name.as_ptr());
157 }
158}
159
160enum TargetFeatureFoldStrength<'a> {
161 EnableOnly(&'a str),
164 Both(&'a str),
166}
167
168impl<'a> TargetFeatureFoldStrength<'a> {
169 fn as_str(&self) -> &'a str {
170 match self {
171 TargetFeatureFoldStrength::EnableOnly(feat) => feat,
172 TargetFeatureFoldStrength::Both(feat) => feat,
173 }
174 }
175}
176
177pub(crate) struct LLVMFeature<'a> {
178 llvm_feature_name: &'a str,
179 dependencies: SmallVec<[TargetFeatureFoldStrength<'a>; 1]>,
180}
181
182impl<'a> LLVMFeature<'a> {
183 fn new(llvm_feature_name: &'a str) -> Self {
184 Self { llvm_feature_name, dependencies: SmallVec::new() }
185 }
186
187 fn with_dependencies(
188 llvm_feature_name: &'a str,
189 dependencies: SmallVec<[TargetFeatureFoldStrength<'a>; 1]>,
190 ) -> Self {
191 Self { llvm_feature_name, dependencies }
192 }
193}
194
195impl<'a> IntoIterator for LLVMFeature<'a> {
196 type Item = &'a str;
197 type IntoIter = impl Iterator<Item = &'a str>;
198
199 fn into_iter(self) -> Self::IntoIter {
200 let dependencies = self.dependencies.into_iter().map(|feat| feat.as_str());
201 std::iter::once(self.llvm_feature_name).chain(dependencies)
202 }
203}
204
205pub(crate) fn to_llvm_features<'a>(sess: &Session, s: &'a str) -> Option<LLVMFeature<'a>> {
222 let (major, _, _) = get_version();
223 match sess.target.arch {
224 Arch::AArch64 | Arch::Arm64EC => {
225 match s {
226 "rcpc2" => Some(LLVMFeature::new("rcpc-immo")),
227 "dpb" => Some(LLVMFeature::new("ccpp")),
228 "dpb2" => Some(LLVMFeature::new("ccdp")),
229 "frintts" => Some(LLVMFeature::new("fptoint")),
230 "fcma" => Some(LLVMFeature::new("complxnum")),
231 "pmuv3" => Some(LLVMFeature::new("perfmon")),
232 "paca" => Some(LLVMFeature::new("pauth")),
233 "pacg" => Some(LLVMFeature::new("pauth")),
234 "flagm2" => Some(LLVMFeature::new("altnzcv")),
235 "neon" => Some(LLVMFeature::with_dependencies(
237 "neon",
238 smallvec![TargetFeatureFoldStrength::Both("fp-armv8")],
239 )),
240 "fhm" => Some(LLVMFeature::new("fp16fml")),
243 "fp16" => Some(LLVMFeature::new("fullfp16")),
244 "fpmr" => None, "tme" if major >= 22 => None,
248 s => Some(LLVMFeature::new(s)),
249 }
250 }
251 Arch::Arm => match s {
252 "fp16" => Some(LLVMFeature::new("fullfp16")),
253 s => Some(LLVMFeature::new(s)),
254 },
255
256 Arch::LoongArch32 | Arch::LoongArch64 => match s {
258 "32s" if major < 21 => None,
259 s => Some(LLVMFeature::new(s)),
260 },
261 Arch::PowerPC | Arch::PowerPC64 => match s {
262 "power8-crypto" => Some(LLVMFeature::new("crypto")),
263 s => Some(LLVMFeature::new(s)),
264 },
265 Arch::Sparc | Arch::Sparc64 => match s {
266 "leoncasa" => Some(LLVMFeature::new("hasleoncasa")),
267 s => Some(LLVMFeature::new(s)),
268 },
269 Arch::Wasm32 | Arch::Wasm64 => match s {
270 "gc" if major < 22 => None,
271 s => Some(LLVMFeature::new(s)),
272 },
273 Arch::X86 | Arch::X86_64 => {
274 match s {
275 "sse4.2" => Some(LLVMFeature::with_dependencies(
276 "sse4.2",
277 smallvec![TargetFeatureFoldStrength::EnableOnly("crc32")],
278 )),
279 "pclmulqdq" => Some(LLVMFeature::new("pclmul")),
280 "rdrand" => Some(LLVMFeature::new("rdrnd")),
281 "bmi1" => Some(LLVMFeature::new("bmi")),
282 "cmpxchg16b" => Some(LLVMFeature::new("cx16")),
283 "lahfsahf" => Some(LLVMFeature::new("sahf")),
284 s if s.starts_with("avx512") => Some(LLVMFeature::with_dependencies(
286 s,
287 smallvec![TargetFeatureFoldStrength::EnableOnly("evex512")],
288 )),
289 "avx10.1" => Some(LLVMFeature::new("avx10.1-512")),
290 "avx10.2" => Some(LLVMFeature::new("avx10.2-512")),
291 "apxf" => Some(LLVMFeature::with_dependencies(
292 "egpr",
293 smallvec![
294 TargetFeatureFoldStrength::Both("push2pop2"),
295 TargetFeatureFoldStrength::Both("ppx"),
296 TargetFeatureFoldStrength::Both("ndd"),
297 TargetFeatureFoldStrength::Both("ccmp"),
298 TargetFeatureFoldStrength::Both("cf"),
299 TargetFeatureFoldStrength::Both("nf"),
300 TargetFeatureFoldStrength::Both("zu"),
301 ],
302 )),
303 s => Some(LLVMFeature::new(s)),
304 }
305 }
306 _ => Some(LLVMFeature::new(s)),
307 }
308}
309
310pub(crate) fn target_config(sess: &Session) -> TargetConfig {
315 let target_machine = create_informational_target_machine(sess, true);
316
317 let (unstable_target_features, target_features) = cfg_target_feature(
318 sess,
319 |feature| {
320 to_llvm_features(sess, feature)
321 .map(|f| SmallVec::<[&str; 2]>::from_iter(f.into_iter()))
322 .unwrap_or_default()
323 },
324 |feature| {
325 if let Some(feat) = to_llvm_features(sess, feature) {
329 for llvm_feature in feat {
331 let cstr = SmallCStr::new(llvm_feature);
332 if !unsafe { llvm::LLVMRustHasFeature(target_machine.raw(), cstr.as_ptr()) } {
336 return false;
337 }
338 }
339 true
340 } else {
341 false
342 }
343 },
344 );
345
346 let mut cfg = TargetConfig {
347 target_features,
348 unstable_target_features,
349 has_reliable_f16: true,
350 has_reliable_f16_math: true,
351 has_reliable_f128: true,
352 has_reliable_f128_math: true,
353 };
354
355 update_target_reliable_float_cfg(sess, &mut cfg);
356 cfg
357}
358
359fn update_target_reliable_float_cfg(sess: &Session, cfg: &mut TargetConfig) {
361 let target_arch = &sess.target.arch;
362 let target_os = &sess.target.options.os;
363 let target_env = &sess.target.options.env;
364 let target_abi = &sess.target.options.abi;
365 let target_pointer_width = sess.target.pointer_width;
366 let version = get_version();
367 let (major, _, _) = version;
368
369 cfg.has_reliable_f16 = match (target_arch, target_os) {
370 (Arch::AArch64, _)
372 if !cfg.target_features.iter().any(|f| f.as_str() == "neon")
373 && version < (20, 1, 1) =>
374 {
375 false
376 }
377 (Arch::Arm64EC, _) => false,
379 (Arch::S390x, _) if major < 21 => false,
381 (Arch::X86_64, Os::Windows) if *target_env == Env::Gnu && *target_abi != Abi::Llvm => false,
383 (Arch::CSky, _) => false,
385 (Arch::Hexagon, _) if major < 21 => false, (Arch::LoongArch32 | Arch::LoongArch64, _) if major < 21 => false, (Arch::PowerPC | Arch::PowerPC64, _) => false,
388 (Arch::Sparc | Arch::Sparc64, _) => false,
389 (Arch::Wasm32 | Arch::Wasm64, _) => false,
390 _ => true,
394 };
395
396 cfg.has_reliable_f128 = match (target_arch, target_os) {
397 (Arch::AmdGpu, _) => false,
399 (Arch::Arm64EC, _) => false,
401 (Arch::Mips64 | Arch::Mips64r6, _) if version < (20, 1, 0) => false,
403 (Arch::Nvptx64, _) => false,
406 (Arch::PowerPC | Arch::PowerPC64, _) => false,
409 (Arch::Sparc, _) => false,
411 (Arch::X86, _) if major < 21 => false,
414 (Arch::X86_64, Os::Windows) if *target_env == Env::Gnu && *target_abi != Abi::Llvm => false,
416 _ => true,
420 };
421
422 cfg.has_reliable_f16_math = cfg.has_reliable_f16;
425
426 cfg.has_reliable_f128_math = match (target_arch, target_os) {
427 _ if *target_env == Env::Musl => false,
437 (Arch::X86_64, _) => false,
438 (_, Os::Linux) if target_pointer_width == 64 => true,
439 _ => false,
440 } && cfg.has_reliable_f128;
441}
442
443pub(crate) fn print_version() {
444 let (major, minor, patch) = get_version();
445 println!("LLVM version: {major}.{minor}.{patch}");
446}
447
448pub(crate) fn get_version() -> (u32, u32, u32) {
449 unsafe {
451 (llvm::LLVMRustVersionMajor(), llvm::LLVMRustVersionMinor(), llvm::LLVMRustVersionPatch())
452 }
453}
454
455pub(crate) fn print_passes() {
456 unsafe {
458 llvm::LLVMRustPrintPasses();
459 }
460}
461
462fn llvm_target_features(tm: &llvm::TargetMachine) -> Vec<(&str, &str)> {
463 let len = unsafe { llvm::LLVMRustGetTargetFeaturesCount(tm) };
464 let mut ret = Vec::with_capacity(len);
465 for i in 0..len {
466 unsafe {
467 let mut feature = ptr::null();
468 let mut desc = ptr::null();
469 llvm::LLVMRustGetTargetFeature(tm, i, &mut feature, &mut desc);
470 if feature.is_null() || desc.is_null() {
471 bug!("LLVM returned a `null` target feature string");
472 }
473 let feature = CStr::from_ptr(feature).to_str().unwrap_or_else(|e| {
474 bug!("LLVM returned a non-utf8 feature string: {}", e);
475 });
476 let desc = CStr::from_ptr(desc).to_str().unwrap_or_else(|e| {
477 bug!("LLVM returned a non-utf8 feature string: {}", e);
478 });
479 ret.push((feature, desc));
480 }
481 }
482 ret
483}
484
485pub(crate) fn print(req: &PrintRequest, out: &mut String, sess: &Session) {
486 require_inited();
487 let tm = create_informational_target_machine(sess, false);
488 match req.kind {
489 PrintKind::TargetCPUs => print_target_cpus(sess, tm.raw(), out),
490 PrintKind::TargetFeatures => print_target_features(sess, tm.raw(), out),
491 _ => bug!("rustc_codegen_llvm can't handle print request: {:?}", req),
492 }
493}
494
495fn print_target_cpus(sess: &Session, tm: &llvm::TargetMachine, out: &mut String) {
496 let cpu_names = llvm::build_string(|s| unsafe {
497 llvm::LLVMRustPrintTargetCPUs(&tm, s);
498 })
499 .unwrap();
500
501 struct Cpu<'a> {
502 cpu_name: &'a str,
503 remark: String,
504 }
505 let target_cpu = handle_native(&sess.target.cpu);
507 let make_remark = |cpu_name| {
508 if cpu_name == target_cpu {
509 let target = &sess.target.llvm_target;
512 format!(
513 " - This is the default target CPU for the current build target (currently {target})."
514 )
515 } else {
516 "".to_owned()
517 }
518 };
519 let mut cpus = cpu_names
520 .lines()
521 .map(|cpu_name| Cpu { cpu_name, remark: make_remark(cpu_name) })
522 .collect::<VecDeque<_>>();
523
524 if sess.host.arch == sess.target.arch {
527 let host = get_host_cpu_name();
528 cpus.push_front(Cpu {
529 cpu_name: "native",
530 remark: format!(" - Select the CPU of the current host (currently {host})."),
531 });
532 }
533
534 let max_name_width = cpus.iter().map(|cpu| cpu.cpu_name.len()).max().unwrap_or(0);
535 writeln!(out, "Available CPUs for this target:").unwrap();
536 for Cpu { cpu_name, remark } in cpus {
537 let width = if remark.is_empty() { 0 } else { max_name_width };
539 writeln!(out, " {cpu_name:<width$}{remark}").unwrap();
540 }
541}
542
543fn print_target_features(sess: &Session, tm: &llvm::TargetMachine, out: &mut String) {
544 let mut llvm_target_features = llvm_target_features(tm);
545 let mut known_llvm_target_features = FxHashSet::<&'static str>::default();
546 let mut rustc_target_features = sess
547 .target
548 .rust_target_features()
549 .iter()
550 .filter_map(|(feature, gate, _implied)| {
551 if !gate.in_cfg() {
552 return None;
554 }
555 let llvm_feature = to_llvm_features(sess, *feature)?.llvm_feature_name;
558 let desc =
559 match llvm_target_features.binary_search_by_key(&llvm_feature, |(f, _d)| f).ok() {
560 Some(index) => {
561 known_llvm_target_features.insert(llvm_feature);
562 llvm_target_features[index].1
563 }
564 None => "",
565 };
566
567 Some((*feature, desc))
568 })
569 .collect::<Vec<_>>();
570
571 rustc_target_features.extend_from_slice(&[(
573 "crt-static",
574 "Enables C Run-time Libraries to be statically linked",
575 )]);
576 rustc_target_features.sort();
578
579 llvm_target_features.retain(|(f, _d)| !known_llvm_target_features.contains(f));
580
581 let max_feature_len = llvm_target_features
582 .iter()
583 .chain(rustc_target_features.iter())
584 .map(|(feature, _desc)| feature.len())
585 .max()
586 .unwrap_or(0);
587
588 writeln!(out, "Features supported by rustc for this target:").unwrap();
589 for (feature, desc) in &rustc_target_features {
590 writeln!(out, " {feature:max_feature_len$} - {desc}.").unwrap();
591 }
592 writeln!(out, "\nCode-generation features supported by LLVM for this target:").unwrap();
593 for (feature, desc) in &llvm_target_features {
594 writeln!(out, " {feature:max_feature_len$} - {desc}.").unwrap();
595 }
596 if llvm_target_features.is_empty() {
597 writeln!(out, " Target features listing is not supported by this LLVM version.")
598 .unwrap();
599 }
600 writeln!(out, "\nUse +feature to enable a feature, or -feature to disable it.").unwrap();
601 writeln!(out, "For example, rustc -C target-cpu=mycpu -C target-feature=+feature1,-feature2\n")
602 .unwrap();
603 writeln!(out, "Code-generation features cannot be used in cfg or #[target_feature],").unwrap();
604 writeln!(out, "and may be renamed or removed in a future version of LLVM or rustc.\n").unwrap();
605}
606
607fn get_host_cpu_name() -> &'static str {
609 let mut len = 0;
610 let slice: &'static [u8] = unsafe {
613 let ptr = llvm::LLVMRustGetHostCPUName(&mut len);
614 assert!(!ptr.is_null());
615 slice::from_raw_parts(ptr, len)
616 };
617 str::from_utf8(slice).expect("host CPU name should be UTF-8")
618}
619
620fn handle_native(cpu_name: &str) -> &str {
623 match cpu_name {
624 "native" => get_host_cpu_name(),
625 _ => cpu_name,
626 }
627}
628
629pub(crate) fn target_cpu(sess: &Session) -> &str {
630 let cpu_name = sess.opts.cg.target_cpu.as_deref().unwrap_or_else(|| &sess.target.cpu);
631 handle_native(cpu_name)
632}
633
634fn llvm_features_by_flags(sess: &Session, features: &mut Vec<String>) {
636 if wants_wasm_eh(sess) && sess.panic_strategy() == PanicStrategy::Unwind {
637 features.push("+exception-handling".into());
638 }
639
640 target_features::retpoline_features_by_flags(sess, features);
641
642 if sess.opts.unstable_opts.fixed_x18 {
644 if sess.target.arch != Arch::AArch64 {
645 sess.dcx().emit_fatal(errors::FixedX18InvalidArch { arch: sess.target.arch.desc() });
646 } else {
647 features.push("+reserve-x18".into());
648 }
649 }
650}
651
652pub(crate) fn global_llvm_features(sess: &Session, only_base_features: bool) -> Vec<String> {
655 let mut features = vec![];
674
675 match sess.opts.cg.target_cpu {
677 Some(ref s) if s == "native" => {
678 let features_string = unsafe {
684 let ptr = llvm::LLVMGetHostCPUFeatures();
685 let features_string = if !ptr.is_null() {
686 CStr::from_ptr(ptr)
687 .to_str()
688 .unwrap_or_else(|e| {
689 bug!("LLVM returned a non-utf8 features string: {}", e);
690 })
691 .to_owned()
692 } else {
693 bug!("could not allocate host CPU features, LLVM returned a `null` string");
694 };
695
696 llvm::LLVMDisposeMessage(ptr);
697
698 features_string
699 };
700 features.extend(features_string.split(',').map(String::from));
701 }
702 Some(_) | None => {}
703 };
704
705 let mut extend_backend_features = |feature: &str, enable: bool| {
706 let enable_disable = if enable { '+' } else { '-' };
707 let Some(llvm_feature) = to_llvm_features(sess, feature) else { return };
712
713 features.extend(
714 std::iter::once(format!("{}{}", enable_disable, llvm_feature.llvm_feature_name)).chain(
715 llvm_feature.dependencies.into_iter().filter_map(move |feat| {
716 match (enable, feat) {
717 (_, TargetFeatureFoldStrength::Both(f))
718 | (true, TargetFeatureFoldStrength::EnableOnly(f)) => {
719 Some(format!("{enable_disable}{f}"))
720 }
721 _ => None,
722 }
723 }),
724 ),
725 );
726 };
727
728 target_features::target_spec_to_backend_features(sess, &mut extend_backend_features);
730
731 if !only_base_features {
733 target_features::flag_to_backend_features(sess, extend_backend_features);
734 }
735
736 llvm_features_by_flags(sess, &mut features);
738
739 features
740}
741
742pub(crate) fn tune_cpu(sess: &Session) -> Option<&str> {
743 let name = sess.opts.unstable_opts.tune_cpu.as_ref()?;
744 Some(handle_native(name))
745}