1 use crate::back::write::create_informational_target_machine;
4 use rustc_data_structures::fx::FxHashSet;
5 use rustc_feature::UnstableFeatures;
7 use rustc_session::config::PrintRequest;
8 use rustc_session::Session;
9 use rustc_span::symbol::sym;
10 use rustc_span::symbol::Symbol;
11 use rustc_target::spec::{MergeFunctions, PanicStrategy};
12 use std::ffi::CString;
16 use std::sync::atomic::{AtomicBool, Ordering};
19 static POISONED: AtomicBool = AtomicBool::new(false);
20 static INIT: Once = Once::new();
22 pub(crate) fn init(sess: &Session) {
24 // Before we touch LLVM, make sure that multithreading is enabled.
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);
35 if POISONED.load(Ordering::SeqCst) {
36 bug!("couldn't enable multi-threaded LLVM");
42 INIT.call_once(|| bug!("llvm is not initialized"));
43 if POISONED.load(Ordering::SeqCst) {
44 bug!("couldn't enable multi-threaded LLVM");
48 unsafe fn configure_llvm(sess: &Session) {
49 let n_args = sess.opts.cg.llvm_args.len() + sess.target.target.options.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);
53 llvm::LLVMRustInstallFatalErrorHandler();
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("")
59 let cg_opts = sess.opts.cg.llvm_args.iter();
60 let tg_opts = sess.target.target.options.llvm_args.iter();
61 let sess_args = cg_opts.chain(tg_opts);
63 let user_specified_args: FxHashSet<_> =
64 sess_args.clone().map(|s| llvm_arg_to_arg_name(s)).filter(|s| !s.is_empty()).collect();
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());
76 add("rustc", true); // fake program name
77 if sess.time_llvm_passes() {
78 add("-time-passes", false);
80 if sess.print_llvm_passes() {
81 add("-debug-pass=Structure", false);
83 if !sess.opts.debugging_opts.no_generate_arange_section {
84 add("-generate-arange-section", false);
90 .unwrap_or(sess.target.target.options.merge_functions)
92 MergeFunctions::Disabled | MergeFunctions::Trampolines => {}
93 MergeFunctions::Aliases => {
94 add("-mergefunc-use-aliases", false);
98 if sess.target.target.target_os == "emscripten"
99 && sess.panic_strategy() == PanicStrategy::Unwind
101 add("-enable-emscripten-cxx-exceptions", false);
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);
108 for arg in sess_args {
113 if sess.opts.debugging_opts.llvm_time_trace && get_major_version() >= 9 {
114 // time-trace is not thread safe and running it in parallel will cause seg faults.
115 if !sess.opts.debugging_opts.no_parallel_llvm {
116 bug!("`-Z llvm-time-trace` requires `-Z no-parallel-llvm")
119 llvm::LLVMTimeTraceProfilerInitialize();
122 llvm::LLVMInitializePasses();
124 ::rustc_llvm::initialize_available_targets();
126 llvm::LLVMRustSetLLVMOptions(llvm_args.len() as c_int, llvm_args.as_ptr());
129 pub fn time_trace_profiler_finish(file_name: &str) {
131 if get_major_version() >= 9 {
132 let file_name = CString::new(file_name).unwrap();
133 llvm::LLVMTimeTraceProfilerFinish(file_name.as_ptr());
138 // WARNING: the features after applying `to_llvm_feature` must be known
139 // to LLVM or the feature detection code will walk past the end of the feature
140 // array, leading to crashes.
142 const ARM_WHITELIST: &[(&str, Option<Symbol>)] = &[
143 ("aclass", Some(sym::arm_target_feature)),
144 ("mclass", Some(sym::arm_target_feature)),
145 ("rclass", Some(sym::arm_target_feature)),
146 ("dsp", Some(sym::arm_target_feature)),
147 ("neon", Some(sym::arm_target_feature)),
148 ("crc", Some(sym::arm_target_feature)),
149 ("crypto", Some(sym::arm_target_feature)),
150 ("v5te", Some(sym::arm_target_feature)),
151 ("v6", Some(sym::arm_target_feature)),
152 ("v6k", Some(sym::arm_target_feature)),
153 ("v6t2", Some(sym::arm_target_feature)),
154 ("v7", Some(sym::arm_target_feature)),
155 ("v8", Some(sym::arm_target_feature)),
156 ("vfp2", Some(sym::arm_target_feature)),
157 ("vfp3", Some(sym::arm_target_feature)),
158 ("vfp4", Some(sym::arm_target_feature)),
161 const AARCH64_WHITELIST: &[(&str, Option<Symbol>)] = &[
162 ("fp", Some(sym::aarch64_target_feature)),
163 ("neon", Some(sym::aarch64_target_feature)),
164 ("sve", Some(sym::aarch64_target_feature)),
165 ("crc", Some(sym::aarch64_target_feature)),
166 ("crypto", Some(sym::aarch64_target_feature)),
167 ("ras", Some(sym::aarch64_target_feature)),
168 ("lse", Some(sym::aarch64_target_feature)),
169 ("rdm", Some(sym::aarch64_target_feature)),
170 ("fp16", Some(sym::aarch64_target_feature)),
171 ("rcpc", Some(sym::aarch64_target_feature)),
172 ("dotprod", Some(sym::aarch64_target_feature)),
173 ("tme", Some(sym::aarch64_target_feature)),
174 ("v8.1a", Some(sym::aarch64_target_feature)),
175 ("v8.2a", Some(sym::aarch64_target_feature)),
176 ("v8.3a", Some(sym::aarch64_target_feature)),
179 const X86_WHITELIST: &[(&str, Option<Symbol>)] = &[
180 ("adx", Some(sym::adx_target_feature)),
184 ("avx512bw", Some(sym::avx512_target_feature)),
185 ("avx512cd", Some(sym::avx512_target_feature)),
186 ("avx512dq", Some(sym::avx512_target_feature)),
187 ("avx512er", Some(sym::avx512_target_feature)),
188 ("avx512f", Some(sym::avx512_target_feature)),
189 ("avx512ifma", Some(sym::avx512_target_feature)),
190 ("avx512pf", Some(sym::avx512_target_feature)),
191 ("avx512vbmi", Some(sym::avx512_target_feature)),
192 ("avx512vl", Some(sym::avx512_target_feature)),
193 ("avx512vpopcntdq", Some(sym::avx512_target_feature)),
196 ("cmpxchg16b", Some(sym::cmpxchg16b_target_feature)),
197 ("f16c", Some(sym::f16c_target_feature)),
201 ("mmx", Some(sym::mmx_target_feature)),
202 ("movbe", Some(sym::movbe_target_feature)),
207 ("rtm", Some(sym::rtm_target_feature)),
214 ("sse4a", Some(sym::sse4a_target_feature)),
216 ("tbm", Some(sym::tbm_target_feature)),
223 const HEXAGON_WHITELIST: &[(&str, Option<Symbol>)] = &[
224 ("hvx", Some(sym::hexagon_target_feature)),
225 ("hvx-length128b", Some(sym::hexagon_target_feature)),
228 const POWERPC_WHITELIST: &[(&str, Option<Symbol>)] = &[
229 ("altivec", Some(sym::powerpc_target_feature)),
230 ("power8-altivec", Some(sym::powerpc_target_feature)),
231 ("power9-altivec", Some(sym::powerpc_target_feature)),
232 ("power8-vector", Some(sym::powerpc_target_feature)),
233 ("power9-vector", Some(sym::powerpc_target_feature)),
234 ("vsx", Some(sym::powerpc_target_feature)),
237 const MIPS_WHITELIST: &[(&str, Option<Symbol>)] =
238 &[("fp64", Some(sym::mips_target_feature)), ("msa", Some(sym::mips_target_feature))];
240 const RISCV_WHITELIST: &[(&str, Option<Symbol>)] = &[
241 ("m", Some(sym::riscv_target_feature)),
242 ("a", Some(sym::riscv_target_feature)),
243 ("c", Some(sym::riscv_target_feature)),
244 ("f", Some(sym::riscv_target_feature)),
245 ("d", Some(sym::riscv_target_feature)),
246 ("e", Some(sym::riscv_target_feature)),
249 const WASM_WHITELIST: &[(&str, Option<Symbol>)] =
250 &[("simd128", Some(sym::wasm_target_feature)), ("atomics", Some(sym::wasm_target_feature))];
252 /// When rustdoc is running, provide a list of all known features so that all their respective
253 /// primitives may be documented.
255 /// IMPORTANT: If you're adding another whitelist to the above lists, make sure to add it to this
257 pub fn all_known_features() -> impl Iterator<Item = (&'static str, Option<Symbol>)> {
261 .chain(AARCH64_WHITELIST.iter().cloned())
262 .chain(X86_WHITELIST.iter().cloned())
263 .chain(HEXAGON_WHITELIST.iter().cloned())
264 .chain(POWERPC_WHITELIST.iter().cloned())
265 .chain(MIPS_WHITELIST.iter().cloned())
266 .chain(RISCV_WHITELIST.iter().cloned())
267 .chain(WASM_WHITELIST.iter().cloned())
270 pub fn to_llvm_feature<'a>(sess: &Session, s: &'a str) -> &'a str {
271 let arch = if sess.target.target.arch == "x86_64" { "x86" } else { &*sess.target.target.arch };
273 ("x86", "pclmulqdq") => "pclmul",
274 ("x86", "rdrand") => "rdrnd",
275 ("x86", "bmi1") => "bmi",
276 ("x86", "cmpxchg16b") => "cx16",
277 ("aarch64", "fp") => "fp-armv8",
278 ("aarch64", "fp16") => "fullfp16",
283 pub fn target_features(sess: &Session) -> Vec<Symbol> {
284 let target_machine = create_informational_target_machine(sess);
285 target_feature_whitelist(sess)
287 .filter_map(|&(feature, gate)| {
288 if UnstableFeatures::from_environment().is_nightly_build() || gate.is_none() {
295 let llvm_feature = to_llvm_feature(sess, feature);
296 let cstr = CString::new(llvm_feature).unwrap();
297 unsafe { llvm::LLVMRustHasFeature(target_machine, cstr.as_ptr()) }
299 .map(|feature| Symbol::intern(feature))
303 pub fn target_feature_whitelist(sess: &Session) -> &'static [(&'static str, Option<Symbol>)] {
304 match &*sess.target.target.arch {
305 "arm" => ARM_WHITELIST,
306 "aarch64" => AARCH64_WHITELIST,
307 "x86" | "x86_64" => X86_WHITELIST,
308 "hexagon" => HEXAGON_WHITELIST,
309 "mips" | "mips64" => MIPS_WHITELIST,
310 "powerpc" | "powerpc64" => POWERPC_WHITELIST,
311 "riscv32" | "riscv64" => RISCV_WHITELIST,
312 "wasm32" => WASM_WHITELIST,
317 pub fn print_version() {
318 // Can be called without initializing LLVM
320 println!("LLVM version: {}.{}", llvm::LLVMRustVersionMajor(), llvm::LLVMRustVersionMinor());
324 pub fn get_major_version() -> u32 {
325 unsafe { llvm::LLVMRustVersionMajor() }
328 pub fn print_passes() {
329 // Can be called without initializing LLVM
331 llvm::LLVMRustPrintPasses();
335 pub(crate) fn print(req: PrintRequest, sess: &Session) {
337 let tm = create_informational_target_machine(sess);
340 PrintRequest::TargetCPUs => llvm::LLVMRustPrintTargetCPUs(tm),
341 PrintRequest::TargetFeatures => llvm::LLVMRustPrintTargetFeatures(tm),
342 _ => bug!("rustc_codegen_llvm can't handle print request: {:?}", req),
347 pub fn target_cpu(sess: &Session) -> &str {
348 let name = match sess.opts.cg.target_cpu {
350 None => &*sess.target.target.options.cpu,
352 if name != "native" {
358 let ptr = llvm::LLVMRustGetHostCPUName(&mut len);
359 str::from_utf8(slice::from_raw_parts(ptr as *const u8, len)).unwrap()