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