]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_codegen_llvm/src/llvm_util.rs
clippy::single_char_pattern
[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 rustc_codegen_ssa::target_features::supported_target_features;
5 use rustc_data_structures::fx::FxHashSet;
6 use rustc_metadata::dynamic_lib::DynamicLibrary;
7 use rustc_middle::bug;
8 use rustc_session::config::PrintRequest;
9 use rustc_session::Session;
10 use rustc_span::symbol::Symbol;
11 use rustc_target::spec::{MergeFunctions, PanicStrategy};
12 use std::ffi::{CStr, CString};
13 use tracing::debug;
14
15 use std::mem;
16 use std::path::Path;
17 use std::ptr;
18 use std::slice;
19 use std::str;
20 use std::sync::atomic::{AtomicBool, Ordering};
21 use std::sync::Once;
22
23 static POISONED: AtomicBool = AtomicBool::new(false);
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         INIT.call_once(|| {
30             if llvm::LLVMStartMultithreaded() != 1 {
31                 // use an extra bool to make sure that all future usage of LLVM
32                 // cannot proceed despite the Once not running more than once.
33                 POISONED.store(true, Ordering::SeqCst);
34             }
35
36             configure_llvm(sess);
37         });
38
39         if POISONED.load(Ordering::SeqCst) {
40             bug!("couldn't enable multi-threaded LLVM");
41         }
42     }
43 }
44
45 fn require_inited() {
46     INIT.call_once(|| bug!("llvm is not initialized"));
47     if POISONED.load(Ordering::SeqCst) {
48         bug!("couldn't enable multi-threaded LLVM");
49     }
50 }
51
52 unsafe fn configure_llvm(sess: &Session) {
53     let n_args = sess.opts.cg.llvm_args.len() + sess.target.llvm_args.len();
54     let mut llvm_c_strs = Vec::with_capacity(n_args + 1);
55     let mut llvm_args = Vec::with_capacity(n_args + 1);
56
57     llvm::LLVMRustInstallFatalErrorHandler();
58
59     fn llvm_arg_to_arg_name(full_arg: &str) -> &str {
60         full_arg.trim().split(|c: char| c == '=' || c.is_whitespace()).next().unwrap_or("")
61     }
62
63     let cg_opts = sess.opts.cg.llvm_args.iter();
64     let tg_opts = sess.target.llvm_args.iter();
65     let sess_args = cg_opts.chain(tg_opts);
66
67     let user_specified_args: FxHashSet<_> =
68         sess_args.clone().map(|s| llvm_arg_to_arg_name(s)).filter(|s| !s.is_empty()).collect();
69
70     {
71         // This adds the given argument to LLVM. Unless `force` is true
72         // user specified arguments are *not* overridden.
73         let mut add = |arg: &str, force: bool| {
74             if force || !user_specified_args.contains(llvm_arg_to_arg_name(arg)) {
75                 let s = CString::new(arg).unwrap();
76                 llvm_args.push(s.as_ptr());
77                 llvm_c_strs.push(s);
78             }
79         };
80         // Set the llvm "program name" to make usage and invalid argument messages more clear.
81         add("rustc -Cllvm-args=\"...\" with", true);
82         if sess.time_llvm_passes() {
83             add("-time-passes", false);
84         }
85         if sess.print_llvm_passes() {
86             add("-debug-pass=Structure", false);
87         }
88         if !sess.opts.debugging_opts.no_generate_arange_section {
89             add("-generate-arange-section", false);
90         }
91
92         // FIXME(nagisa): disable the machine outliner by default in LLVM versions 11, where it was
93         // introduced and up.
94         //
95         // This should remain in place until https://reviews.llvm.org/D103167 is fixed. If LLVM
96         // has been upgraded since, consider adjusting the version check below to contain an upper
97         // bound.
98         if llvm_util::get_version() >= (11, 0, 0) {
99             add("-enable-machine-outliner=never", false);
100         }
101
102         match sess.opts.debugging_opts.merge_functions.unwrap_or(sess.target.merge_functions) {
103             MergeFunctions::Disabled | MergeFunctions::Trampolines => {}
104             MergeFunctions::Aliases => {
105                 add("-mergefunc-use-aliases", false);
106             }
107         }
108
109         if sess.target.os == "emscripten" && sess.panic_strategy() == PanicStrategy::Unwind {
110             add("-enable-emscripten-cxx-exceptions", false);
111         }
112
113         // HACK(eddyb) LLVM inserts `llvm.assume` calls to preserve align attributes
114         // during inlining. Unfortunately these may block other optimizations.
115         add("-preserve-alignment-assumptions-during-inlining=false", false);
116
117         // Use non-zero `import-instr-limit` multiplier for cold callsites.
118         add("-import-cold-multiplier=0.1", false);
119
120         for arg in sess_args {
121             add(&(*arg), true);
122         }
123     }
124
125     if sess.opts.debugging_opts.llvm_time_trace {
126         // time-trace is not thread safe and running it in parallel will cause seg faults.
127         if !sess.opts.debugging_opts.no_parallel_llvm {
128             bug!("`-Z llvm-time-trace` requires `-Z no-parallel-llvm")
129         }
130
131         llvm::LLVMTimeTraceProfilerInitialize();
132     }
133
134     llvm::LLVMInitializePasses();
135
136     for plugin in &sess.opts.debugging_opts.llvm_plugins {
137         let path = Path::new(plugin);
138         let res = DynamicLibrary::open(path);
139         match res {
140             Ok(_) => debug!("LLVM plugin loaded succesfully {} ({})", path.display(), plugin),
141             Err(e) => bug!("couldn't load plugin: {}", e),
142         }
143         mem::forget(res);
144     }
145
146     rustc_llvm::initialize_available_targets();
147
148     llvm::LLVMRustSetLLVMOptions(llvm_args.len() as c_int, llvm_args.as_ptr());
149 }
150
151 pub fn time_trace_profiler_finish(file_name: &str) {
152     unsafe {
153         let file_name = CString::new(file_name).unwrap();
154         llvm::LLVMTimeTraceProfilerFinish(file_name.as_ptr());
155     }
156 }
157
158 // WARNING: the features after applying `to_llvm_feature` must be known
159 // to LLVM or the feature detection code will walk past the end of the feature
160 // array, leading to crashes.
161 // To find a list of LLVM's names, check llvm-project/llvm/include/llvm/Support/*TargetParser.def
162 // where the * matches the architecture's name
163 // Beware to not use the llvm github project for this, but check the git submodule
164 // found in src/llvm-project
165 // Though note that Rust can also be build with an external precompiled version of LLVM
166 // which might lead to failures if the oldest tested / supported LLVM version
167 // doesn't yet support the relevant intrinsics
168 pub fn to_llvm_feature<'a>(sess: &Session, s: &'a str) -> &'a str {
169     let arch = if sess.target.arch == "x86_64" { "x86" } else { &*sess.target.arch };
170     match (arch, s) {
171         ("x86", "pclmulqdq") => "pclmul",
172         ("x86", "rdrand") => "rdrnd",
173         ("x86", "bmi1") => "bmi",
174         ("x86", "cmpxchg16b") => "cx16",
175         ("x86", "avx512vaes") => "vaes",
176         ("x86", "avx512gfni") => "gfni",
177         ("x86", "avx512vpclmulqdq") => "vpclmulqdq",
178         ("aarch64", "fp") => "fp-armv8",
179         ("aarch64", "fp16") => "fullfp16",
180         ("aarch64", "fhm") => "fp16fml",
181         ("aarch64", "rcpc2") => "rcpc-immo",
182         ("aarch64", "dpb") => "ccpp",
183         ("aarch64", "dpb2") => "ccdp",
184         ("aarch64", "frintts") => "fptoint",
185         ("aarch64", "fcma") => "complxnum",
186         (_, s) => s,
187     }
188 }
189
190 pub fn target_features(sess: &Session) -> Vec<Symbol> {
191     let target_machine = create_informational_target_machine(sess);
192     supported_target_features(sess)
193         .iter()
194         .filter_map(
195             |&(feature, gate)| {
196                 if sess.is_nightly_build() || gate.is_none() { Some(feature) } else { None }
197             },
198         )
199         .filter(|feature| {
200             let llvm_feature = to_llvm_feature(sess, feature);
201             let cstr = CString::new(llvm_feature).unwrap();
202             unsafe { llvm::LLVMRustHasFeature(target_machine, cstr.as_ptr()) }
203         })
204         .map(|feature| Symbol::intern(feature))
205         .collect()
206 }
207
208 pub fn print_version() {
209     let (major, minor, patch) = get_version();
210     println!("LLVM version: {}.{}.{}", major, minor, patch);
211 }
212
213 pub fn get_version() -> (u32, u32, u32) {
214     // Can be called without initializing LLVM
215     unsafe {
216         (llvm::LLVMRustVersionMajor(), llvm::LLVMRustVersionMinor(), llvm::LLVMRustVersionPatch())
217     }
218 }
219
220 pub fn print_passes() {
221     // Can be called without initializing LLVM
222     unsafe {
223         llvm::LLVMRustPrintPasses();
224     }
225 }
226
227 fn llvm_target_features(tm: &llvm::TargetMachine) -> Vec<(&str, &str)> {
228     let len = unsafe { llvm::LLVMRustGetTargetFeaturesCount(tm) };
229     let mut ret = Vec::with_capacity(len);
230     for i in 0..len {
231         unsafe {
232             let mut feature = ptr::null();
233             let mut desc = ptr::null();
234             llvm::LLVMRustGetTargetFeature(tm, i, &mut feature, &mut desc);
235             if feature.is_null() || desc.is_null() {
236                 bug!("LLVM returned a `null` target feature string");
237             }
238             let feature = CStr::from_ptr(feature).to_str().unwrap_or_else(|e| {
239                 bug!("LLVM returned a non-utf8 feature string: {}", e);
240             });
241             let desc = CStr::from_ptr(desc).to_str().unwrap_or_else(|e| {
242                 bug!("LLVM returned a non-utf8 feature string: {}", e);
243             });
244             ret.push((feature, desc));
245         }
246     }
247     ret
248 }
249
250 fn print_target_features(sess: &Session, tm: &llvm::TargetMachine) {
251     let mut target_features = llvm_target_features(tm);
252     let mut rustc_target_features = supported_target_features(sess)
253         .iter()
254         .filter_map(|(feature, _gate)| {
255             let llvm_feature = to_llvm_feature(sess, *feature);
256             // LLVM asserts that these are sorted. LLVM and Rust both use byte comparison for these strings.
257             target_features.binary_search_by_key(&llvm_feature, |(f, _d)| *f).ok().map(|index| {
258                 let (_f, desc) = target_features.remove(index);
259                 (*feature, desc)
260             })
261         })
262         .collect::<Vec<_>>();
263     rustc_target_features.extend_from_slice(&[(
264         "crt-static",
265         "Enables C Run-time Libraries to be statically linked",
266     )]);
267     let max_feature_len = target_features
268         .iter()
269         .chain(rustc_target_features.iter())
270         .map(|(feature, _desc)| feature.len())
271         .max()
272         .unwrap_or(0);
273
274     println!("Features supported by rustc for this target:");
275     for (feature, desc) in &rustc_target_features {
276         println!("    {1:0$} - {2}.", max_feature_len, feature, desc);
277     }
278     println!("\nCode-generation features supported by LLVM for this target:");
279     for (feature, desc) in &target_features {
280         println!("    {1:0$} - {2}.", max_feature_len, feature, desc);
281     }
282     if target_features.len() == 0 {
283         println!("    Target features listing is not supported by this LLVM version.");
284     }
285     println!("\nUse +feature to enable a feature, or -feature to disable it.");
286     println!("For example, rustc -C target-cpu=mycpu -C target-feature=+feature1,-feature2\n");
287     println!("Code-generation features cannot be used in cfg or #[target_feature],");
288     println!("and may be renamed or removed in a future version of LLVM or rustc.\n");
289 }
290
291 pub(crate) fn print(req: PrintRequest, sess: &Session) {
292     require_inited();
293     let tm = create_informational_target_machine(sess);
294     match req {
295         PrintRequest::TargetCPUs => unsafe { llvm::LLVMRustPrintTargetCPUs(tm) },
296         PrintRequest::TargetFeatures => print_target_features(sess, tm),
297         _ => bug!("rustc_codegen_llvm can't handle print request: {:?}", req),
298     }
299 }
300
301 fn handle_native(name: &str) -> &str {
302     if name != "native" {
303         return name;
304     }
305
306     unsafe {
307         let mut len = 0;
308         let ptr = llvm::LLVMRustGetHostCPUName(&mut len);
309         str::from_utf8(slice::from_raw_parts(ptr as *const u8, len)).unwrap()
310     }
311 }
312
313 pub fn target_cpu(sess: &Session) -> &str {
314     let name = sess.opts.cg.target_cpu.as_ref().unwrap_or(&sess.target.cpu);
315     handle_native(name)
316 }
317
318 /// The list of LLVM features computed from CLI flags (`-Ctarget-cpu`, `-Ctarget-feature`,
319 /// `--target` and similar).
320 // FIXME(nagisa): Cache the output of this somehow? Maybe make this a query? We're calling this
321 // for every function that has `#[target_feature]` on it. The global features won't change between
322 // the functions; only crates, maybe…
323 pub fn llvm_global_features(sess: &Session) -> Vec<String> {
324     // FIXME(nagisa): this should definitely be available more centrally and to other codegen backends.
325     /// These features control behaviour of rustc rather than llvm.
326     const RUSTC_SPECIFIC_FEATURES: &[&str] = &["crt-static"];
327
328     // Features that come earlier are overriden by conflicting features later in the string.
329     // Typically we'll want more explicit settings to override the implicit ones, so:
330     //
331     // * Features from -Ctarget-cpu=*; are overriden by [^1]
332     // * Features implied by --target; are overriden by
333     // * Features from -Ctarget-feature; are overriden by
334     // * function specific features.
335     //
336     // [^1]: target-cpu=native is handled here, other target-cpu values are handled implicitly
337     // through LLVM TargetMachine implementation.
338     //
339     // FIXME(nagisa): it isn't clear what's the best interaction between features implied by
340     // `-Ctarget-cpu` and `--target` are. On one hand, you'd expect CLI arguments to always
341     // override anything that's implicit, so e.g. when there's no `--target` flag, features implied
342     // the host target are overriden by `-Ctarget-cpu=*`. On the other hand, what about when both
343     // `--target` and `-Ctarget-cpu=*` are specified? Both then imply some target features and both
344     // flags are specified by the user on the CLI. It isn't as clear-cut which order of precedence
345     // should be taken in cases like these.
346     let mut features = vec![];
347
348     // -Ctarget-cpu=native
349     match sess.opts.cg.target_cpu {
350         Some(ref s) if s == "native" => {
351             let features_string = unsafe {
352                 let ptr = llvm::LLVMGetHostCPUFeatures();
353                 let features_string = if !ptr.is_null() {
354                     CStr::from_ptr(ptr)
355                         .to_str()
356                         .unwrap_or_else(|e| {
357                             bug!("LLVM returned a non-utf8 features string: {}", e);
358                         })
359                         .to_owned()
360                 } else {
361                     bug!("could not allocate host CPU features, LLVM returned a `null` string");
362                 };
363
364                 llvm::LLVMDisposeMessage(ptr);
365
366                 features_string
367             };
368             features.extend(features_string.split(',').map(String::from));
369         }
370         Some(_) | None => {}
371     };
372
373     let filter = |s: &str| {
374         if s.is_empty() {
375             return None;
376         }
377         let feature = if s.starts_with('+') || s.starts_with('-') {
378             &s[1..]
379         } else {
380             return Some(s.to_string());
381         };
382         // Rustc-specific feature requests like `+crt-static` or `-crt-static`
383         // are not passed down to LLVM.
384         if RUSTC_SPECIFIC_FEATURES.contains(&feature) {
385             return None;
386         }
387         // ... otherwise though we run through `to_llvm_feature` feature when
388         // passing requests down to LLVM. This means that all in-language
389         // features also work on the command line instead of having two
390         // different names when the LLVM name and the Rust name differ.
391         Some(format!("{}{}", &s[..1], to_llvm_feature(sess, feature)))
392     };
393
394     // Features implied by an implicit or explicit `--target`.
395     features.extend(sess.target.features.split(',').filter_map(&filter));
396
397     // -Ctarget-features
398     features.extend(sess.opts.cg.target_feature.split(',').filter_map(&filter));
399
400     features
401 }
402
403 pub fn tune_cpu(sess: &Session) -> Option<&str> {
404     let name = sess.opts.debugging_opts.tune_cpu.as_ref()?;
405     Some(handle_native(name))
406 }