1 use crate::back
::write
::create_informational_target_machine
;
2 use crate::{llvm, llvm_util}
;
4 use libloading
::Library
;
5 use rustc_codegen_ssa
::target_features
::{
6 supported_target_features
, tied_target_features
, RUSTC_SPECIFIC_FEATURES
,
8 use rustc_data_structures
::fx
::{FxHashMap, FxHashSet}
;
9 use rustc_data_structures
::small_c_str
::SmallCStr
;
10 use rustc_fs_util
::path_to_c_string
;
11 use rustc_middle
::bug
;
12 use rustc_session
::config
::PrintRequest
;
13 use rustc_session
::Session
;
14 use rustc_span
::symbol
::Symbol
;
15 use rustc_target
::spec
::{MergeFunctions, PanicStrategy}
;
16 use smallvec
::{smallvec, SmallVec}
;
17 use std
::ffi
::{CStr, CString}
;
27 static INIT
: Once
= Once
::new();
29 pub(crate) fn init(sess
: &Session
) {
31 // Before we touch LLVM, make sure that multithreading is enabled.
32 if llvm
::LLVMIsMultithreaded() != 1 {
33 bug
!("LLVM compiled without support for threads");
42 if !INIT
.is_completed() {
43 bug
!("LLVM is not initialized");
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);
52 llvm
::LLVMRustInstallFatalErrorHandler();
53 // On Windows, an LLVM assertion will open an Abort/Retry/Ignore dialog
54 // box for the purpose of launching a debugger. However, on CI this will
55 // cause it to hang until it times out, which can take several hours.
56 if std
::env
::var_os("CI").is_some() {
57 llvm
::LLVMRustDisableSystemDialogsOnCrash();
60 fn llvm_arg_to_arg_name(full_arg
: &str) -> &str {
61 full_arg
.trim().split(|c
: char| c
== '
='
|| c
.is_whitespace()).next().unwrap_or("")
64 let cg_opts
= sess
.opts
.cg
.llvm_args
.iter().map(AsRef
::as_ref
);
65 let tg_opts
= sess
.target
.llvm_args
.iter().map(AsRef
::as_ref
);
66 let sess_args
= cg_opts
.chain(tg_opts
);
68 let user_specified_args
: FxHashSet
<_
> =
69 sess_args
.clone().map(|s
| llvm_arg_to_arg_name(s
)).filter(|s
| !s
.is_empty()).collect();
72 // This adds the given argument to LLVM. Unless `force` is true
73 // user specified arguments are *not* overridden.
74 let mut add
= |arg
: &str, force
: bool
| {
75 if force
|| !user_specified_args
.contains(llvm_arg_to_arg_name(arg
)) {
76 let s
= CString
::new(arg
).unwrap();
77 llvm_args
.push(s
.as_ptr());
81 // Set the llvm "program name" to make usage and invalid argument messages more clear.
82 add("rustc -Cllvm-args=\"...\" with", true);
83 if sess
.time_llvm_passes() {
84 add("-time-passes", false);
86 if sess
.print_llvm_passes() {
87 add("-debug-pass=Structure", false);
89 if sess
.target
.generate_arange_section
90 && !sess
.opts
.unstable_opts
.no_generate_arange_section
92 add("-generate-arange-section", false);
95 // Disable the machine outliner by default in LLVM versions 11 and LLVM
96 // version 12, where it leads to miscompilation.
99 // - https://github.com/rust-lang/rust/issues/85351
100 // - https://reviews.llvm.org/D103167
101 if llvm_util
::get_version() < (13, 0, 0) {
102 add("-enable-machine-outliner=never", false);
105 match sess
.opts
.unstable_opts
.merge_functions
.unwrap_or(sess
.target
.merge_functions
) {
106 MergeFunctions
::Disabled
| MergeFunctions
::Trampolines
=> {}
107 MergeFunctions
::Aliases
=> {
108 add("-mergefunc-use-aliases", false);
112 if sess
.target
.os
== "emscripten" && sess
.panic_strategy() == PanicStrategy
::Unwind
{
113 add("-enable-emscripten-cxx-exceptions", false);
116 // HACK(eddyb) LLVM inserts `llvm.assume` calls to preserve align attributes
117 // during inlining. Unfortunately these may block other optimizations.
118 add("-preserve-alignment-assumptions-during-inlining=false", false);
120 // Use non-zero `import-instr-limit` multiplier for cold callsites.
121 add("-import-cold-multiplier=0.1", false);
123 for arg
in sess_args
{
128 if sess
.opts
.unstable_opts
.llvm_time_trace
{
129 llvm
::LLVMTimeTraceProfilerInitialize();
132 llvm
::LLVMInitializePasses();
134 // Use the legacy plugin registration if we don't use the new pass manager
135 if !should_use_new_llvm_pass_manager(
136 &sess
.opts
.unstable_opts
.new_llvm_pass_manager
,
139 // Register LLVM plugins by loading them into the compiler process.
140 for plugin
in &sess
.opts
.unstable_opts
.llvm_plugins
{
141 let lib
= Library
::new(plugin
).unwrap_or_else(|e
| bug
!("couldn't load plugin: {}", e
));
142 debug
!("LLVM plugin loaded successfully {:?} ({})", lib
, plugin
);
144 // Intentionally leak the dynamic library. We can't ever unload it
145 // since the library can make things that will live arbitrarily long.
150 rustc_llvm
::initialize_available_targets();
152 llvm
::LLVMRustSetLLVMOptions(llvm_args
.len() as c_int
, llvm_args
.as_ptr());
155 pub fn time_trace_profiler_finish(file_name
: &Path
) {
157 let file_name
= path_to_c_string(file_name
);
158 llvm
::LLVMTimeTraceProfilerFinish(file_name
.as_ptr());
162 // WARNING: the features after applying `to_llvm_features` must be known
163 // to LLVM or the feature detection code will walk past the end of the feature
164 // array, leading to crashes.
166 // To find a list of LLVM's names, check llvm-project/llvm/include/llvm/Support/*TargetParser.def
167 // where the * matches the architecture's name
168 // Beware to not use the llvm github project for this, but check the git submodule
169 // found in src/llvm-project
170 // Though note that Rust can also be build with an external precompiled version of LLVM
171 // which might lead to failures if the oldest tested / supported LLVM version
172 // doesn't yet support the relevant intrinsics
173 pub fn to_llvm_features
<'a
>(sess
: &Session
, s
: &'a
str) -> SmallVec
<[&'a
str; 2]> {
174 let arch
= if sess
.target
.arch
== "x86_64" { "x86" }
else { &*sess.target.arch }
;
176 ("x86", "sse4.2") => {
177 if get_version() >= (14, 0, 0) {
178 smallvec
!["sse4.2", "crc32"]
183 ("x86", "pclmulqdq") => smallvec
!["pclmul"],
184 ("x86", "rdrand") => smallvec
!["rdrnd"],
185 ("x86", "bmi1") => smallvec
!["bmi"],
186 ("x86", "cmpxchg16b") => smallvec
!["cx16"],
187 ("x86", "avx512vaes") => smallvec
!["vaes"],
188 ("x86", "avx512gfni") => smallvec
!["gfni"],
189 ("x86", "avx512vpclmulqdq") => smallvec
!["vpclmulqdq"],
190 ("aarch64", "rcpc2") => smallvec
!["rcpc-immo"],
191 ("aarch64", "dpb") => smallvec
!["ccpp"],
192 ("aarch64", "dpb2") => smallvec
!["ccdp"],
193 ("aarch64", "frintts") => smallvec
!["fptoint"],
194 ("aarch64", "fcma") => smallvec
!["complxnum"],
195 ("aarch64", "pmuv3") => smallvec
!["perfmon"],
196 ("aarch64", "paca") => smallvec
!["pauth"],
197 ("aarch64", "pacg") => smallvec
!["pauth"],
198 // Rust ties fp and neon together. In LLVM neon implicitly enables fp,
199 // but we manually enable neon when a feature only implicitly enables fp
200 ("aarch64", "f32mm") => smallvec
!["f32mm", "neon"],
201 ("aarch64", "f64mm") => smallvec
!["f64mm", "neon"],
202 ("aarch64", "fhm") => smallvec
!["fp16fml", "neon"],
203 ("aarch64", "fp16") => smallvec
!["fullfp16", "neon"],
204 ("aarch64", "jsconv") => smallvec
!["jsconv", "neon"],
205 ("aarch64", "sve") => smallvec
!["sve", "neon"],
206 ("aarch64", "sve2") => smallvec
!["sve2", "neon"],
207 ("aarch64", "sve2-aes") => smallvec
!["sve2-aes", "neon"],
208 ("aarch64", "sve2-sm4") => smallvec
!["sve2-sm4", "neon"],
209 ("aarch64", "sve2-sha3") => smallvec
!["sve2-sha3", "neon"],
210 ("aarch64", "sve2-bitperm") => smallvec
!["sve2-bitperm", "neon"],
211 (_
, s
) => smallvec
![s
],
215 // Given a map from target_features to whether they are enabled or disabled,
216 // ensure only valid combinations are allowed.
217 pub fn check_tied_features(
219 features
: &FxHashMap
<&str, bool
>,
220 ) -> Option
<&'
static [&'
static str]> {
221 if !features
.is_empty() {
222 for tied
in tied_target_features(sess
) {
223 // Tied features must be set to the same value, or not set at all
224 let mut tied_iter
= tied
.iter();
225 let enabled
= features
.get(tied_iter
.next().unwrap());
226 if tied_iter
.any(|f
| enabled
!= features
.get(f
)) {
234 // Used to generate cfg variables and apply features
235 // Must express features in the way Rust understands them
236 pub fn target_features(sess
: &Session
, allow_unstable
: bool
) -> Vec
<Symbol
> {
237 let target_machine
= create_informational_target_machine(sess
);
238 let mut features
: Vec
<Symbol
> = supported_target_features(sess
)
240 .filter_map(|&(feature
, gate
)| {
241 if sess
.is_nightly_build() || allow_unstable
|| gate
.is_none() {
248 // check that all features in a given smallvec are enabled
249 for llvm_feature
in to_llvm_features(sess
, feature
) {
250 let cstr
= SmallCStr
::new(llvm_feature
);
251 if !unsafe { llvm::LLVMRustHasFeature(target_machine, cstr.as_ptr()) }
{
257 .map(|feature
| Symbol
::intern(feature
))
260 // LLVM 14 changed the ABI for i128 arguments to __float/__fix builtins on Win64
261 // (see https://reviews.llvm.org/D110413). This unstable target feature is intended for use
262 // by compiler-builtins, to export the builtins with the expected, LLVM-version-dependent ABI.
263 // The target feature can be dropped once we no longer support older LLVM versions.
264 if sess
.is_nightly_build() && get_version() >= (14, 0, 0) {
265 features
.push(Symbol
::intern("llvm14-builtins-abi"));
270 pub fn print_version() {
271 let (major
, minor
, patch
) = get_version();
272 println
!("LLVM version: {}.{}.{}", major
, minor
, patch
);
275 pub fn get_version() -> (u32, u32, u32) {
276 // Can be called without initializing LLVM
278 (llvm
::LLVMRustVersionMajor(), llvm
::LLVMRustVersionMinor(), llvm
::LLVMRustVersionPatch())
282 pub fn print_passes() {
283 // Can be called without initializing LLVM
285 llvm
::LLVMRustPrintPasses();
289 fn llvm_target_features(tm
: &llvm
::TargetMachine
) -> Vec
<(&str, &str)> {
290 let len
= unsafe { llvm::LLVMRustGetTargetFeaturesCount(tm) }
;
291 let mut ret
= Vec
::with_capacity(len
);
294 let mut feature
= ptr
::null();
295 let mut desc
= ptr
::null();
296 llvm
::LLVMRustGetTargetFeature(tm
, i
, &mut feature
, &mut desc
);
297 if feature
.is_null() || desc
.is_null() {
298 bug
!("LLVM returned a `null` target feature string");
300 let feature
= CStr
::from_ptr(feature
).to_str().unwrap_or_else(|e
| {
301 bug
!("LLVM returned a non-utf8 feature string: {}", e
);
303 let desc
= CStr
::from_ptr(desc
).to_str().unwrap_or_else(|e
| {
304 bug
!("LLVM returned a non-utf8 feature string: {}", e
);
306 ret
.push((feature
, desc
));
312 fn print_target_features(sess
: &Session
, tm
: &llvm
::TargetMachine
) {
313 let mut target_features
= llvm_target_features(tm
);
314 let mut rustc_target_features
= supported_target_features(sess
)
316 .filter_map(|(feature
, _gate
)| {
317 for llvm_feature
in to_llvm_features(sess
, *feature
) {
318 // LLVM asserts that these are sorted. LLVM and Rust both use byte comparison for these strings.
319 match target_features
.binary_search_by_key(&llvm_feature
, |(f
, _d
)| f
).ok().map(
321 let (_f
, desc
) = target_features
.remove(index
);
325 Some(v
) => return Some(v
),
331 .collect
::<Vec
<_
>>();
332 rustc_target_features
.extend_from_slice(&[(
334 "Enables C Run-time Libraries to be statically linked",
336 let max_feature_len
= target_features
338 .chain(rustc_target_features
.iter())
339 .map(|(feature
, _desc
)| feature
.len())
343 println
!("Features supported by rustc for this target:");
344 for (feature
, desc
) in &rustc_target_features
{
345 println
!(" {1:0$} - {2}.", max_feature_len
, feature
, desc
);
347 println
!("\nCode-generation features supported by LLVM for this target:");
348 for (feature
, desc
) in &target_features
{
349 println
!(" {1:0$} - {2}.", max_feature_len
, feature
, desc
);
351 if target_features
.is_empty() {
352 println
!(" Target features listing is not supported by this LLVM version.");
354 println
!("\nUse +feature to enable a feature, or -feature to disable it.");
355 println
!("For example, rustc -C target-cpu=mycpu -C target-feature=+feature1,-feature2\n");
356 println
!("Code-generation features cannot be used in cfg or #[target_feature],");
357 println
!("and may be renamed or removed in a future version of LLVM or rustc.\n");
360 pub(crate) fn print(req
: PrintRequest
, sess
: &Session
) {
362 let tm
= create_informational_target_machine(sess
);
364 PrintRequest
::TargetCPUs
=> unsafe { llvm::LLVMRustPrintTargetCPUs(tm) }
,
365 PrintRequest
::TargetFeatures
=> print_target_features(sess
, tm
),
366 _
=> bug
!("rustc_codegen_llvm can't handle print request: {:?}", req
),
370 fn handle_native(name
: &str) -> &str {
371 if name
!= "native" {
377 let ptr
= llvm
::LLVMRustGetHostCPUName(&mut len
);
378 str::from_utf8(slice
::from_raw_parts(ptr
as *const u8, len
)).unwrap()
382 pub fn target_cpu(sess
: &Session
) -> &str {
383 match sess
.opts
.cg
.target_cpu
{
384 Some(ref name
) => handle_native(name
),
385 None
=> handle_native(sess
.target
.cpu
.as_ref()),
389 /// The list of LLVM features computed from CLI flags (`-Ctarget-cpu`, `-Ctarget-feature`,
390 /// `--target` and similar).
391 pub(crate) fn global_llvm_features(sess
: &Session
, diagnostics
: bool
) -> Vec
<String
> {
392 // Features that come earlier are overridden by conflicting features later in the string.
393 // Typically we'll want more explicit settings to override the implicit ones, so:
395 // * Features from -Ctarget-cpu=*; are overridden by [^1]
396 // * Features implied by --target; are overridden by
397 // * Features from -Ctarget-feature; are overridden by
398 // * function specific features.
400 // [^1]: target-cpu=native is handled here, other target-cpu values are handled implicitly
401 // through LLVM TargetMachine implementation.
403 // FIXME(nagisa): it isn't clear what's the best interaction between features implied by
404 // `-Ctarget-cpu` and `--target` are. On one hand, you'd expect CLI arguments to always
405 // override anything that's implicit, so e.g. when there's no `--target` flag, features implied
406 // the host target are overridden by `-Ctarget-cpu=*`. On the other hand, what about when both
407 // `--target` and `-Ctarget-cpu=*` are specified? Both then imply some target features and both
408 // flags are specified by the user on the CLI. It isn't as clear-cut which order of precedence
409 // should be taken in cases like these.
410 let mut features
= vec
![];
412 // -Ctarget-cpu=native
413 match sess
.opts
.cg
.target_cpu
{
414 Some(ref s
) if s
== "native" => {
415 let features_string
= unsafe {
416 let ptr
= llvm
::LLVMGetHostCPUFeatures();
417 let features_string
= if !ptr
.is_null() {
420 .unwrap_or_else(|e
| {
421 bug
!("LLVM returned a non-utf8 features string: {}", e
);
425 bug
!("could not allocate host CPU features, LLVM returned a `null` string");
428 llvm
::LLVMDisposeMessage(ptr
);
432 features
.extend(features_string
.split('
,'
).map(String
::from
));
437 // Features implied by an implicit or explicit `--target`.
442 .filter(|v
| !v
.is_empty() && backend_feature_name(v
).is_some())
447 let supported_features
= supported_target_features(sess
);
448 let mut featsmap
= FxHashMap
::default();
455 let enable_disable
= match s
.chars().next() {
457 Some(c @ '
+'
| c @ '
-'
) => c
,
460 let mut diag
= sess
.struct_warn(&format
!(
461 "unknown feature specified for `-Ctarget-feature`: `{}`",
464 diag
.note("features must begin with a `+` to enable or `-` to disable it");
471 let feature
= backend_feature_name(s
)?
;
472 // Warn against use of LLVM specific feature names on the CLI.
473 if diagnostics
&& !supported_features
.iter().any(|&(v
, _
)| v
== feature
) {
474 let rust_feature
= supported_features
.iter().find_map(|&(rust_feature
, _
)| {
475 let llvm_features
= to_llvm_features(sess
, rust_feature
);
476 if llvm_features
.contains(&feature
) && !llvm_features
.contains(&rust_feature
) {
482 let mut diag
= sess
.struct_warn(&format
!(
483 "unknown feature specified for `-Ctarget-feature`: `{}`",
486 diag
.note("it is still passed through to the codegen backend");
487 if let Some(rust_feature
) = rust_feature
{
488 diag
.help(&format
!("you might have meant: `{}`", rust_feature
));
490 diag
.note("consider filing a feature request");
496 // FIXME(nagisa): figure out how to not allocate a full hashset here.
497 featsmap
.insert(feature
, enable_disable
== '
+'
);
500 // rustc-specific features do not get passed down to LLVM…
501 if RUSTC_SPECIFIC_FEATURES
.contains(&feature
) {
504 // ... otherwise though we run through `to_llvm_features` when
505 // passing requests down to LLVM. This means that all in-language
506 // features also work on the command line instead of having two
507 // different names when the LLVM name and the Rust name differ.
509 to_llvm_features(sess
, feature
)
511 .map(move |f
| format
!("{}{}", enable_disable
, f
)),
515 features
.extend(feats
);
517 if diagnostics
&& let Some(f
) = check_tied_features(sess
, &featsmap
) {
519 "target features {} must all be enabled or disabled together",
527 /// Returns a feature name for the given `+feature` or `-feature` string.
529 /// Only allows features that are backend specific (i.e. not [`RUSTC_SPECIFIC_FEATURES`].)
530 fn backend_feature_name(s
: &str) -> Option
<&str> {
531 // features must start with a `+` or `-`.
532 let feature
= s
.strip_prefix(&['
+'
, '
-'
][..]).unwrap_or_else(|| {
533 bug
!("target feature `{}` must begin with a `+` or `-`", s
);
535 // Rustc-specific feature requests like `+crt-static` or `-crt-static`
536 // are not passed down to LLVM.
537 if RUSTC_SPECIFIC_FEATURES
.contains(&feature
) {
543 pub fn tune_cpu(sess
: &Session
) -> Option
<&str> {
544 let name
= sess
.opts
.unstable_opts
.tune_cpu
.as_ref()?
;
545 Some(handle_native(name
))
548 pub(crate) fn should_use_new_llvm_pass_manager(user_opt
: &Option
<bool
>, target_arch
: &str) -> bool
{
549 // The new pass manager is enabled by default for LLVM >= 13.
550 // This matches Clang, which also enables it since Clang 13.
552 // Since LLVM 15, the legacy pass manager is no longer supported.
553 if llvm_util
::get_version() >= (15, 0, 0) {
557 // There are some perf issues with the new pass manager when targeting
558 // s390x with LLVM 13, so enable the new pass manager only with LLVM 14.
559 // See https://github.com/rust-lang/rust/issues/89609.
560 let min_version
= if target_arch
== "s390x" { 14 }
else { 13 }
;
561 user_opt
.unwrap_or_else(|| llvm_util
::get_version() >= (min_version
, 0, 0))