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