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