]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_llvm/llvm_util.rs
Rollup merge of #67410 - mati865:mingw_link_fix, r=Mark-Simulacrum
[rust.git] / src / librustc_codegen_llvm / llvm_util.rs
1 use crate::back::write::create_informational_target_machine;
2 use crate::llvm;
3 use syntax_pos::symbol::Symbol;
4 use rustc::session::Session;
5 use rustc::session::config::PrintRequest;
6 use rustc_data_structures::fx::FxHashSet;
7 use rustc_target::spec::{MergeFunctions, PanicStrategy};
8 use libc::c_int;
9 use std::ffi::CString;
10 use rustc_feature::UnstableFeatures;
11 use syntax::symbol::sym;
12 use rustc::bug;
13
14 use std::str;
15 use std::slice;
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();
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| {
57             c == '=' || c.is_whitespace()
58         }).next().unwrap_or("")
59     }
60
61     let user_specified_args: FxHashSet<_> = sess
62         .opts
63         .cg
64         .llvm_args
65         .iter()
66         .map(|s| llvm_arg_to_arg_name(s))
67         .filter(|s| s.len() > 0)
68         .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         add("rustc", true); // fake program name
81         if sess.time_llvm_passes() { add("-time-passes", false); }
82         if sess.print_llvm_passes() { add("-debug-pass=Structure", false); }
83
84         if sess.opts.debugging_opts.generate_arange_section {
85             add("-generate-arange-section", false);
86         }
87         if get_major_version() >= 8 {
88             match sess.opts.debugging_opts.merge_functions
89                   .unwrap_or(sess.target.target.options.merge_functions) {
90                 MergeFunctions::Disabled |
91                 MergeFunctions::Trampolines => {}
92                 MergeFunctions::Aliases => {
93                     add("-mergefunc-use-aliases", false);
94                 }
95             }
96         }
97
98         if sess.target.target.target_os == "emscripten" &&
99             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         for arg in &sess.opts.cg.llvm_args {
108             add(&(*arg), true);
109         }
110     }
111
112     llvm::LLVMInitializePasses();
113
114     ::rustc_llvm::initialize_available_targets();
115
116     llvm::LLVMRustSetLLVMOptions(llvm_args.len() as c_int,
117                                  llvm_args.as_ptr());
118 }
119
120 // WARNING: the features after applying `to_llvm_feature` must be known
121 // to LLVM or the feature detection code will walk past the end of the feature
122 // array, leading to crashes.
123
124 const ARM_WHITELIST: &[(&str, Option<Symbol>)] = &[
125     ("aclass", Some(sym::arm_target_feature)),
126     ("mclass", Some(sym::arm_target_feature)),
127     ("rclass", Some(sym::arm_target_feature)),
128     ("dsp", Some(sym::arm_target_feature)),
129     ("neon", Some(sym::arm_target_feature)),
130     ("crc", Some(sym::arm_target_feature)),
131     ("crypto", Some(sym::arm_target_feature)),
132     ("v5te", Some(sym::arm_target_feature)),
133     ("v6", Some(sym::arm_target_feature)),
134     ("v6k", Some(sym::arm_target_feature)),
135     ("v6t2", Some(sym::arm_target_feature)),
136     ("v7", Some(sym::arm_target_feature)),
137     ("v8", Some(sym::arm_target_feature)),
138     ("vfp2", Some(sym::arm_target_feature)),
139     ("vfp3", Some(sym::arm_target_feature)),
140     ("vfp4", Some(sym::arm_target_feature)),
141 ];
142
143 const AARCH64_WHITELIST: &[(&str, Option<Symbol>)] = &[
144     ("fp", Some(sym::aarch64_target_feature)),
145     ("neon", Some(sym::aarch64_target_feature)),
146     ("sve", Some(sym::aarch64_target_feature)),
147     ("crc", Some(sym::aarch64_target_feature)),
148     ("crypto", Some(sym::aarch64_target_feature)),
149     ("ras", Some(sym::aarch64_target_feature)),
150     ("lse", Some(sym::aarch64_target_feature)),
151     ("rdm", Some(sym::aarch64_target_feature)),
152     ("fp16", Some(sym::aarch64_target_feature)),
153     ("rcpc", Some(sym::aarch64_target_feature)),
154     ("dotprod", Some(sym::aarch64_target_feature)),
155     ("v8.1a", Some(sym::aarch64_target_feature)),
156     ("v8.2a", Some(sym::aarch64_target_feature)),
157     ("v8.3a", Some(sym::aarch64_target_feature)),
158 ];
159
160 const X86_WHITELIST: &[(&str, Option<Symbol>)] = &[
161     ("adx", Some(sym::adx_target_feature)),
162     ("aes", None),
163     ("avx", None),
164     ("avx2", None),
165     ("avx512bw", Some(sym::avx512_target_feature)),
166     ("avx512cd", Some(sym::avx512_target_feature)),
167     ("avx512dq", Some(sym::avx512_target_feature)),
168     ("avx512er", Some(sym::avx512_target_feature)),
169     ("avx512f", Some(sym::avx512_target_feature)),
170     ("avx512ifma", Some(sym::avx512_target_feature)),
171     ("avx512pf", Some(sym::avx512_target_feature)),
172     ("avx512vbmi", Some(sym::avx512_target_feature)),
173     ("avx512vl", Some(sym::avx512_target_feature)),
174     ("avx512vpopcntdq", Some(sym::avx512_target_feature)),
175     ("bmi1", None),
176     ("bmi2", None),
177     ("cmpxchg16b", Some(sym::cmpxchg16b_target_feature)),
178     ("f16c", Some(sym::f16c_target_feature)),
179     ("fma", None),
180     ("fxsr", None),
181     ("lzcnt", None),
182     ("mmx", Some(sym::mmx_target_feature)),
183     ("movbe", Some(sym::movbe_target_feature)),
184     ("pclmulqdq", None),
185     ("popcnt", None),
186     ("rdrand", None),
187     ("rdseed", None),
188     ("rtm", Some(sym::rtm_target_feature)),
189     ("sha", None),
190     ("sse", None),
191     ("sse2", None),
192     ("sse3", None),
193     ("sse4.1", None),
194     ("sse4.2", None),
195     ("sse4a", Some(sym::sse4a_target_feature)),
196     ("ssse3", None),
197     ("tbm", Some(sym::tbm_target_feature)),
198     ("xsave", None),
199     ("xsavec", None),
200     ("xsaveopt", None),
201     ("xsaves", None),
202 ];
203
204 const HEXAGON_WHITELIST: &[(&str, Option<Symbol>)] = &[
205     ("hvx", Some(sym::hexagon_target_feature)),
206     ("hvx-length128b", Some(sym::hexagon_target_feature)),
207 ];
208
209 const POWERPC_WHITELIST: &[(&str, Option<Symbol>)] = &[
210     ("altivec", Some(sym::powerpc_target_feature)),
211     ("power8-altivec", Some(sym::powerpc_target_feature)),
212     ("power9-altivec", Some(sym::powerpc_target_feature)),
213     ("power8-vector", Some(sym::powerpc_target_feature)),
214     ("power9-vector", Some(sym::powerpc_target_feature)),
215     ("vsx", Some(sym::powerpc_target_feature)),
216 ];
217
218 const MIPS_WHITELIST: &[(&str, Option<Symbol>)] = &[
219     ("fp64", Some(sym::mips_target_feature)),
220     ("msa", Some(sym::mips_target_feature)),
221 ];
222
223 const WASM_WHITELIST: &[(&str, Option<Symbol>)] = &[
224     ("simd128", Some(sym::wasm_target_feature)),
225     ("atomics", Some(sym::wasm_target_feature)),
226 ];
227
228 /// When rustdoc is running, provide a list of all known features so that all their respective
229 /// primitives may be documented.
230 ///
231 /// IMPORTANT: If you're adding another whitelist to the above lists, make sure to add it to this
232 /// iterator!
233 pub fn all_known_features() -> impl Iterator<Item=(&'static str, Option<Symbol>)> {
234     ARM_WHITELIST.iter().cloned()
235         .chain(AARCH64_WHITELIST.iter().cloned())
236         .chain(X86_WHITELIST.iter().cloned())
237         .chain(HEXAGON_WHITELIST.iter().cloned())
238         .chain(POWERPC_WHITELIST.iter().cloned())
239         .chain(MIPS_WHITELIST.iter().cloned())
240         .chain(WASM_WHITELIST.iter().cloned())
241 }
242
243 pub fn to_llvm_feature<'a>(sess: &Session, s: &'a str) -> &'a str {
244     let arch = if sess.target.target.arch == "x86_64" {
245         "x86"
246     } else {
247         &*sess.target.target.arch
248     };
249     match (arch, s) {
250         ("x86", "pclmulqdq") => "pclmul",
251         ("x86", "rdrand") => "rdrnd",
252         ("x86", "bmi1") => "bmi",
253         ("x86", "cmpxchg16b") => "cx16",
254         ("aarch64", "fp") => "fp-armv8",
255         ("aarch64", "fp16") => "fullfp16",
256         (_, s) => s,
257     }
258 }
259
260 pub fn target_features(sess: &Session) -> Vec<Symbol> {
261     let target_machine = create_informational_target_machine(sess, true);
262     target_feature_whitelist(sess)
263         .iter()
264         .filter_map(|&(feature, gate)| {
265             if UnstableFeatures::from_environment().is_nightly_build() || gate.is_none() {
266                 Some(feature)
267             } else {
268                 None
269             }
270         })
271         .filter(|feature| {
272             let llvm_feature = to_llvm_feature(sess, feature);
273             let cstr = CString::new(llvm_feature).unwrap();
274             unsafe { llvm::LLVMRustHasFeature(target_machine, cstr.as_ptr()) }
275         })
276         .map(|feature| Symbol::intern(feature)).collect()
277 }
278
279 pub fn target_feature_whitelist(sess: &Session)
280     -> &'static [(&'static str, Option<Symbol>)]
281 {
282     match &*sess.target.target.arch {
283         "arm" => ARM_WHITELIST,
284         "aarch64" => AARCH64_WHITELIST,
285         "x86" | "x86_64" => X86_WHITELIST,
286         "hexagon" => HEXAGON_WHITELIST,
287         "mips" | "mips64" => MIPS_WHITELIST,
288         "powerpc" | "powerpc64" => POWERPC_WHITELIST,
289         "wasm32" => WASM_WHITELIST,
290         _ => &[],
291     }
292 }
293
294 pub fn print_version() {
295     // Can be called without initializing LLVM
296     unsafe {
297         println!("LLVM version: {}.{}",
298                  llvm::LLVMRustVersionMajor(), llvm::LLVMRustVersionMinor());
299     }
300 }
301
302 pub fn get_major_version() -> u32 {
303     unsafe { llvm::LLVMRustVersionMajor() }
304 }
305
306 pub fn print_passes() {
307     // Can be called without initializing LLVM
308     unsafe { llvm::LLVMRustPrintPasses(); }
309 }
310
311 pub(crate) fn print(req: PrintRequest, sess: &Session) {
312     require_inited();
313     let tm = create_informational_target_machine(sess, true);
314     unsafe {
315         match req {
316             PrintRequest::TargetCPUs => llvm::LLVMRustPrintTargetCPUs(tm),
317             PrintRequest::TargetFeatures => llvm::LLVMRustPrintTargetFeatures(tm),
318             _ => bug!("rustc_codegen_llvm can't handle print request: {:?}", req),
319         }
320     }
321 }
322
323 pub fn target_cpu(sess: &Session) -> &str {
324     let name = match sess.opts.cg.target_cpu {
325         Some(ref s) => &**s,
326         None => &*sess.target.target.options.cpu
327     };
328     if name != "native" {
329         return name
330     }
331
332     unsafe {
333         let mut len = 0;
334         let ptr = llvm::LLVMRustGetHostCPUName(&mut len);
335         str::from_utf8(slice::from_raw_parts(ptr as *const u8, len)).unwrap()
336     }
337 }