]> git.proxmox.com Git - rustc.git/blob - compiler/rustc_codegen_llvm/src/llvm_util.rs
bump version to 1.80.1+dfsg1-1~bpo12+pve1
[rustc.git] / compiler / rustc_codegen_llvm / src / llvm_util.rs
1 use crate::back::write::create_informational_target_machine;
2 use crate::errors::{
3 FixedX18InvalidArch, InvalidTargetFeaturePrefix, PossibleFeature, TargetFeatureDisableOrEnable,
4 UnknownCTargetFeature, UnknownCTargetFeaturePrefix, UnstableCTargetFeature,
5 };
6 use crate::llvm;
7 use libc::c_int;
8 use rustc_codegen_ssa::base::wants_wasm_eh;
9 use rustc_codegen_ssa::traits::PrintBackendInfo;
10 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
11 use rustc_data_structures::small_c_str::SmallCStr;
12 use rustc_fs_util::path_to_c_string;
13 use rustc_middle::bug;
14 use rustc_session::config::{PrintKind, PrintRequest};
15 use rustc_session::Session;
16 use rustc_span::symbol::Symbol;
17 use rustc_target::spec::{MergeFunctions, PanicStrategy};
18 use rustc_target::target_features::RUSTC_SPECIFIC_FEATURES;
19
20 use std::ffi::{c_char, c_void, CStr, CString};
21 use std::path::Path;
22 use std::ptr;
23 use std::slice;
24 use std::str;
25 use std::sync::Once;
26
27 static INIT: Once = Once::new();
28
29 pub(crate) fn init(sess: &Session) {
30 unsafe {
31 // Before we touch LLVM, make sure that multithreading is enabled.
32 if llvm::LLVMIsMultithreaded() != 1 {
33 bug!("LLVM compiled without support for threads");
34 }
35 INIT.call_once(|| {
36 configure_llvm(sess);
37 });
38 }
39 }
40
41 fn require_inited() {
42 if !INIT.is_completed() {
43 bug!("LLVM is not initialized");
44 }
45 }
46
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);
51
52 llvm::LLVMRustInstallErrorHandlers();
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();
58 }
59
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("")
62 }
63
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);
67
68 let user_specified_args: FxHashSet<_> =
69 sess_args.clone().map(|s| llvm_arg_to_arg_name(s)).filter(|s| !s.is_empty()).collect();
70
71 {
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());
78 llvm_c_strs.push(s);
79 }
80 };
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.opts.unstable_opts.time_llvm_passes {
84 add("-time-passes", false);
85 }
86 if sess.opts.unstable_opts.print_llvm_passes {
87 add("-debug-pass=Structure", false);
88 }
89 if sess.target.generate_arange_section
90 && !sess.opts.unstable_opts.no_generate_arange_section
91 {
92 add("-generate-arange-section", false);
93 }
94
95 match sess.opts.unstable_opts.merge_functions.unwrap_or(sess.target.merge_functions) {
96 MergeFunctions::Disabled | MergeFunctions::Trampolines => {}
97 MergeFunctions::Aliases => {
98 add("-mergefunc-use-aliases", false);
99 }
100 }
101
102 if wants_wasm_eh(sess) {
103 add("-wasm-enable-eh", false);
104 }
105
106 if sess.target.os == "emscripten" && sess.panic_strategy() == PanicStrategy::Unwind {
107 add("-enable-emscripten-cxx-exceptions", false);
108 }
109
110 // HACK(eddyb) LLVM inserts `llvm.assume` calls to preserve align attributes
111 // during inlining. Unfortunately these may block other optimizations.
112 add("-preserve-alignment-assumptions-during-inlining=false", false);
113
114 // Use non-zero `import-instr-limit` multiplier for cold callsites.
115 add("-import-cold-multiplier=0.1", false);
116
117 if sess.print_llvm_stats() {
118 add("-stats", false);
119 }
120
121 for arg in sess_args {
122 add(&(*arg), true);
123 }
124 }
125
126 if sess.opts.unstable_opts.llvm_time_trace {
127 llvm::LLVMRustTimeTraceProfilerInitialize();
128 }
129
130 rustc_llvm::initialize_available_targets();
131
132 llvm::LLVMRustSetLLVMOptions(llvm_args.len() as c_int, llvm_args.as_ptr());
133 }
134
135 pub fn time_trace_profiler_finish(file_name: &Path) {
136 unsafe {
137 let file_name = path_to_c_string(file_name);
138 llvm::LLVMRustTimeTraceProfilerFinish(file_name.as_ptr());
139 }
140 }
141
142 pub enum TargetFeatureFoldStrength<'a> {
143 // The feature is only tied when enabling the feature, disabling
144 // this feature shouldn't disable the tied feature.
145 EnableOnly(&'a str),
146 // The feature is tied for both enabling and disabling this feature.
147 Both(&'a str),
148 }
149
150 impl<'a> TargetFeatureFoldStrength<'a> {
151 fn as_str(&self) -> &'a str {
152 match self {
153 TargetFeatureFoldStrength::EnableOnly(feat) => feat,
154 TargetFeatureFoldStrength::Both(feat) => feat,
155 }
156 }
157 }
158
159 pub struct LLVMFeature<'a> {
160 pub llvm_feature_name: &'a str,
161 pub dependency: Option<TargetFeatureFoldStrength<'a>>,
162 }
163
164 impl<'a> LLVMFeature<'a> {
165 pub fn new(llvm_feature_name: &'a str) -> Self {
166 Self { llvm_feature_name, dependency: None }
167 }
168
169 pub fn with_dependency(
170 llvm_feature_name: &'a str,
171 dependency: TargetFeatureFoldStrength<'a>,
172 ) -> Self {
173 Self { llvm_feature_name, dependency: Some(dependency) }
174 }
175
176 pub fn contains(&self, feat: &str) -> bool {
177 self.iter().any(|dep| dep == feat)
178 }
179
180 pub fn iter(&'a self) -> impl Iterator<Item = &'a str> {
181 let dependencies = self.dependency.iter().map(|feat| feat.as_str());
182 std::iter::once(self.llvm_feature_name).chain(dependencies)
183 }
184 }
185
186 impl<'a> IntoIterator for LLVMFeature<'a> {
187 type Item = &'a str;
188 type IntoIter = impl Iterator<Item = &'a str>;
189
190 fn into_iter(self) -> Self::IntoIter {
191 let dependencies = self.dependency.into_iter().map(|feat| feat.as_str());
192 std::iter::once(self.llvm_feature_name).chain(dependencies)
193 }
194 }
195
196 // WARNING: the features after applying `to_llvm_features` must be known
197 // to LLVM or the feature detection code will walk past the end of the feature
198 // array, leading to crashes.
199 //
200 // To find a list of LLVM's names, see llvm-project/llvm/lib/Target/{ARCH}/*.td
201 // where `{ARCH}` is the architecture name. Look for instances of `SubtargetFeature`.
202 //
203 // Check the current rustc fork of LLVM in the repo at https://github.com/rust-lang/llvm-project/.
204 // The commit in use can be found via the `llvm-project` submodule in https://github.com/rust-lang/rust/tree/master/src
205 // Though note that Rust can also be build with an external precompiled version of LLVM
206 // which might lead to failures if the oldest tested / supported LLVM version
207 // doesn't yet support the relevant intrinsics
208 pub fn to_llvm_features<'a>(sess: &Session, s: &'a str) -> LLVMFeature<'a> {
209 let arch = if sess.target.arch == "x86_64" {
210 "x86"
211 } else if sess.target.arch == "arm64ec" {
212 "aarch64"
213 } else {
214 &*sess.target.arch
215 };
216 match (arch, s) {
217 ("x86", "sse4.2") => {
218 LLVMFeature::with_dependency("sse4.2", TargetFeatureFoldStrength::EnableOnly("crc32"))
219 }
220 ("x86", "pclmulqdq") => LLVMFeature::new("pclmul"),
221 ("x86", "rdrand") => LLVMFeature::new("rdrnd"),
222 ("x86", "bmi1") => LLVMFeature::new("bmi"),
223 ("x86", "cmpxchg16b") => LLVMFeature::new("cx16"),
224 ("x86", "lahfsahf") => LLVMFeature::new("sahf"),
225 ("aarch64", "rcpc2") => LLVMFeature::new("rcpc-immo"),
226 ("aarch64", "dpb") => LLVMFeature::new("ccpp"),
227 ("aarch64", "dpb2") => LLVMFeature::new("ccdp"),
228 ("aarch64", "frintts") => LLVMFeature::new("fptoint"),
229 ("aarch64", "fcma") => LLVMFeature::new("complxnum"),
230 ("aarch64", "pmuv3") => LLVMFeature::new("perfmon"),
231 ("aarch64", "paca") => LLVMFeature::new("pauth"),
232 ("aarch64", "pacg") => LLVMFeature::new("pauth"),
233 // Rust ties fp and neon together.
234 ("aarch64", "neon") => {
235 LLVMFeature::with_dependency("neon", TargetFeatureFoldStrength::Both("fp-armv8"))
236 }
237 // In LLVM neon implicitly enables fp, but we manually enable
238 // neon when a feature only implicitly enables fp
239 ("aarch64", "f32mm") => {
240 LLVMFeature::with_dependency("f32mm", TargetFeatureFoldStrength::EnableOnly("neon"))
241 }
242 ("aarch64", "f64mm") => {
243 LLVMFeature::with_dependency("f64mm", TargetFeatureFoldStrength::EnableOnly("neon"))
244 }
245 ("aarch64", "fhm") => {
246 LLVMFeature::with_dependency("fp16fml", TargetFeatureFoldStrength::EnableOnly("neon"))
247 }
248 ("aarch64", "fp16") => {
249 LLVMFeature::with_dependency("fullfp16", TargetFeatureFoldStrength::EnableOnly("neon"))
250 }
251 ("aarch64", "jsconv") => {
252 LLVMFeature::with_dependency("jsconv", TargetFeatureFoldStrength::EnableOnly("neon"))
253 }
254 ("aarch64", "sve") => {
255 LLVMFeature::with_dependency("sve", TargetFeatureFoldStrength::EnableOnly("neon"))
256 }
257 ("aarch64", "sve2") => {
258 LLVMFeature::with_dependency("sve2", TargetFeatureFoldStrength::EnableOnly("neon"))
259 }
260 ("aarch64", "sve2-aes") => {
261 LLVMFeature::with_dependency("sve2-aes", TargetFeatureFoldStrength::EnableOnly("neon"))
262 }
263 ("aarch64", "sve2-sm4") => {
264 LLVMFeature::with_dependency("sve2-sm4", TargetFeatureFoldStrength::EnableOnly("neon"))
265 }
266 ("aarch64", "sve2-sha3") => {
267 LLVMFeature::with_dependency("sve2-sha3", TargetFeatureFoldStrength::EnableOnly("neon"))
268 }
269 ("aarch64", "sve2-bitperm") => LLVMFeature::with_dependency(
270 "sve2-bitperm",
271 TargetFeatureFoldStrength::EnableOnly("neon"),
272 ),
273 // In LLVM 18, `unaligned-scalar-mem` was merged with `unaligned-vector-mem` into a single feature called
274 // `fast-unaligned-access`. In LLVM 19, it was split back out.
275 ("riscv32" | "riscv64", "unaligned-scalar-mem") if get_version().0 == 18 => {
276 LLVMFeature::new("fast-unaligned-access")
277 }
278 // For LLVM 18, enable the evex512 target feature if a avx512 target feature is enabled.
279 ("x86", s) if get_version().0 >= 18 && s.starts_with("avx512") => {
280 LLVMFeature::with_dependency(s, TargetFeatureFoldStrength::EnableOnly("evex512"))
281 }
282 (_, s) => LLVMFeature::new(s),
283 }
284 }
285
286 /// Given a map from target_features to whether they are enabled or disabled,
287 /// ensure only valid combinations are allowed.
288 pub fn check_tied_features(
289 sess: &Session,
290 features: &FxHashMap<&str, bool>,
291 ) -> Option<&'static [&'static str]> {
292 if !features.is_empty() {
293 for tied in sess.target.tied_target_features() {
294 // Tied features must be set to the same value, or not set at all
295 let mut tied_iter = tied.iter();
296 let enabled = features.get(tied_iter.next().unwrap());
297 if tied_iter.any(|f| enabled != features.get(f)) {
298 return Some(tied);
299 }
300 }
301 }
302 return None;
303 }
304
305 /// Used to generate cfg variables and apply features
306 /// Must express features in the way Rust understands them
307 pub fn target_features(sess: &Session, allow_unstable: bool) -> Vec<Symbol> {
308 let target_machine = create_informational_target_machine(sess);
309 sess.target
310 .supported_target_features()
311 .iter()
312 .filter_map(|&(feature, gate)| {
313 if sess.is_nightly_build() || allow_unstable || gate.is_stable() {
314 Some(feature)
315 } else {
316 None
317 }
318 })
319 .filter(|feature| {
320 // check that all features in a given smallvec are enabled
321 for llvm_feature in to_llvm_features(sess, feature) {
322 let cstr = SmallCStr::new(llvm_feature);
323 if !unsafe { llvm::LLVMRustHasFeature(&target_machine, cstr.as_ptr()) } {
324 return false;
325 }
326 }
327 true
328 })
329 .map(|feature| Symbol::intern(feature))
330 .collect()
331 }
332
333 pub fn print_version() {
334 let (major, minor, patch) = get_version();
335 println!("LLVM version: {major}.{minor}.{patch}");
336 }
337
338 pub fn get_version() -> (u32, u32, u32) {
339 // Can be called without initializing LLVM
340 unsafe {
341 (llvm::LLVMRustVersionMajor(), llvm::LLVMRustVersionMinor(), llvm::LLVMRustVersionPatch())
342 }
343 }
344
345 pub fn print_passes() {
346 // Can be called without initializing LLVM
347 unsafe {
348 llvm::LLVMRustPrintPasses();
349 }
350 }
351
352 fn llvm_target_features(tm: &llvm::TargetMachine) -> Vec<(&str, &str)> {
353 let len = unsafe { llvm::LLVMRustGetTargetFeaturesCount(tm) };
354 let mut ret = Vec::with_capacity(len);
355 for i in 0..len {
356 unsafe {
357 let mut feature = ptr::null();
358 let mut desc = ptr::null();
359 llvm::LLVMRustGetTargetFeature(tm, i, &mut feature, &mut desc);
360 if feature.is_null() || desc.is_null() {
361 bug!("LLVM returned a `null` target feature string");
362 }
363 let feature = CStr::from_ptr(feature).to_str().unwrap_or_else(|e| {
364 bug!("LLVM returned a non-utf8 feature string: {}", e);
365 });
366 let desc = CStr::from_ptr(desc).to_str().unwrap_or_else(|e| {
367 bug!("LLVM returned a non-utf8 feature string: {}", e);
368 });
369 ret.push((feature, desc));
370 }
371 }
372 ret
373 }
374
375 fn print_target_features(out: &mut dyn PrintBackendInfo, sess: &Session, tm: &llvm::TargetMachine) {
376 let mut llvm_target_features = llvm_target_features(tm);
377 let mut known_llvm_target_features = FxHashSet::<&'static str>::default();
378 let mut rustc_target_features = sess
379 .target
380 .supported_target_features()
381 .iter()
382 .map(|(feature, _gate)| {
383 // LLVM asserts that these are sorted. LLVM and Rust both use byte comparison for these strings.
384 let llvm_feature = to_llvm_features(sess, *feature).llvm_feature_name;
385 let desc =
386 match llvm_target_features.binary_search_by_key(&llvm_feature, |(f, _d)| f).ok() {
387 Some(index) => {
388 known_llvm_target_features.insert(llvm_feature);
389 llvm_target_features[index].1
390 }
391 None => "",
392 };
393
394 (*feature, desc)
395 })
396 .collect::<Vec<_>>();
397 rustc_target_features.extend_from_slice(&[(
398 "crt-static",
399 "Enables C Run-time Libraries to be statically linked",
400 )]);
401 llvm_target_features.retain(|(f, _d)| !known_llvm_target_features.contains(f));
402
403 let max_feature_len = llvm_target_features
404 .iter()
405 .chain(rustc_target_features.iter())
406 .map(|(feature, _desc)| feature.len())
407 .max()
408 .unwrap_or(0);
409
410 writeln!(out, "Features supported by rustc for this target:");
411 for (feature, desc) in &rustc_target_features {
412 writeln!(out, " {feature:max_feature_len$} - {desc}.");
413 }
414 writeln!(out, "\nCode-generation features supported by LLVM for this target:");
415 for (feature, desc) in &llvm_target_features {
416 writeln!(out, " {feature:max_feature_len$} - {desc}.");
417 }
418 if llvm_target_features.is_empty() {
419 writeln!(out, " Target features listing is not supported by this LLVM version.");
420 }
421 writeln!(out, "\nUse +feature to enable a feature, or -feature to disable it.");
422 writeln!(out, "For example, rustc -C target-cpu=mycpu -C target-feature=+feature1,-feature2\n");
423 writeln!(out, "Code-generation features cannot be used in cfg or #[target_feature],");
424 writeln!(out, "and may be renamed or removed in a future version of LLVM or rustc.\n");
425 }
426
427 pub(crate) fn print(req: &PrintRequest, mut out: &mut dyn PrintBackendInfo, sess: &Session) {
428 require_inited();
429 let tm = create_informational_target_machine(sess);
430 match req.kind {
431 PrintKind::TargetCPUs => {
432 // SAFETY generate a C compatible string from a byte slice to pass
433 // the target CPU name into LLVM, the lifetime of the reference is
434 // at least as long as the C function
435 let cpu_cstring = CString::new(handle_native(sess.target.cpu.as_ref()))
436 .unwrap_or_else(|e| bug!("failed to convert to cstring: {}", e));
437 unsafe extern "C" fn callback(out: *mut c_void, string: *const c_char, len: usize) {
438 let out = &mut *(out as *mut &mut dyn PrintBackendInfo);
439 let bytes = slice::from_raw_parts(string as *const u8, len);
440 write!(out, "{}", String::from_utf8_lossy(bytes));
441 }
442 unsafe {
443 llvm::LLVMRustPrintTargetCPUs(
444 &tm,
445 cpu_cstring.as_ptr(),
446 callback,
447 std::ptr::addr_of_mut!(out) as *mut c_void,
448 );
449 }
450 }
451 PrintKind::TargetFeatures => print_target_features(out, sess, &tm),
452 _ => bug!("rustc_codegen_llvm can't handle print request: {:?}", req),
453 }
454 }
455
456 fn handle_native(name: &str) -> &str {
457 if name != "native" {
458 return name;
459 }
460
461 unsafe {
462 let mut len = 0;
463 let ptr = llvm::LLVMRustGetHostCPUName(&mut len);
464 str::from_utf8(slice::from_raw_parts(ptr as *const u8, len)).unwrap()
465 }
466 }
467
468 pub fn target_cpu(sess: &Session) -> &str {
469 match sess.opts.cg.target_cpu {
470 Some(ref name) => handle_native(name),
471 None => handle_native(sess.target.cpu.as_ref()),
472 }
473 }
474
475 /// The list of LLVM features computed from CLI flags (`-Ctarget-cpu`, `-Ctarget-feature`,
476 /// `--target` and similar).
477 pub(crate) fn global_llvm_features(sess: &Session, diagnostics: bool) -> Vec<String> {
478 // Features that come earlier are overridden by conflicting features later in the string.
479 // Typically we'll want more explicit settings to override the implicit ones, so:
480 //
481 // * Features from -Ctarget-cpu=*; are overridden by [^1]
482 // * Features implied by --target; are overridden by
483 // * Features from -Ctarget-feature; are overridden by
484 // * function specific features.
485 //
486 // [^1]: target-cpu=native is handled here, other target-cpu values are handled implicitly
487 // through LLVM TargetMachine implementation.
488 //
489 // FIXME(nagisa): it isn't clear what's the best interaction between features implied by
490 // `-Ctarget-cpu` and `--target` are. On one hand, you'd expect CLI arguments to always
491 // override anything that's implicit, so e.g. when there's no `--target` flag, features implied
492 // the host target are overridden by `-Ctarget-cpu=*`. On the other hand, what about when both
493 // `--target` and `-Ctarget-cpu=*` are specified? Both then imply some target features and both
494 // flags are specified by the user on the CLI. It isn't as clear-cut which order of precedence
495 // should be taken in cases like these.
496 let mut features = vec![];
497
498 // -Ctarget-cpu=native
499 match sess.opts.cg.target_cpu {
500 Some(ref s) if s == "native" => {
501 let features_string = unsafe {
502 let ptr = llvm::LLVMGetHostCPUFeatures();
503 let features_string = if !ptr.is_null() {
504 CStr::from_ptr(ptr)
505 .to_str()
506 .unwrap_or_else(|e| {
507 bug!("LLVM returned a non-utf8 features string: {}", e);
508 })
509 .to_owned()
510 } else {
511 bug!("could not allocate host CPU features, LLVM returned a `null` string");
512 };
513
514 llvm::LLVMDisposeMessage(ptr);
515
516 features_string
517 };
518 features.extend(features_string.split(',').map(String::from));
519 }
520 Some(_) | None => {}
521 };
522
523 // Features implied by an implicit or explicit `--target`.
524 features.extend(
525 sess.target
526 .features
527 .split(',')
528 .filter(|v| !v.is_empty() && backend_feature_name(sess, v).is_some())
529 .map(String::from),
530 );
531
532 if wants_wasm_eh(sess) && sess.panic_strategy() == PanicStrategy::Unwind {
533 features.push("+exception-handling".into());
534 }
535
536 // -Ctarget-features
537 let supported_features = sess.target.supported_target_features();
538 let mut featsmap = FxHashMap::default();
539 let feats = sess
540 .opts
541 .cg
542 .target_feature
543 .split(',')
544 .filter_map(|s| {
545 let enable_disable = match s.chars().next() {
546 None => return None,
547 Some(c @ ('+' | '-')) => c,
548 Some(_) => {
549 if diagnostics {
550 sess.dcx().emit_warn(UnknownCTargetFeaturePrefix { feature: s });
551 }
552 return None;
553 }
554 };
555
556 let feature = backend_feature_name(sess, s)?;
557 // Warn against use of LLVM specific feature names and unstable features on the CLI.
558 if diagnostics {
559 let feature_state = supported_features.iter().find(|&&(v, _)| v == feature);
560 if feature_state.is_none() {
561 let rust_feature = supported_features.iter().find_map(|&(rust_feature, _)| {
562 let llvm_features = to_llvm_features(sess, rust_feature);
563 if llvm_features.contains(feature) && !llvm_features.contains(rust_feature)
564 {
565 Some(rust_feature)
566 } else {
567 None
568 }
569 });
570 let unknown_feature = if let Some(rust_feature) = rust_feature {
571 UnknownCTargetFeature {
572 feature,
573 rust_feature: PossibleFeature::Some { rust_feature },
574 }
575 } else {
576 UnknownCTargetFeature { feature, rust_feature: PossibleFeature::None }
577 };
578 sess.dcx().emit_warn(unknown_feature);
579 } else if feature_state
580 .is_some_and(|(_name, feature_gate)| !feature_gate.is_stable())
581 {
582 // An unstable feature. Warn about using it.
583 sess.dcx().emit_warn(UnstableCTargetFeature { feature });
584 }
585 }
586
587 if diagnostics {
588 // FIXME(nagisa): figure out how to not allocate a full hashset here.
589 featsmap.insert(feature, enable_disable == '+');
590 }
591
592 // rustc-specific features do not get passed down to LLVM…
593 if RUSTC_SPECIFIC_FEATURES.contains(&feature) {
594 return None;
595 }
596 // ... otherwise though we run through `to_llvm_features` when
597 // passing requests down to LLVM. This means that all in-language
598 // features also work on the command line instead of having two
599 // different names when the LLVM name and the Rust name differ.
600 let llvm_feature = to_llvm_features(sess, feature);
601
602 Some(
603 std::iter::once(format!("{}{}", enable_disable, llvm_feature.llvm_feature_name))
604 .chain(llvm_feature.dependency.into_iter().filter_map(move |feat| {
605 match (enable_disable, feat) {
606 ('-' | '+', TargetFeatureFoldStrength::Both(f))
607 | ('+', TargetFeatureFoldStrength::EnableOnly(f)) => {
608 Some(format!("{enable_disable}{f}"))
609 }
610 _ => None,
611 }
612 })),
613 )
614 })
615 .flatten();
616 features.extend(feats);
617
618 // -Zfixed-x18
619 if sess.opts.unstable_opts.fixed_x18 {
620 if sess.target.arch != "aarch64" {
621 sess.dcx().emit_fatal(FixedX18InvalidArch { arch: &sess.target.arch });
622 } else {
623 features.push("+reserve-x18".into());
624 }
625 }
626
627 if diagnostics && let Some(f) = check_tied_features(sess, &featsmap) {
628 sess.dcx().emit_err(TargetFeatureDisableOrEnable {
629 features: f,
630 span: None,
631 missing_features: None,
632 });
633 }
634
635 features
636 }
637
638 /// Returns a feature name for the given `+feature` or `-feature` string.
639 ///
640 /// Only allows features that are backend specific (i.e. not [`RUSTC_SPECIFIC_FEATURES`].)
641 fn backend_feature_name<'a>(sess: &Session, s: &'a str) -> Option<&'a str> {
642 // features must start with a `+` or `-`.
643 let feature = s
644 .strip_prefix(&['+', '-'][..])
645 .unwrap_or_else(|| sess.dcx().emit_fatal(InvalidTargetFeaturePrefix { feature: s }));
646 // Rustc-specific feature requests like `+crt-static` or `-crt-static`
647 // are not passed down to LLVM.
648 if RUSTC_SPECIFIC_FEATURES.contains(&feature) {
649 return None;
650 }
651 Some(feature)
652 }
653
654 pub fn tune_cpu(sess: &Session) -> Option<&str> {
655 let name = sess.opts.unstable_opts.tune_cpu.as_ref()?;
656 Some(handle_native(name))
657 }