]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_codegen_llvm/src/llvm_util.rs
Merge commit 'f51aade56f93175dde89177a92e3669ebd8e7592' into clippyup
[rust.git] / compiler / rustc_codegen_llvm / src / llvm_util.rs
1 use crate::back::write::create_informational_target_machine;
2 use crate::{llvm, llvm_util};
3 use libc::c_int;
4 use libloading::Library;
5 use rustc_codegen_ssa::target_features::{
6     supported_target_features, tied_target_features, RUSTC_SPECIFIC_FEATURES,
7 };
8 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
9 use rustc_data_structures::small_c_str::SmallCStr;
10 use rustc_fs_util::path_to_c_string;
11 use rustc_middle::bug;
12 use rustc_session::config::PrintRequest;
13 use rustc_session::Session;
14 use rustc_span::symbol::Symbol;
15 use rustc_target::spec::{MergeFunctions, PanicStrategy};
16 use smallvec::{smallvec, SmallVec};
17 use std::ffi::{CStr, CString};
18 use tracing::debug;
19
20 use std::mem;
21 use std::path::Path;
22 use std::ptr;
23 use std::slice;
24 use std::str;
25 use std::sync::Once;
26
27 static INIT: Once = Once::new();
28
29 pub(crate) fn init(sess: &Session) {
30     unsafe {
31         // Before we touch LLVM, make sure that multithreading is enabled.
32         if llvm::LLVMIsMultithreaded() != 1 {
33             bug!("LLVM compiled without support for threads");
34         }
35         INIT.call_once(|| {
36             configure_llvm(sess);
37         });
38     }
39 }
40
41 fn require_inited() {
42     if !INIT.is_completed() {
43         bug!("LLVM is not initialized");
44     }
45 }
46
47 unsafe fn configure_llvm(sess: &Session) {
48     let n_args = sess.opts.cg.llvm_args.len() + sess.target.llvm_args.len();
49     let mut llvm_c_strs = Vec::with_capacity(n_args + 1);
50     let mut llvm_args = Vec::with_capacity(n_args + 1);
51
52     llvm::LLVMRustInstallFatalErrorHandler();
53     // On Windows, an LLVM assertion will open an Abort/Retry/Ignore dialog
54     // box for the purpose of launching a debugger. However, on CI this will
55     // cause it to hang until it times out, which can take several hours.
56     if std::env::var_os("CI").is_some() {
57         llvm::LLVMRustDisableSystemDialogsOnCrash();
58     }
59
60     fn llvm_arg_to_arg_name(full_arg: &str) -> &str {
61         full_arg.trim().split(|c: char| c == '=' || c.is_whitespace()).next().unwrap_or("")
62     }
63
64     let cg_opts = sess.opts.cg.llvm_args.iter().map(AsRef::as_ref);
65     let tg_opts = sess.target.llvm_args.iter().map(AsRef::as_ref);
66     let sess_args = cg_opts.chain(tg_opts);
67
68     let user_specified_args: FxHashSet<_> =
69         sess_args.clone().map(|s| llvm_arg_to_arg_name(s)).filter(|s| !s.is_empty()).collect();
70
71     {
72         // This adds the given argument to LLVM. Unless `force` is true
73         // user specified arguments are *not* overridden.
74         let mut add = |arg: &str, force: bool| {
75             if force || !user_specified_args.contains(llvm_arg_to_arg_name(arg)) {
76                 let s = CString::new(arg).unwrap();
77                 llvm_args.push(s.as_ptr());
78                 llvm_c_strs.push(s);
79             }
80         };
81         // Set the llvm "program name" to make usage and invalid argument messages more clear.
82         add("rustc -Cllvm-args=\"...\" with", true);
83         if sess.time_llvm_passes() {
84             add("-time-passes", false);
85         }
86         if sess.print_llvm_passes() {
87             add("-debug-pass=Structure", false);
88         }
89         if sess.target.generate_arange_section
90             && !sess.opts.unstable_opts.no_generate_arange_section
91         {
92             add("-generate-arange-section", false);
93         }
94
95         match sess.opts.unstable_opts.merge_functions.unwrap_or(sess.target.merge_functions) {
96             MergeFunctions::Disabled | MergeFunctions::Trampolines => {}
97             MergeFunctions::Aliases => {
98                 add("-mergefunc-use-aliases", false);
99             }
100         }
101
102         if sess.target.os == "emscripten" && sess.panic_strategy() == PanicStrategy::Unwind {
103             add("-enable-emscripten-cxx-exceptions", false);
104         }
105
106         // HACK(eddyb) LLVM inserts `llvm.assume` calls to preserve align attributes
107         // during inlining. Unfortunately these may block other optimizations.
108         add("-preserve-alignment-assumptions-during-inlining=false", false);
109
110         // Use non-zero `import-instr-limit` multiplier for cold callsites.
111         add("-import-cold-multiplier=0.1", false);
112
113         for arg in sess_args {
114             add(&(*arg), true);
115         }
116     }
117
118     if sess.opts.unstable_opts.llvm_time_trace {
119         llvm::LLVMTimeTraceProfilerInitialize();
120     }
121
122     llvm::LLVMInitializePasses();
123
124     // Use the legacy plugin registration if we don't use the new pass manager
125     if !should_use_new_llvm_pass_manager(
126         &sess.opts.unstable_opts.new_llvm_pass_manager,
127         &sess.target.arch,
128     ) {
129         // Register LLVM plugins by loading them into the compiler process.
130         for plugin in &sess.opts.unstable_opts.llvm_plugins {
131             let lib = Library::new(plugin).unwrap_or_else(|e| bug!("couldn't load plugin: {}", e));
132             debug!("LLVM plugin loaded successfully {:?} ({})", lib, plugin);
133
134             // Intentionally leak the dynamic library. We can't ever unload it
135             // since the library can make things that will live arbitrarily long.
136             mem::forget(lib);
137         }
138     }
139
140     rustc_llvm::initialize_available_targets();
141
142     llvm::LLVMRustSetLLVMOptions(llvm_args.len() as c_int, llvm_args.as_ptr());
143 }
144
145 pub fn time_trace_profiler_finish(file_name: &Path) {
146     unsafe {
147         let file_name = path_to_c_string(file_name);
148         llvm::LLVMTimeTraceProfilerFinish(file_name.as_ptr());
149     }
150 }
151
152 // WARNING: the features after applying `to_llvm_features` must be known
153 // to LLVM or the feature detection code will walk past the end of the feature
154 // array, leading to crashes.
155 //
156 // To find a list of LLVM's names, check llvm-project/llvm/include/llvm/Support/*TargetParser.def
157 // where the * matches the architecture's name
158 // Beware to not use the llvm github project for this, but check the git submodule
159 // found in src/llvm-project
160 // Though note that Rust can also be build with an external precompiled version of LLVM
161 // which might lead to failures if the oldest tested / supported LLVM version
162 // doesn't yet support the relevant intrinsics
163 pub fn to_llvm_features<'a>(sess: &Session, s: &'a str) -> SmallVec<[&'a str; 2]> {
164     let arch = if sess.target.arch == "x86_64" { "x86" } else { &*sess.target.arch };
165     match (arch, s) {
166         ("x86", "sse4.2") => {
167             if get_version() >= (14, 0, 0) {
168                 smallvec!["sse4.2", "crc32"]
169             } else {
170                 smallvec!["sse4.2"]
171             }
172         }
173         ("x86", "pclmulqdq") => smallvec!["pclmul"],
174         ("x86", "rdrand") => smallvec!["rdrnd"],
175         ("x86", "bmi1") => smallvec!["bmi"],
176         ("x86", "cmpxchg16b") => smallvec!["cx16"],
177         ("x86", "avx512vaes") => smallvec!["vaes"],
178         ("x86", "avx512gfni") => smallvec!["gfni"],
179         ("x86", "avx512vpclmulqdq") => smallvec!["vpclmulqdq"],
180         ("aarch64", "rcpc2") => smallvec!["rcpc-immo"],
181         ("aarch64", "dpb") => smallvec!["ccpp"],
182         ("aarch64", "dpb2") => smallvec!["ccdp"],
183         ("aarch64", "frintts") => smallvec!["fptoint"],
184         ("aarch64", "fcma") => smallvec!["complxnum"],
185         ("aarch64", "pmuv3") => smallvec!["perfmon"],
186         ("aarch64", "paca") => smallvec!["pauth"],
187         ("aarch64", "pacg") => smallvec!["pauth"],
188         // Rust ties fp and neon together. In LLVM neon implicitly enables fp,
189         // but we manually enable neon when a feature only implicitly enables fp
190         ("aarch64", "f32mm") => smallvec!["f32mm", "neon"],
191         ("aarch64", "f64mm") => smallvec!["f64mm", "neon"],
192         ("aarch64", "fhm") => smallvec!["fp16fml", "neon"],
193         ("aarch64", "fp16") => smallvec!["fullfp16", "neon"],
194         ("aarch64", "jsconv") => smallvec!["jsconv", "neon"],
195         ("aarch64", "sve") => smallvec!["sve", "neon"],
196         ("aarch64", "sve2") => smallvec!["sve2", "neon"],
197         ("aarch64", "sve2-aes") => smallvec!["sve2-aes", "neon"],
198         ("aarch64", "sve2-sm4") => smallvec!["sve2-sm4", "neon"],
199         ("aarch64", "sve2-sha3") => smallvec!["sve2-sha3", "neon"],
200         ("aarch64", "sve2-bitperm") => smallvec!["sve2-bitperm", "neon"],
201         (_, s) => smallvec![s],
202     }
203 }
204
205 // Given a map from target_features to whether they are enabled or disabled,
206 // ensure only valid combinations are allowed.
207 pub fn check_tied_features(
208     sess: &Session,
209     features: &FxHashMap<&str, bool>,
210 ) -> Option<&'static [&'static str]> {
211     if !features.is_empty() {
212         for tied in tied_target_features(sess) {
213             // Tied features must be set to the same value, or not set at all
214             let mut tied_iter = tied.iter();
215             let enabled = features.get(tied_iter.next().unwrap());
216             if tied_iter.any(|f| enabled != features.get(f)) {
217                 return Some(tied);
218             }
219         }
220     }
221     return None;
222 }
223
224 // Used to generate cfg variables and apply features
225 // Must express features in the way Rust understands them
226 pub fn target_features(sess: &Session, allow_unstable: bool) -> Vec<Symbol> {
227     let target_machine = create_informational_target_machine(sess);
228     let mut features: Vec<Symbol> = supported_target_features(sess)
229         .iter()
230         .filter_map(|&(feature, gate)| {
231             if sess.is_nightly_build() || allow_unstable || gate.is_none() {
232                 Some(feature)
233             } else {
234                 None
235             }
236         })
237         .filter(|feature| {
238             // check that all features in a given smallvec are enabled
239             for llvm_feature in to_llvm_features(sess, feature) {
240                 let cstr = SmallCStr::new(llvm_feature);
241                 if !unsafe { llvm::LLVMRustHasFeature(target_machine, cstr.as_ptr()) } {
242                     return false;
243                 }
244             }
245             true
246         })
247         .map(|feature| Symbol::intern(feature))
248         .collect();
249
250     // LLVM 14 changed the ABI for i128 arguments to __float/__fix builtins on Win64
251     // (see https://reviews.llvm.org/D110413). This unstable target feature is intended for use
252     // by compiler-builtins, to export the builtins with the expected, LLVM-version-dependent ABI.
253     // The target feature can be dropped once we no longer support older LLVM versions.
254     if sess.is_nightly_build() && get_version() >= (14, 0, 0) {
255         features.push(Symbol::intern("llvm14-builtins-abi"));
256     }
257     features
258 }
259
260 pub fn print_version() {
261     let (major, minor, patch) = get_version();
262     println!("LLVM version: {}.{}.{}", major, minor, patch);
263 }
264
265 pub fn get_version() -> (u32, u32, u32) {
266     // Can be called without initializing LLVM
267     unsafe {
268         (llvm::LLVMRustVersionMajor(), llvm::LLVMRustVersionMinor(), llvm::LLVMRustVersionPatch())
269     }
270 }
271
272 pub fn print_passes() {
273     // Can be called without initializing LLVM
274     unsafe {
275         llvm::LLVMRustPrintPasses();
276     }
277 }
278
279 fn llvm_target_features(tm: &llvm::TargetMachine) -> Vec<(&str, &str)> {
280     let len = unsafe { llvm::LLVMRustGetTargetFeaturesCount(tm) };
281     let mut ret = Vec::with_capacity(len);
282     for i in 0..len {
283         unsafe {
284             let mut feature = ptr::null();
285             let mut desc = ptr::null();
286             llvm::LLVMRustGetTargetFeature(tm, i, &mut feature, &mut desc);
287             if feature.is_null() || desc.is_null() {
288                 bug!("LLVM returned a `null` target feature string");
289             }
290             let feature = CStr::from_ptr(feature).to_str().unwrap_or_else(|e| {
291                 bug!("LLVM returned a non-utf8 feature string: {}", e);
292             });
293             let desc = CStr::from_ptr(desc).to_str().unwrap_or_else(|e| {
294                 bug!("LLVM returned a non-utf8 feature string: {}", e);
295             });
296             ret.push((feature, desc));
297         }
298     }
299     ret
300 }
301
302 fn print_target_features(sess: &Session, tm: &llvm::TargetMachine) {
303     let mut target_features = llvm_target_features(tm);
304     let mut rustc_target_features = supported_target_features(sess)
305         .iter()
306         .filter_map(|(feature, _gate)| {
307             for llvm_feature in to_llvm_features(sess, *feature) {
308                 // LLVM asserts that these are sorted. LLVM and Rust both use byte comparison for these strings.
309                 match target_features.binary_search_by_key(&llvm_feature, |(f, _d)| f).ok().map(
310                     |index| {
311                         let (_f, desc) = target_features.remove(index);
312                         (*feature, desc)
313                     },
314                 ) {
315                     Some(v) => return Some(v),
316                     None => {}
317                 }
318             }
319             None
320         })
321         .collect::<Vec<_>>();
322     rustc_target_features.extend_from_slice(&[(
323         "crt-static",
324         "Enables C Run-time Libraries to be statically linked",
325     )]);
326     let max_feature_len = target_features
327         .iter()
328         .chain(rustc_target_features.iter())
329         .map(|(feature, _desc)| feature.len())
330         .max()
331         .unwrap_or(0);
332
333     println!("Features supported by rustc for this target:");
334     for (feature, desc) in &rustc_target_features {
335         println!("    {1:0$} - {2}.", max_feature_len, feature, desc);
336     }
337     println!("\nCode-generation features supported by LLVM for this target:");
338     for (feature, desc) in &target_features {
339         println!("    {1:0$} - {2}.", max_feature_len, feature, desc);
340     }
341     if target_features.is_empty() {
342         println!("    Target features listing is not supported by this LLVM version.");
343     }
344     println!("\nUse +feature to enable a feature, or -feature to disable it.");
345     println!("For example, rustc -C target-cpu=mycpu -C target-feature=+feature1,-feature2\n");
346     println!("Code-generation features cannot be used in cfg or #[target_feature],");
347     println!("and may be renamed or removed in a future version of LLVM or rustc.\n");
348 }
349
350 pub(crate) fn print(req: PrintRequest, sess: &Session) {
351     require_inited();
352     let tm = create_informational_target_machine(sess);
353     match req {
354         PrintRequest::TargetCPUs => unsafe { llvm::LLVMRustPrintTargetCPUs(tm) },
355         PrintRequest::TargetFeatures => print_target_features(sess, tm),
356         _ => bug!("rustc_codegen_llvm can't handle print request: {:?}", req),
357     }
358 }
359
360 fn handle_native(name: &str) -> &str {
361     if name != "native" {
362         return name;
363     }
364
365     unsafe {
366         let mut len = 0;
367         let ptr = llvm::LLVMRustGetHostCPUName(&mut len);
368         str::from_utf8(slice::from_raw_parts(ptr as *const u8, len)).unwrap()
369     }
370 }
371
372 pub fn target_cpu(sess: &Session) -> &str {
373     match sess.opts.cg.target_cpu {
374         Some(ref name) => handle_native(name),
375         None => handle_native(sess.target.cpu.as_ref()),
376     }
377 }
378
379 /// The list of LLVM features computed from CLI flags (`-Ctarget-cpu`, `-Ctarget-feature`,
380 /// `--target` and similar).
381 pub(crate) fn global_llvm_features(sess: &Session, diagnostics: bool) -> Vec<String> {
382     // Features that come earlier are overridden by conflicting features later in the string.
383     // Typically we'll want more explicit settings to override the implicit ones, so:
384     //
385     // * Features from -Ctarget-cpu=*; are overridden by [^1]
386     // * Features implied by --target; are overridden by
387     // * Features from -Ctarget-feature; are overridden by
388     // * function specific features.
389     //
390     // [^1]: target-cpu=native is handled here, other target-cpu values are handled implicitly
391     // through LLVM TargetMachine implementation.
392     //
393     // FIXME(nagisa): it isn't clear what's the best interaction between features implied by
394     // `-Ctarget-cpu` and `--target` are. On one hand, you'd expect CLI arguments to always
395     // override anything that's implicit, so e.g. when there's no `--target` flag, features implied
396     // the host target are overridden by `-Ctarget-cpu=*`. On the other hand, what about when both
397     // `--target` and `-Ctarget-cpu=*` are specified? Both then imply some target features and both
398     // flags are specified by the user on the CLI. It isn't as clear-cut which order of precedence
399     // should be taken in cases like these.
400     let mut features = vec![];
401
402     // -Ctarget-cpu=native
403     match sess.opts.cg.target_cpu {
404         Some(ref s) if s == "native" => {
405             let features_string = unsafe {
406                 let ptr = llvm::LLVMGetHostCPUFeatures();
407                 let features_string = if !ptr.is_null() {
408                     CStr::from_ptr(ptr)
409                         .to_str()
410                         .unwrap_or_else(|e| {
411                             bug!("LLVM returned a non-utf8 features string: {}", e);
412                         })
413                         .to_owned()
414                 } else {
415                     bug!("could not allocate host CPU features, LLVM returned a `null` string");
416                 };
417
418                 llvm::LLVMDisposeMessage(ptr);
419
420                 features_string
421             };
422             features.extend(features_string.split(',').map(String::from));
423         }
424         Some(_) | None => {}
425     };
426
427     // Features implied by an implicit or explicit `--target`.
428     features.extend(
429         sess.target
430             .features
431             .split(',')
432             .filter(|v| !v.is_empty() && backend_feature_name(v).is_some())
433             // Drop +atomics-32 feature introduced in LLVM 15.
434             .filter(|v| *v != "+atomics-32" || get_version() >= (15, 0, 0))
435             .map(String::from),
436     );
437
438     // -Ctarget-features
439     let supported_features = supported_target_features(sess);
440     let mut featsmap = FxHashMap::default();
441     let feats = sess
442         .opts
443         .cg
444         .target_feature
445         .split(',')
446         .filter_map(|s| {
447             let enable_disable = match s.chars().next() {
448                 None => return None,
449                 Some(c @ '+' | c @ '-') => c,
450                 Some(_) => {
451                     if diagnostics {
452                         let mut diag = sess.struct_warn(&format!(
453                             "unknown feature specified for `-Ctarget-feature`: `{}`",
454                             s
455                         ));
456                         diag.note("features must begin with a `+` to enable or `-` to disable it");
457                         diag.emit();
458                     }
459                     return None;
460                 }
461             };
462
463             let feature = backend_feature_name(s)?;
464             // Warn against use of LLVM specific feature names on the CLI.
465             if diagnostics && !supported_features.iter().any(|&(v, _)| v == feature) {
466                 let rust_feature = supported_features.iter().find_map(|&(rust_feature, _)| {
467                     let llvm_features = to_llvm_features(sess, rust_feature);
468                     if llvm_features.contains(&feature) && !llvm_features.contains(&rust_feature) {
469                         Some(rust_feature)
470                     } else {
471                         None
472                     }
473                 });
474                 let mut diag = sess.struct_warn(&format!(
475                     "unknown feature specified for `-Ctarget-feature`: `{}`",
476                     feature
477                 ));
478                 diag.note("it is still passed through to the codegen backend");
479                 if let Some(rust_feature) = rust_feature {
480                     diag.help(&format!("you might have meant: `{}`", rust_feature));
481                 } else {
482                     diag.note("consider filing a feature request");
483                 }
484                 diag.emit();
485             }
486
487             if diagnostics {
488                 // FIXME(nagisa): figure out how to not allocate a full hashset here.
489                 featsmap.insert(feature, enable_disable == '+');
490             }
491
492             // rustc-specific features do not get passed down to LLVM…
493             if RUSTC_SPECIFIC_FEATURES.contains(&feature) {
494                 return None;
495             }
496             // ... otherwise though we run through `to_llvm_features` when
497             // passing requests down to LLVM. This means that all in-language
498             // features also work on the command line instead of having two
499             // different names when the LLVM name and the Rust name differ.
500             Some(
501                 to_llvm_features(sess, feature)
502                     .into_iter()
503                     .map(move |f| format!("{}{}", enable_disable, f)),
504             )
505         })
506         .flatten();
507     features.extend(feats);
508
509     if diagnostics && let Some(f) = check_tied_features(sess, &featsmap) {
510         sess.err(&format!(
511             "target features {} must all be enabled or disabled together",
512             f.join(", ")
513         ));
514     }
515
516     features
517 }
518
519 /// Returns a feature name for the given `+feature` or `-feature` string.
520 ///
521 /// Only allows features that are backend specific (i.e. not [`RUSTC_SPECIFIC_FEATURES`].)
522 fn backend_feature_name(s: &str) -> Option<&str> {
523     // features must start with a `+` or `-`.
524     let feature = s.strip_prefix(&['+', '-'][..]).unwrap_or_else(|| {
525         bug!("target feature `{}` must begin with a `+` or `-`", s);
526     });
527     // Rustc-specific feature requests like `+crt-static` or `-crt-static`
528     // are not passed down to LLVM.
529     if RUSTC_SPECIFIC_FEATURES.contains(&feature) {
530         return None;
531     }
532     Some(feature)
533 }
534
535 pub fn tune_cpu(sess: &Session) -> Option<&str> {
536     let name = sess.opts.unstable_opts.tune_cpu.as_ref()?;
537     Some(handle_native(name))
538 }
539
540 pub(crate) fn should_use_new_llvm_pass_manager(user_opt: &Option<bool>, target_arch: &str) -> bool {
541     // The new pass manager is enabled by default for LLVM >= 13.
542     // This matches Clang, which also enables it since Clang 13.
543
544     // Since LLVM 15, the legacy pass manager is no longer supported.
545     if llvm_util::get_version() >= (15, 0, 0) {
546         return true;
547     }
548
549     // There are some perf issues with the new pass manager when targeting
550     // s390x with LLVM 13, so enable the new pass manager only with LLVM 14.
551     // See https://github.com/rust-lang/rust/issues/89609.
552     let min_version = if target_arch == "s390x" { 14 } else { 13 };
553     user_opt.unwrap_or_else(|| llvm_util::get_version() >= (min_version, 0, 0))
554 }