1 use crate::back::write::create_informational_target_machine;
4 use rustc_codegen_ssa::target_features::{
5 supported_target_features, tied_target_features, RUSTC_SPECIFIC_FEATURES,
7 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
8 use rustc_data_structures::small_c_str::SmallCStr;
9 use rustc_fs_util::path_to_c_string;
10 use rustc_middle::bug;
11 use rustc_session::config::PrintRequest;
12 use rustc_session::Session;
13 use rustc_span::symbol::Symbol;
14 use rustc_target::spec::{MergeFunctions, PanicStrategy};
15 use smallvec::{smallvec, SmallVec};
16 use std::ffi::{CStr, CString};
24 static INIT: Once = Once::new();
26 pub(crate) fn init(sess: &Session) {
28 // Before we touch LLVM, make sure that multithreading is enabled.
29 if llvm::LLVMIsMultithreaded() != 1 {
30 bug!("LLVM compiled without support for threads");
39 if !INIT.is_completed() {
40 bug!("LLVM is not initialized");
44 unsafe fn configure_llvm(sess: &Session) {
45 let n_args = sess.opts.cg.llvm_args.len() + sess.target.llvm_args.len();
46 let mut llvm_c_strs = Vec::with_capacity(n_args + 1);
47 let mut llvm_args = Vec::with_capacity(n_args + 1);
49 llvm::LLVMRustInstallFatalErrorHandler();
50 // On Windows, an LLVM assertion will open an Abort/Retry/Ignore dialog
51 // box for the purpose of launching a debugger. However, on CI this will
52 // cause it to hang until it times out, which can take several hours.
53 if std::env::var_os("CI").is_some() {
54 llvm::LLVMRustDisableSystemDialogsOnCrash();
57 fn llvm_arg_to_arg_name(full_arg: &str) -> &str {
58 full_arg.trim().split(|c: char| c == '=' || c.is_whitespace()).next().unwrap_or("")
61 let cg_opts = sess.opts.cg.llvm_args.iter().map(AsRef::as_ref);
62 let tg_opts = sess.target.llvm_args.iter().map(AsRef::as_ref);
63 let sess_args = cg_opts.chain(tg_opts);
65 let user_specified_args: FxHashSet<_> =
66 sess_args.clone().map(|s| llvm_arg_to_arg_name(s)).filter(|s| !s.is_empty()).collect();
69 // This adds the given argument to LLVM. Unless `force` is true
70 // user specified arguments are *not* overridden.
71 let mut add = |arg: &str, force: bool| {
72 if force || !user_specified_args.contains(llvm_arg_to_arg_name(arg)) {
73 let s = CString::new(arg).unwrap();
74 llvm_args.push(s.as_ptr());
78 // Set the llvm "program name" to make usage and invalid argument messages more clear.
79 add("rustc -Cllvm-args=\"...\" with", true);
80 if sess.time_llvm_passes() {
81 add("-time-passes", false);
83 if sess.print_llvm_passes() {
84 add("-debug-pass=Structure", false);
86 if sess.target.generate_arange_section
87 && !sess.opts.unstable_opts.no_generate_arange_section
89 add("-generate-arange-section", false);
92 match sess.opts.unstable_opts.merge_functions.unwrap_or(sess.target.merge_functions) {
93 MergeFunctions::Disabled | MergeFunctions::Trampolines => {}
94 MergeFunctions::Aliases => {
95 add("-mergefunc-use-aliases", false);
99 if sess.target.os == "emscripten" && sess.panic_strategy() == PanicStrategy::Unwind {
100 add("-enable-emscripten-cxx-exceptions", false);
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);
107 // Use non-zero `import-instr-limit` multiplier for cold callsites.
108 add("-import-cold-multiplier=0.1", false);
110 for arg in sess_args {
115 if sess.opts.unstable_opts.llvm_time_trace {
116 llvm::LLVMTimeTraceProfilerInitialize();
119 llvm::LLVMInitializePasses();
121 rustc_llvm::initialize_available_targets();
123 llvm::LLVMRustSetLLVMOptions(llvm_args.len() as c_int, llvm_args.as_ptr());
126 pub fn time_trace_profiler_finish(file_name: &Path) {
128 let file_name = path_to_c_string(file_name);
129 llvm::LLVMTimeTraceProfilerFinish(file_name.as_ptr());
133 // WARNING: the features after applying `to_llvm_features` must be known
134 // to LLVM or the feature detection code will walk past the end of the feature
135 // array, leading to crashes.
137 // To find a list of LLVM's names, check llvm-project/llvm/include/llvm/Support/*TargetParser.def
138 // where the * matches the architecture's name
140 // For targets not present in the above location, see llvm-project/llvm/lib/Target/{ARCH}/*.td
141 // where `{ARCH}` is the architecture name. Look for instances of `SubtargetFeature`.
143 // Beware to not use the llvm github project for this, but check the git submodule
144 // found in src/llvm-project
145 // Though note that Rust can also be build with an external precompiled version of LLVM
146 // which might lead to failures if the oldest tested / supported LLVM version
147 // doesn't yet support the relevant intrinsics
148 pub fn to_llvm_features<'a>(sess: &Session, s: &'a str) -> SmallVec<[&'a str; 2]> {
149 let arch = if sess.target.arch == "x86_64" { "x86" } else { &*sess.target.arch };
151 ("x86", "sse4.2") => {
152 if get_version() >= (14, 0, 0) {
153 smallvec!["sse4.2", "crc32"]
158 ("x86", "pclmulqdq") => smallvec!["pclmul"],
159 ("x86", "rdrand") => smallvec!["rdrnd"],
160 ("x86", "bmi1") => smallvec!["bmi"],
161 ("x86", "cmpxchg16b") => smallvec!["cx16"],
162 ("x86", "avx512vaes") => smallvec!["vaes"],
163 ("x86", "avx512gfni") => smallvec!["gfni"],
164 ("x86", "avx512vpclmulqdq") => smallvec!["vpclmulqdq"],
165 ("aarch64", "rcpc2") => smallvec!["rcpc-immo"],
166 ("aarch64", "dpb") => smallvec!["ccpp"],
167 ("aarch64", "dpb2") => smallvec!["ccdp"],
168 ("aarch64", "frintts") => smallvec!["fptoint"],
169 ("aarch64", "fcma") => smallvec!["complxnum"],
170 ("aarch64", "pmuv3") => smallvec!["perfmon"],
171 ("aarch64", "paca") => smallvec!["pauth"],
172 ("aarch64", "pacg") => smallvec!["pauth"],
173 // Rust ties fp and neon together. In LLVM neon implicitly enables fp,
174 // but we manually enable neon when a feature only implicitly enables fp
175 ("aarch64", "f32mm") => smallvec!["f32mm", "neon"],
176 ("aarch64", "f64mm") => smallvec!["f64mm", "neon"],
177 ("aarch64", "fhm") => smallvec!["fp16fml", "neon"],
178 ("aarch64", "fp16") => smallvec!["fullfp16", "neon"],
179 ("aarch64", "jsconv") => smallvec!["jsconv", "neon"],
180 ("aarch64", "sve") => smallvec!["sve", "neon"],
181 ("aarch64", "sve2") => smallvec!["sve2", "neon"],
182 ("aarch64", "sve2-aes") => smallvec!["sve2-aes", "neon"],
183 ("aarch64", "sve2-sm4") => smallvec!["sve2-sm4", "neon"],
184 ("aarch64", "sve2-sha3") => smallvec!["sve2-sha3", "neon"],
185 ("aarch64", "sve2-bitperm") => smallvec!["sve2-bitperm", "neon"],
186 (_, s) => smallvec![s],
190 // Given a map from target_features to whether they are enabled or disabled,
191 // ensure only valid combinations are allowed.
192 pub fn check_tied_features(
194 features: &FxHashMap<&str, bool>,
195 ) -> Option<&'static [&'static str]> {
196 if !features.is_empty() {
197 for tied in tied_target_features(sess) {
198 // Tied features must be set to the same value, or not set at all
199 let mut tied_iter = tied.iter();
200 let enabled = features.get(tied_iter.next().unwrap());
201 if tied_iter.any(|f| enabled != features.get(f)) {
209 // Used to generate cfg variables and apply features
210 // Must express features in the way Rust understands them
211 pub fn target_features(sess: &Session, allow_unstable: bool) -> Vec<Symbol> {
212 let target_machine = create_informational_target_machine(sess);
213 let mut features: Vec<Symbol> = supported_target_features(sess)
215 .filter_map(|&(feature, gate)| {
216 if sess.is_nightly_build() || allow_unstable || gate.is_none() {
223 // check that all features in a given smallvec are enabled
224 for llvm_feature in to_llvm_features(sess, feature) {
225 let cstr = SmallCStr::new(llvm_feature);
226 if !unsafe { llvm::LLVMRustHasFeature(target_machine, cstr.as_ptr()) } {
232 .map(|feature| Symbol::intern(feature))
235 // LLVM 14 changed the ABI for i128 arguments to __float/__fix builtins on Win64
236 // (see https://reviews.llvm.org/D110413). This unstable target feature is intended for use
237 // by compiler-builtins, to export the builtins with the expected, LLVM-version-dependent ABI.
238 // The target feature can be dropped once we no longer support older LLVM versions.
239 if sess.is_nightly_build() && get_version() >= (14, 0, 0) {
240 features.push(Symbol::intern("llvm14-builtins-abi"));
245 pub fn print_version() {
246 let (major, minor, patch) = get_version();
247 println!("LLVM version: {}.{}.{}", major, minor, patch);
250 pub fn get_version() -> (u32, u32, u32) {
251 // Can be called without initializing LLVM
253 (llvm::LLVMRustVersionMajor(), llvm::LLVMRustVersionMinor(), llvm::LLVMRustVersionPatch())
257 pub fn print_passes() {
258 // Can be called without initializing LLVM
260 llvm::LLVMRustPrintPasses();
264 fn llvm_target_features(tm: &llvm::TargetMachine) -> Vec<(&str, &str)> {
265 let len = unsafe { llvm::LLVMRustGetTargetFeaturesCount(tm) };
266 let mut ret = Vec::with_capacity(len);
269 let mut feature = ptr::null();
270 let mut desc = ptr::null();
271 llvm::LLVMRustGetTargetFeature(tm, i, &mut feature, &mut desc);
272 if feature.is_null() || desc.is_null() {
273 bug!("LLVM returned a `null` target feature string");
275 let feature = CStr::from_ptr(feature).to_str().unwrap_or_else(|e| {
276 bug!("LLVM returned a non-utf8 feature string: {}", e);
278 let desc = CStr::from_ptr(desc).to_str().unwrap_or_else(|e| {
279 bug!("LLVM returned a non-utf8 feature string: {}", e);
281 ret.push((feature, desc));
287 fn print_target_features(sess: &Session, tm: &llvm::TargetMachine) {
288 let mut target_features = llvm_target_features(tm);
289 let mut rustc_target_features = supported_target_features(sess)
291 .filter_map(|(feature, _gate)| {
292 for llvm_feature in to_llvm_features(sess, *feature) {
293 // LLVM asserts that these are sorted. LLVM and Rust both use byte comparison for these strings.
294 match target_features.binary_search_by_key(&llvm_feature, |(f, _d)| f).ok().map(
296 let (_f, desc) = target_features.remove(index);
300 Some(v) => return Some(v),
306 .collect::<Vec<_>>();
307 rustc_target_features.extend_from_slice(&[(
309 "Enables C Run-time Libraries to be statically linked",
311 let max_feature_len = target_features
313 .chain(rustc_target_features.iter())
314 .map(|(feature, _desc)| feature.len())
318 println!("Features supported by rustc for this target:");
319 for (feature, desc) in &rustc_target_features {
320 println!(" {1:0$} - {2}.", max_feature_len, feature, desc);
322 println!("\nCode-generation features supported by LLVM for this target:");
323 for (feature, desc) in &target_features {
324 println!(" {1:0$} - {2}.", max_feature_len, feature, desc);
326 if target_features.is_empty() {
327 println!(" Target features listing is not supported by this LLVM version.");
329 println!("\nUse +feature to enable a feature, or -feature to disable it.");
330 println!("For example, rustc -C target-cpu=mycpu -C target-feature=+feature1,-feature2\n");
331 println!("Code-generation features cannot be used in cfg or #[target_feature],");
332 println!("and may be renamed or removed in a future version of LLVM or rustc.\n");
335 pub(crate) fn print(req: PrintRequest, sess: &Session) {
337 let tm = create_informational_target_machine(sess);
339 PrintRequest::TargetCPUs => unsafe { llvm::LLVMRustPrintTargetCPUs(tm) },
340 PrintRequest::TargetFeatures => print_target_features(sess, tm),
341 _ => bug!("rustc_codegen_llvm can't handle print request: {:?}", req),
345 fn handle_native(name: &str) -> &str {
346 if name != "native" {
352 let ptr = llvm::LLVMRustGetHostCPUName(&mut len);
353 str::from_utf8(slice::from_raw_parts(ptr as *const u8, len)).unwrap()
357 pub fn target_cpu(sess: &Session) -> &str {
358 match sess.opts.cg.target_cpu {
359 Some(ref name) => handle_native(name),
360 None => handle_native(sess.target.cpu.as_ref()),
364 /// The list of LLVM features computed from CLI flags (`-Ctarget-cpu`, `-Ctarget-feature`,
365 /// `--target` and similar).
366 pub(crate) fn global_llvm_features(sess: &Session, diagnostics: bool) -> Vec<String> {
367 // Features that come earlier are overridden by conflicting features later in the string.
368 // Typically we'll want more explicit settings to override the implicit ones, so:
370 // * Features from -Ctarget-cpu=*; are overridden by [^1]
371 // * Features implied by --target; are overridden by
372 // * Features from -Ctarget-feature; are overridden by
373 // * function specific features.
375 // [^1]: target-cpu=native is handled here, other target-cpu values are handled implicitly
376 // through LLVM TargetMachine implementation.
378 // FIXME(nagisa): it isn't clear what's the best interaction between features implied by
379 // `-Ctarget-cpu` and `--target` are. On one hand, you'd expect CLI arguments to always
380 // override anything that's implicit, so e.g. when there's no `--target` flag, features implied
381 // the host target are overridden by `-Ctarget-cpu=*`. On the other hand, what about when both
382 // `--target` and `-Ctarget-cpu=*` are specified? Both then imply some target features and both
383 // flags are specified by the user on the CLI. It isn't as clear-cut which order of precedence
384 // should be taken in cases like these.
385 let mut features = vec![];
387 // -Ctarget-cpu=native
388 match sess.opts.cg.target_cpu {
389 Some(ref s) if s == "native" => {
390 let features_string = unsafe {
391 let ptr = llvm::LLVMGetHostCPUFeatures();
392 let features_string = if !ptr.is_null() {
395 .unwrap_or_else(|e| {
396 bug!("LLVM returned a non-utf8 features string: {}", e);
400 bug!("could not allocate host CPU features, LLVM returned a `null` string");
403 llvm::LLVMDisposeMessage(ptr);
407 features.extend(features_string.split(',').map(String::from));
412 // Features implied by an implicit or explicit `--target`.
417 .filter(|v| !v.is_empty() && backend_feature_name(v).is_some())
418 // Drop +atomics-32 feature introduced in LLVM 15.
419 .filter(|v| *v != "+atomics-32" || get_version() >= (15, 0, 0))
424 let supported_features = supported_target_features(sess);
425 let mut featsmap = FxHashMap::default();
432 let enable_disable = match s.chars().next() {
434 Some(c @ '+' | c @ '-') => c,
437 let mut diag = sess.struct_warn(&format!(
438 "unknown feature specified for `-Ctarget-feature`: `{}`",
441 diag.note("features must begin with a `+` to enable or `-` to disable it");
448 let feature = backend_feature_name(s)?;
449 // Warn against use of LLVM specific feature names on the CLI.
450 if diagnostics && !supported_features.iter().any(|&(v, _)| v == feature) {
451 let rust_feature = supported_features.iter().find_map(|&(rust_feature, _)| {
452 let llvm_features = to_llvm_features(sess, rust_feature);
453 if llvm_features.contains(&feature) && !llvm_features.contains(&rust_feature) {
459 let mut diag = sess.struct_warn(&format!(
460 "unknown feature specified for `-Ctarget-feature`: `{}`",
463 diag.note("it is still passed through to the codegen backend");
464 if let Some(rust_feature) = rust_feature {
465 diag.help(&format!("you might have meant: `{}`", rust_feature));
467 diag.note("consider filing a feature request");
473 // FIXME(nagisa): figure out how to not allocate a full hashset here.
474 featsmap.insert(feature, enable_disable == '+');
477 // rustc-specific features do not get passed down to LLVM…
478 if RUSTC_SPECIFIC_FEATURES.contains(&feature) {
481 // ... otherwise though we run through `to_llvm_features` when
482 // passing requests down to LLVM. This means that all in-language
483 // features also work on the command line instead of having two
484 // different names when the LLVM name and the Rust name differ.
486 to_llvm_features(sess, feature)
488 .map(move |f| format!("{}{}", enable_disable, f)),
492 features.extend(feats);
494 if diagnostics && let Some(f) = check_tied_features(sess, &featsmap) {
496 "target features {} must all be enabled or disabled together",
504 /// Returns a feature name for the given `+feature` or `-feature` string.
506 /// Only allows features that are backend specific (i.e. not [`RUSTC_SPECIFIC_FEATURES`].)
507 fn backend_feature_name(s: &str) -> Option<&str> {
508 // features must start with a `+` or `-`.
509 let feature = s.strip_prefix(&['+', '-'][..]).unwrap_or_else(|| {
510 bug!("target feature `{}` must begin with a `+` or `-`", s);
512 // Rustc-specific feature requests like `+crt-static` or `-crt-static`
513 // are not passed down to LLVM.
514 if RUSTC_SPECIFIC_FEATURES.contains(&feature) {
520 pub fn tune_cpu(sess: &Session) -> Option<&str> {
521 let name = sess.opts.unstable_opts.tune_cpu.as_ref()?;
522 Some(handle_native(name))