]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_codegen_llvm/src/llvm_util.rs
Rollup merge of #80133 - Aaron1011:fix/const-mut-deref, r=estebank
[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::supported_target_features;
5 use rustc_data_structures::fx::FxHashSet;
6 use rustc_middle::bug;
7 use rustc_session::config::PrintRequest;
8 use rustc_session::Session;
9 use rustc_span::symbol::Symbol;
10 use rustc_target::spec::{MergeFunctions, PanicStrategy};
11 use std::ffi::CString;
12
13 use std::slice;
14 use std::str;
15 use std::sync::atomic::{AtomicBool, Ordering};
16 use std::sync::Once;
17
18 static POISONED: AtomicBool = AtomicBool::new(false);
19 static INIT: Once = Once::new();
20
21 pub(crate) fn init(sess: &Session) {
22     unsafe {
23         // Before we touch LLVM, make sure that multithreading is enabled.
24         INIT.call_once(|| {
25             if llvm::LLVMStartMultithreaded() != 1 {
26                 // use an extra bool to make sure that all future usage of LLVM
27                 // cannot proceed despite the Once not running more than once.
28                 POISONED.store(true, Ordering::SeqCst);
29             }
30
31             configure_llvm(sess);
32         });
33
34         if POISONED.load(Ordering::SeqCst) {
35             bug!("couldn't enable multi-threaded LLVM");
36         }
37     }
38 }
39
40 fn require_inited() {
41     INIT.call_once(|| bug!("llvm is not initialized"));
42     if POISONED.load(Ordering::SeqCst) {
43         bug!("couldn't enable multi-threaded LLVM");
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
54     fn llvm_arg_to_arg_name(full_arg: &str) -> &str {
55         full_arg.trim().split(|c: char| c == '=' || c.is_whitespace()).next().unwrap_or("")
56     }
57
58     let cg_opts = sess.opts.cg.llvm_args.iter();
59     let tg_opts = sess.target.llvm_args.iter();
60     let sess_args = cg_opts.chain(tg_opts);
61
62     let user_specified_args: FxHashSet<_> =
63         sess_args.clone().map(|s| llvm_arg_to_arg_name(s)).filter(|s| !s.is_empty()).collect();
64
65     {
66         // This adds the given argument to LLVM. Unless `force` is true
67         // user specified arguments are *not* overridden.
68         let mut add = |arg: &str, force: bool| {
69             if force || !user_specified_args.contains(llvm_arg_to_arg_name(arg)) {
70                 let s = CString::new(arg).unwrap();
71                 llvm_args.push(s.as_ptr());
72                 llvm_c_strs.push(s);
73             }
74         };
75         // Set the llvm "program name" to make usage and invalid argument messages more clear.
76         add("rustc -Cllvm-args=\"...\" with", true);
77         if sess.time_llvm_passes() {
78             add("-time-passes", false);
79         }
80         if sess.print_llvm_passes() {
81             add("-debug-pass=Structure", false);
82         }
83         if !sess.opts.debugging_opts.no_generate_arange_section {
84             add("-generate-arange-section", false);
85         }
86         match sess.opts.debugging_opts.merge_functions.unwrap_or(sess.target.merge_functions) {
87             MergeFunctions::Disabled | MergeFunctions::Trampolines => {}
88             MergeFunctions::Aliases => {
89                 add("-mergefunc-use-aliases", false);
90             }
91         }
92
93         if sess.target.os == "emscripten" && sess.panic_strategy() == PanicStrategy::Unwind {
94             add("-enable-emscripten-cxx-exceptions", false);
95         }
96
97         // HACK(eddyb) LLVM inserts `llvm.assume` calls to preserve align attributes
98         // during inlining. Unfortunately these may block other optimizations.
99         add("-preserve-alignment-assumptions-during-inlining=false", false);
100
101         for arg in sess_args {
102             add(&(*arg), true);
103         }
104     }
105
106     if sess.opts.debugging_opts.llvm_time_trace {
107         // time-trace is not thread safe and running it in parallel will cause seg faults.
108         if !sess.opts.debugging_opts.no_parallel_llvm {
109             bug!("`-Z llvm-time-trace` requires `-Z no-parallel-llvm")
110         }
111
112         llvm::LLVMTimeTraceProfilerInitialize();
113     }
114
115     llvm::LLVMInitializePasses();
116
117     rustc_llvm::initialize_available_targets();
118
119     llvm::LLVMRustSetLLVMOptions(llvm_args.len() as c_int, llvm_args.as_ptr());
120 }
121
122 pub fn time_trace_profiler_finish(file_name: &str) {
123     unsafe {
124         let file_name = CString::new(file_name).unwrap();
125         llvm::LLVMTimeTraceProfilerFinish(file_name.as_ptr());
126     }
127 }
128
129 // WARNING: the features after applying `to_llvm_feature` must be known
130 // to LLVM or the feature detection code will walk past the end of the feature
131 // array, leading to crashes.
132 // To find a list of LLVM's names, check llvm-project/llvm/include/llvm/Support/*TargetParser.def
133 // where the * matches the architecture's name
134 // Beware to not use the llvm github project for this, but check the git submodule
135 // found in src/llvm-project
136 // Though note that Rust can also be build with an external precompiled version of LLVM
137 // which might lead to failures if the oldest tested / supported LLVM version
138 // doesn't yet support the relevant intrinsics
139 pub fn to_llvm_feature<'a>(sess: &Session, s: &'a str) -> &'a str {
140     let arch = if sess.target.arch == "x86_64" { "x86" } else { &*sess.target.arch };
141     match (arch, s) {
142         ("x86", "pclmulqdq") => "pclmul",
143         ("x86", "rdrand") => "rdrnd",
144         ("x86", "bmi1") => "bmi",
145         ("x86", "cmpxchg16b") => "cx16",
146         ("x86", "avx512vaes") => "vaes",
147         ("x86", "avx512gfni") => "gfni",
148         ("x86", "avx512vpclmulqdq") => "vpclmulqdq",
149         ("aarch64", "fp") => "fp-armv8",
150         ("aarch64", "fp16") => "fullfp16",
151         (_, s) => s,
152     }
153 }
154
155 pub fn target_features(sess: &Session) -> Vec<Symbol> {
156     let target_machine = create_informational_target_machine(sess);
157     supported_target_features(sess)
158         .iter()
159         .filter_map(
160             |&(feature, gate)| {
161                 if sess.is_nightly_build() || gate.is_none() { Some(feature) } else { None }
162             },
163         )
164         .filter(|feature| {
165             let llvm_feature = to_llvm_feature(sess, feature);
166             let cstr = CString::new(llvm_feature).unwrap();
167             unsafe { llvm::LLVMRustHasFeature(target_machine, cstr.as_ptr()) }
168         })
169         .map(|feature| Symbol::intern(feature))
170         .collect()
171 }
172
173 pub fn print_version() {
174     // Can be called without initializing LLVM
175     unsafe {
176         println!("LLVM version: {}.{}", llvm::LLVMRustVersionMajor(), llvm::LLVMRustVersionMinor());
177     }
178 }
179
180 pub fn get_major_version() -> u32 {
181     unsafe { llvm::LLVMRustVersionMajor() }
182 }
183
184 pub fn print_passes() {
185     // Can be called without initializing LLVM
186     unsafe {
187         llvm::LLVMRustPrintPasses();
188     }
189 }
190
191 pub(crate) fn print(req: PrintRequest, sess: &Session) {
192     require_inited();
193     let tm = create_informational_target_machine(sess);
194     unsafe {
195         match req {
196             PrintRequest::TargetCPUs => llvm::LLVMRustPrintTargetCPUs(tm),
197             PrintRequest::TargetFeatures => llvm::LLVMRustPrintTargetFeatures(tm),
198             _ => bug!("rustc_codegen_llvm can't handle print request: {:?}", req),
199         }
200     }
201 }
202
203 fn handle_native(name: &str) -> &str {
204     if name != "native" {
205         return name;
206     }
207
208     unsafe {
209         let mut len = 0;
210         let ptr = llvm::LLVMRustGetHostCPUName(&mut len);
211         str::from_utf8(slice::from_raw_parts(ptr as *const u8, len)).unwrap()
212     }
213 }
214
215 pub fn target_cpu(sess: &Session) -> &str {
216     let name = match sess.opts.cg.target_cpu {
217         Some(ref s) => &**s,
218         None => &*sess.target.cpu,
219     };
220
221     handle_native(name)
222 }
223
224 pub fn tune_cpu(sess: &Session) -> Option<&str> {
225     match sess.opts.debugging_opts.tune_cpu {
226         Some(ref s) => Some(handle_native(&**s)),
227         None => None,
228     }
229 }