1use std::any::Any;
2use std::collections::BTreeMap;
3use std::env::consts::{DLL_PREFIX, DLL_SUFFIX};
4use std::path::{Path, PathBuf};
5use std::sync::atomic::{AtomicBool, Ordering};
6use std::sync::{Arc, OnceLock};
7use std::{env, thread};
8
9use rand::{RngCore, rng};
10use rustc_ast as ast;
11use rustc_attr_parsing::ShouldEmit;
12use rustc_codegen_ssa::back::archive::{ArArchiveBuilderBuilder, ArchiveBuilderBuilder};
13use rustc_codegen_ssa::back::link::link_binary;
14use rustc_codegen_ssa::target_features::internal_target_features;
15use rustc_codegen_ssa::traits::CodegenBackend;
16use rustc_codegen_ssa::{CompiledModules, CrateInfo, TargetConfig};
17use rustc_data_structures::base_n::{CASE_INSENSITIVE, ToBaseN};
18use rustc_data_structures::jobserver::Proxy;
19use rustc_data_structures::sync;
20use rustc_metadata::{DylibError, EncodedMetadata, load_symbol_from_dylib};
21use rustc_middle::dep_graph::IncrCompSession;
22use rustc_middle::ty::{CurrentGcx, TyCtxt};
23use rustc_query_impl::{CollectActiveJobsKind, collect_active_query_jobs};
24pub use rustc_session::config::DEFAULT_STACK_SIZE;
25use rustc_session::config::{
26 Cfg, Jobs, OptionsTargetModifiers, OutFileName, OutputFilenames, Sysroot, host_tuple,
27};
28use rustc_session::output::OutputTypes;
29use rustc_session::{CodegenBackendInit, EarlyDiagCtxt, EarlySession, Session, filesearch};
30use rustc_span::edition::Edition;
31use rustc_span::source_map::SourceMapInputs;
32use rustc_span::{SessionGlobals, Symbol, sym};
33use rustc_structures::CrateType;
34use rustc_target::spec::{Arch, Target};
35use tracing::info;
36
37use crate::diagnostics;
38use crate::passes::parse_crate_name;
39
40type MakeBackendFn = fn() -> Box<dyn CodegenBackend>;
42
43pub(crate) fn add_configuration(
48 cfg: &mut Cfg,
49 target_config: &TargetConfig,
50 target: &Target,
51 is_nightly_build: bool,
52 is_crt_static: bool,
53) {
54 cfg.extend(
56 target
57 .rust_target_features()
58 .iter()
59 .filter_map(|(feature, stab, _)| {
60 if stab.in_cfg()
61 && (is_nightly_build || stab.requires_nightly(true).is_none())
62 {
63 Some(Symbol::intern(feature))
64 } else {
65 None
66 }
67 })
68 .filter(|feature| target_config.internal_target_features.contains(&feature))
69 .map(|feature| (sym::target_feature, Some(feature))),
70 );
71
72 if target_config.has_reliable_f16 {
73 cfg.insert((sym::target_has_reliable_f16, None));
74 }
75 if target_config.has_reliable_f16_math {
76 cfg.insert((sym::target_has_reliable_f16_math, None));
77 }
78 if target_config.has_reliable_f16b {
79 cfg.insert((sym::target_has_reliable_f16b, None));
80 }
81 if target_config.has_reliable_f128 {
82 cfg.insert((sym::target_has_reliable_f128, None));
83 }
84 if target_config.has_reliable_f128_math {
85 cfg.insert((sym::target_has_reliable_f128_math, None));
86 }
87
88 if is_crt_static {
89 cfg.insert((sym::target_feature, Some(sym::crt_dash_static)));
90 }
91}
92
93pub(crate) fn add_target_modifiers(
95 tmod: &mut BTreeMap<OptionsTargetModifiers, String>,
96 target_config: &TargetConfig,
97 target: &Target,
98 cg_backend: &dyn CodegenBackend,
99) {
100 let target_feature_modifier = target
104 .rust_target_features()
105 .iter()
106 .filter(|(_, stab, _)| stab.is_target_modifier())
107 .map(|(feature, ..)| *feature)
108 .filter(|feature| target_config.internal_target_features.contains(&Symbol::intern(feature)))
109 .collect::<Vec<_>>()
110 .join(",");
111 tmod.insert(OptionsTargetModifiers::TargetFeatures, target_feature_modifier);
112
113 tmod.insert(OptionsTargetModifiers::CodegenBackendName, cg_backend.name().to_string());
115}
116
117pub(crate) fn check_abi_required_features(sess: &Session) {
120 let abi_feature_constraints = sess.target.abi_required_features();
121 for feature in
125 abi_feature_constraints.required.iter().chain(abi_feature_constraints.incompatible.iter())
126 {
127 if !sess.target.rust_target_features().iter().any(|(name, ..)|
feature == name) {
{
::core::panicking::panic_fmt(format_args!("target feature {0} is required/incompatible for the current ABI but not a recognized feature for this target",
feature));
}
};assert!(
128 sess.target.rust_target_features().iter().any(|(name, ..)| feature == name),
129 "target feature {feature} is required/incompatible for the current ABI but not a recognized feature for this target"
130 );
131 }
132
133 let hard_error = #[allow(non_exhaustive_omitted_patterns)] match sess.target.arch {
Arch::AArch64 | Arch::Arm | Arch::X86 => true,
_ => false,
}matches!(sess.target.arch, Arch::AArch64 | Arch::Arm | Arch::X86);
138
139 for feature in abi_feature_constraints.required {
140 if !sess.internal_target_features.contains(&Symbol::intern(feature)) {
141 let diag = diagnostics::AbiRequiredTargetFeature {
142 feature,
143 enabled: "enabled",
144 fcw: !hard_error,
145 };
146 if hard_error {
147 sess.dcx().emit_err(diag);
148 } else {
149 sess.dcx().emit_warn(diag);
150 }
151 }
152 }
153 for feature in abi_feature_constraints.incompatible {
154 if sess.internal_target_features.contains(&Symbol::intern(feature)) {
155 let diag = diagnostics::AbiRequiredTargetFeature {
156 feature,
157 enabled: "disabled",
158 fcw: !hard_error,
159 };
160 if hard_error {
161 sess.dcx().emit_err(diag);
162 } else {
163 sess.dcx().emit_warn(diag);
164 }
165 }
166 }
167}
168
169pub static STACK_SIZE: OnceLock<usize> = OnceLock::new();
170
171fn init_stack_size(early_dcx: &EarlyDiagCtxt) -> usize {
172 *STACK_SIZE.get_or_init(|| {
174 env::var_os("RUST_MIN_STACK")
175 .as_ref()
176 .map(|os_str| os_str.to_string_lossy())
177 .filter(|s| !s.trim().is_empty())
181 .map(|s| {
185 let s = s.trim();
186 s.parse::<usize>().unwrap_or_else(|_| {
187 let mut err = early_dcx.early_struct_fatal(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`RUST_MIN_STACK` should be a number of bytes, but was \"{0}\"",
s))
})format!(
188 r#"`RUST_MIN_STACK` should be a number of bytes, but was "{s}""#,
189 ));
190 err.note("you can also unset `RUST_MIN_STACK` to use the default stack size");
191 err.emit_fatal()
192 })
193 })
194 .unwrap_or(DEFAULT_STACK_SIZE)
196 })
197}
198
199fn run_in_thread_with_globals<F: FnOnce(CurrentGcx) -> R + Send, R: Send>(
200 thread_stack_size: usize,
201 edition: Edition,
202 sm_inputs: SourceMapInputs,
203 extra_symbols: &[&'static str],
204 f: F,
205) -> R {
206 let builder = thread::Builder::new().name("rustc".to_string()).stack_size(thread_stack_size);
213
214 thread::scope(|s| {
217 let r = builder
220 .spawn_scoped(s, move || {
221 rustc_span::create_session_globals_then(
222 edition,
223 extra_symbols,
224 Some(sm_inputs),
225 || f(CurrentGcx::new()),
226 )
227 })
228 .unwrap()
229 .join();
230
231 match r {
232 Ok(v) => v,
233 Err(e) => std::panic::resume_unwind(e),
234 }
235 })
236}
237
238pub(crate) fn run_in_thread_pool_with_globals<F: FnOnce(CurrentGcx) -> R + Send, R: Send>(
239 thread_builder_diag: &EarlyDiagCtxt,
240 edition: Edition,
241 jobs: Jobs,
242 extra_symbols: &[&'static str],
243 sm_inputs: SourceMapInputs,
244 f: F,
245) -> R {
246 use std::process;
247
248 use rustc_data_structures::defer;
249 use rustc_middle::ty::tls;
250 use rustc_query_impl::break_query_cycle;
251
252 let thread_stack_size = init_stack_size(thread_builder_diag);
253
254 let jobs_frontend = jobs.frontend.limit();
255 let registry = sync::Registry::new(jobs_frontend);
256
257 let Some(proof) = sync::check_dyn_thread_safe() else {
258 {
match (&jobs_frontend.get(), &1) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(jobs_frontend.get(), 1);
259 return run_in_thread_with_globals(
260 thread_stack_size,
261 edition,
262 sm_inputs,
263 extra_symbols,
264 |current_gcx| {
265 registry.register();
267
268 f(current_gcx)
269 },
270 );
271 };
272
273 let current_gcx = proof.derive(CurrentGcx::new());
274 let current_gcx2 = current_gcx.clone();
275
276 let proxy = Proxy::new();
277
278 let _drop_helper_thread = defer({
281 let proxy = Arc::clone(&proxy);
282 move || proxy.drop_helper_thread()
283 });
284
285 let proxy_ = Arc::clone(&proxy);
286
287 let builder = rustc_thread_pool::ThreadPoolBuilder::new()
288 .thread_name(|_| "rustc".to_string())
289 .acquire_thread_handler(move || proxy.acquire_thread())
290 .release_thread_handler(move || proxy_.release_thread())
291 .num_threads(jobs_frontend.get())
292 .deadlock_handler(move || {
293 let current_gcx2 = current_gcx2.clone();
297 let registry = rustc_thread_pool::Registry::current();
298 let session_globals = rustc_span::with_session_globals(|session_globals| {
299 session_globals as *const SessionGlobals as usize
300 });
301 thread::Builder::new()
302 .name("rustc query cycle handler".to_string())
303 .spawn(move || {
304 let on_panic = defer(|| {
305 const MESSAGE: &str = "\
309internal compiler error: query cycle handler thread panicked, aborting process";
310 { ::std::io::_eprint(format_args!("{0}\n", MESSAGE)); };eprintln!("{MESSAGE}");
311 process::abort();
314 });
315
316 current_gcx2.access(|gcx| {
319 tls::enter_context(&tls::ImplicitCtxt::new(gcx), || {
320 tls::with(|tcx| {
321 let job_map = rustc_span::set_session_globals_then(
324 unsafe { &*(session_globals as *const SessionGlobals) },
325 || {
326 collect_active_query_jobs(
330 tcx,
331 CollectActiveJobsKind::FullNoContention,
332 )
333 },
334 );
335 break_query_cycle(job_map, ®istry);
336 })
337 })
338 });
339
340 on_panic.disable();
341 })
342 .unwrap();
343 })
344 .stack_size(thread_stack_size);
345
346 rustc_span::create_session_globals_then(edition, extra_symbols, Some(sm_inputs), || {
351 rustc_span::with_session_globals(|session_globals| {
352 let session_globals = proof.derive(session_globals);
353 builder
354 .build_scoped(
355 move |thread: rustc_thread_pool::ThreadBuilder| {
357 registry.register();
359
360 rustc_span::set_session_globals_then(session_globals.into_inner(), || {
361 thread.run()
362 })
363 },
364 move |pool: &rustc_thread_pool::ThreadPool| {
366 pool.install(|| f(current_gcx.into_inner()))
367 },
368 )
369 .unwrap_or_else(|err| {
370 let mut diag = thread_builder_diag.early_struct_fatal(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("failed to spawn compiler thread pool: could not create {0} threads ({1})",
jobs_frontend, err))
})format!(
371 "failed to spawn compiler thread pool: could not create {jobs_frontend} threads ({err})",
372 ));
373 diag.help(
374 "try lowering `-Z threads` or checking the operating system's resource limits",
375 );
376 diag.emit_fatal()
377 })
378 })
379 })
380}
381
382fn load_backend_from_dylib(early_dcx: &EarlyDiagCtxt, path: &Path) -> MakeBackendFn {
383 match unsafe { load_symbol_from_dylib::<MakeBackendFn>(path, "__rustc_codegen_backend") } {
384 Ok(backend_sym) => backend_sym,
385 Err(DylibError::DlOpen(path, err)) => {
386 let err = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("couldn\'t load codegen backend {0}{1}",
path, err))
})format!("couldn't load codegen backend {path}{err}");
387 early_dcx.early_fatal(err);
388 }
389 Err(DylibError::DlSym(_path, err)) => {
390 let e = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`__rustc_codegen_backend` symbol lookup in the codegen backend failed{0}",
err))
})format!(
391 "`__rustc_codegen_backend` symbol lookup in the codegen backend failed{err}",
392 );
393 early_dcx.early_fatal(e);
394 }
395 }
396}
397
398pub fn get_codegen_backend(
402 early_dcx: &EarlyDiagCtxt,
403 sysroot: &Sysroot,
404 backend_name: Option<&str>,
405 target: &Target,
406) -> Box<dyn CodegenBackend> {
407 static LOAD: OnceLock<unsafe fn() -> Box<dyn CodegenBackend>> = OnceLock::new();
408
409 let load = LOAD.get_or_init(|| {
410 let backend = backend_name
411 .or(target.default_codegen_backend.as_deref())
412 .or(::core::option::Option::Some("llvm")option_env!("CFG_DEFAULT_CODEGEN_BACKEND"))
413 .unwrap_or("dummy");
414
415 match backend {
416 filename if filename.contains('.') => {
417 load_backend_from_dylib(early_dcx, filename.as_ref())
418 }
419 "dummy" => || Box::new(DummyCodegenBackend),
420 #[cfg(feature = "llvm")]
421 "llvm" => rustc_codegen_llvm::LlvmCodegenBackend::new,
422 backend_name => get_codegen_sysroot(early_dcx, sysroot, backend_name),
423 }
424 });
425
426 unsafe { load() }
430}
431
432pub struct DummyCodegenBackend;
433
434impl CodegenBackend for DummyCodegenBackend {
435 fn name(&self) -> &'static str {
436 "dummy"
437 }
438
439 fn init(&mut self, sess: &EarlySession) -> (CodegenBackendInit, TargetConfig) {
440 let init = CodegenBackendInit::default();
441
442 let abi_required_features = sess.target.abi_required_features();
443 let internal_target_features = internal_target_features::<0>(
444 sess,
445 |_feature| Default::default(),
446 |feature| {
447 abi_required_features.required.contains(&feature)
452 },
453 );
454
455 let config = TargetConfig {
456 internal_target_features,
457 has_reliable_f16: true,
458 has_reliable_f16_math: true,
459 has_reliable_f16b: true,
460 has_reliable_f128: true,
461 has_reliable_f128_math: true,
462 };
463
464 (init, config)
465 }
466
467 fn supported_crate_types(&self, _sess: &Session) -> Vec<CrateType> {
468 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[CrateType::Rlib, CrateType::Executable]))vec![CrateType::Rlib, CrateType::Executable]
473 }
474
475 fn target_cpu(&self, _sess: &Session) -> String {
476 String::new()
477 }
478
479 fn codegen_crate<'tcx>(&self, _tcx: TyCtxt<'tcx>) -> Box<dyn Any> {
480 Box::new(CompiledModules { modules: ::alloc::vec::Vec::new()vec![], allocator_module: None })
481 }
482
483 fn join_codegen(
484 &self,
485 ongoing_codegen: Box<dyn Any>,
486 _sess: &Session,
487 _incr_comp_session: Option<&mut IncrCompSession>,
488 _outputs: &OutputFilenames,
489 _crate_info: &CrateInfo,
490 ) -> CompiledModules {
491 *ongoing_codegen.downcast().unwrap()
492 }
493
494 fn link(
495 &self,
496 sess: &Session,
497 compiled_modules: CompiledModules,
498 crate_info: CrateInfo,
499 metadata: EncodedMetadata,
500 outputs: &OutputFilenames,
501 ) {
502 #[allow(rustc::bad_opt_access)]
504 if let Some(&crate_type) =
505 crate_info.crate_types.iter().find(|&&crate_type| crate_type != CrateType::Rlib)
506 && outputs.outputs.should_link()
507 {
508 sess.dcx().fatal(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("crate type {0} not supported by the dummy codegen backend",
crate_type))
})format!(
509 "crate type {crate_type} not supported by the dummy codegen backend"
510 ));
511 }
512
513 link_binary(
514 sess,
515 &DummyArchiveBuilderBuilder,
516 compiled_modules,
517 crate_info,
518 metadata,
519 outputs,
520 self.name(),
521 );
522 }
523}
524
525struct DummyArchiveBuilderBuilder;
526
527impl ArchiveBuilderBuilder for DummyArchiveBuilderBuilder {
528 fn new_archive_builder<'a>(
529 &self,
530 sess: &'a Session,
531 ) -> Box<dyn rustc_codegen_ssa::back::archive::ArchiveBuilder + 'a> {
532 ArArchiveBuilderBuilder.new_archive_builder(sess)
533 }
534
535 fn create_dll_import_lib(
536 &self,
537 sess: &Session,
538 _lib_name: &str,
539 _items: Vec<rustc_codegen_ssa::back::archive::ImportLibraryItem>,
540 output_path: &Path,
541 ) {
542 ArArchiveBuilderBuilder.new_archive_builder(sess).build(output_path, None);
544 }
545}
546
547pub fn rustc_path<'a>(sysroot: &Sysroot) -> Option<&'a Path> {
551 static RUSTC_PATH: OnceLock<Option<PathBuf>> = OnceLock::new();
552
553 RUSTC_PATH
554 .get_or_init(|| {
555 let candidate = sysroot
556 .default
557 .join("bin"env!("RUSTC_INSTALL_BINDIR"))
558 .join(if falsecfg!(target_os = "windows") { "rustc.exe" } else { "rustc" });
559 candidate.exists().then_some(candidate)
560 })
561 .as_deref()
562}
563
564fn get_codegen_sysroot(
565 early_dcx: &EarlyDiagCtxt,
566 sysroot: &Sysroot,
567 backend_name: &str,
568) -> MakeBackendFn {
569 static LOADED: AtomicBool = AtomicBool::new(false);
575 if !!LOADED.fetch_or(true, Ordering::SeqCst) {
{
::core::panicking::panic_fmt(format_args!("cannot load the default codegen backend twice"));
}
};assert!(
576 !LOADED.fetch_or(true, Ordering::SeqCst),
577 "cannot load the default codegen backend twice"
578 );
579
580 let target = host_tuple();
581
582 let sysroot = sysroot
583 .all_paths()
584 .map(|sysroot| {
585 filesearch::make_target_lib_path(sysroot, target).with_file_name("codegen-backends")
586 })
587 .find(|f| {
588 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_interface/src/util.rs:588",
"rustc_interface::util", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("/rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_interface/src/util.rs"),
::tracing_core::__macro_support::Option::Some(588u32),
::tracing_core::__macro_support::Option::Some("rustc_interface::util"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("codegen backend candidate: {0}",
f.display()) as &dyn ::tracing::field::Value))])
});
} else { ; }
};info!("codegen backend candidate: {}", f.display());
589 f.exists()
590 })
591 .unwrap_or_else(|| {
592 let candidates = sysroot
593 .all_paths()
594 .map(|p| p.display().to_string())
595 .collect::<Vec<_>>()
596 .join("\n* ");
597 let err = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("failed to find a `codegen-backends` folder in the sysroot candidates:\n* {0}",
candidates))
})format!(
598 "failed to find a `codegen-backends` folder in the sysroot candidates:\n\
599 * {candidates}"
600 );
601 early_dcx.early_fatal(err);
602 });
603
604 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_interface/src/util.rs:604",
"rustc_interface::util", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("/rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_interface/src/util.rs"),
::tracing_core::__macro_support::Option::Some(604u32),
::tracing_core::__macro_support::Option::Some("rustc_interface::util"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("probing {0} for a codegen backend",
sysroot.display()) as &dyn ::tracing::field::Value))])
});
} else { ; }
};info!("probing {} for a codegen backend", sysroot.display());
605
606 let d = sysroot.read_dir().unwrap_or_else(|e| {
607 let err = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("failed to load default codegen backend, couldn\'t read `{0}`: {1}",
sysroot.display(), e))
})format!(
608 "failed to load default codegen backend, couldn't read `{}`: {e}",
609 sysroot.display(),
610 );
611 early_dcx.early_fatal(err);
612 });
613
614 let mut file: Option<PathBuf> = None;
615
616 let expected_names = &[
617 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("rustc_codegen_{0}-{1}",
backend_name, "1.102.0-nightly"))
})format!("rustc_codegen_{}-{}", backend_name, env!("CFG_RELEASE")),
618 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("rustc_codegen_{0}", backend_name))
})format!("rustc_codegen_{backend_name}"),
619 ];
620 for entry in d.filter_map(|e| e.ok()) {
621 let path = entry.path();
622 let Some(filename) = path.file_name().and_then(|s| s.to_str()) else { continue };
623 if !(filename.starts_with(DLL_PREFIX) && filename.ends_with(DLL_SUFFIX)) {
624 continue;
625 }
626 let name = &filename[DLL_PREFIX.len()..filename.len() - DLL_SUFFIX.len()];
627 if !expected_names.iter().any(|expected| expected == name) {
628 continue;
629 }
630 if let Some(ref prev) = file {
631 let err = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("duplicate codegen backends found\nfirst: {0}\nsecond: {1}\n",
prev.display(), path.display()))
})format!(
632 "duplicate codegen backends found\n\
633 first: {}\n\
634 second: {}\n\
635 ",
636 prev.display(),
637 path.display()
638 );
639 early_dcx.early_fatal(err);
640 }
641 file = Some(path.clone());
642 }
643
644 match file {
645 Some(ref s) => load_backend_from_dylib(early_dcx, s),
646 None => {
647 let err = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("unsupported builtin codegen backend `{0}`",
backend_name))
})format!("unsupported builtin codegen backend `{backend_name}`");
648 early_dcx.early_fatal(err);
649 }
650 }
651}
652
653fn multiple_output_types_to_stdout(
654 output_types: &OutputTypes,
655 single_output_file_is_stdout: bool,
656) -> bool {
657 use std::io::IsTerminal;
658 if std::io::stdout().is_terminal() {
659 let named_text_types = output_types
662 .iter()
663 .filter(|(f, o)| f.is_text_output() && *o == &Some(OutFileName::Stdout))
664 .count();
665 let unnamed_text_types =
666 output_types.iter().filter(|(f, o)| f.is_text_output() && o.is_none()).count();
667 named_text_types > 1 || unnamed_text_types > 1 && single_output_file_is_stdout
668 } else {
669 let named_types =
671 output_types.values().filter(|o| *o == &Some(OutFileName::Stdout)).count();
672 let unnamed_types = output_types.values().filter(|o| o.is_none()).count();
673 named_types > 1 || unnamed_types > 1 && single_output_file_is_stdout
674 }
675}
676
677pub fn build_output_filenames(attrs: &[ast::Attribute], sess: &Session) -> OutputFilenames {
678 if multiple_output_types_to_stdout(
679 &sess.opts.output_types,
680 sess.io.output_file == Some(OutFileName::Stdout),
681 ) {
682 sess.dcx().emit_fatal(diagnostics::MultipleOutputTypesToStdout);
683 }
684
685 let crate_name =
686 sess.opts.crate_name.clone().or_else(|| {
687 parse_crate_name(sess, attrs, ShouldEmit::Nothing).map(|i| i.0.to_string())
688 });
689
690 let invocation_temp = sess
691 .opts
692 .incremental
693 .as_ref()
694 .map(|_| rng().next_u32().to_base_fixed_len(CASE_INSENSITIVE).to_string());
695
696 match sess.io.output_file {
697 None => {
698 let dirpath = sess.io.output_dir.clone().unwrap_or_default();
702
703 let stem = crate_name.clone().unwrap_or_else(|| sess.io.input.filestem().to_owned());
705
706 OutputFilenames::new(
707 dirpath,
708 crate_name.unwrap_or_else(|| stem.replace('-', "_")),
709 stem,
710 None,
711 sess.io.temps_dir.clone(),
712 invocation_temp,
713 sess.opts.unstable_opts.split_dwarf_out_dir.clone(),
714 sess.opts.cg.extra_filename.clone(),
715 sess.opts.output_types.clone(),
716 )
717 }
718
719 Some(ref out_file) => {
720 let unnamed_output_types =
721 sess.opts.output_types.values().filter(|a| a.is_none()).count();
722 let ofile = if unnamed_output_types > 1 {
723 sess.dcx().emit_warn(diagnostics::MultipleOutputTypesAdaption);
724 None
725 } else {
726 if !sess.opts.cg.extra_filename.is_empty() {
727 sess.dcx().emit_warn(diagnostics::IgnoringExtraFilename);
728 }
729 Some(out_file.clone())
730 };
731 if sess.io.output_dir.is_some() {
732 sess.dcx().emit_warn(diagnostics::IgnoringOutDir);
733 }
734
735 let out_filestem =
736 out_file.filestem().unwrap_or_default().to_str().unwrap().to_string();
737 OutputFilenames::new(
738 out_file.parent().unwrap_or_else(|| Path::new("")).to_path_buf(),
739 crate_name.unwrap_or_else(|| out_filestem.replace('-', "_")),
740 out_filestem,
741 ofile,
742 sess.io.temps_dir.clone(),
743 invocation_temp,
744 sess.opts.unstable_opts.split_dwarf_out_dir.clone(),
745 sess.opts.cg.extra_filename.clone(),
746 sess.opts.output_types.clone(),
747 )
748 }
749 }
750}
751
752pub macro version_str() {
754 option_env!("CFG_VERSION")
755}
756
757pub fn rustc_version_str() -> Option<&'static str> {
759 ::core::option::Option::Some("1.102.0-nightly (75a3786af 2026-11-30)")version_str!()
760}