1use std::any::Any;
2use std::env::consts::{DLL_PREFIX, DLL_SUFFIX};
3use std::num::NonZero;
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::WorkProductMap;
22use rustc_middle::ty::{CurrentGcx, TyCtxt};
23use rustc_query_impl::{CollectActiveJobsKind, collect_active_query_jobs};
24use rustc_session::config::{
25 Cfg, Jobs, OutFileName, OutputFilenames, OutputTypes, Sysroot, host_tuple,
26};
27use rustc_session::{EarlyDiagCtxt, EarlySession, IncrCompSession, Session, filesearch};
28use rustc_span::edition::Edition;
29use rustc_span::source_map::SourceMapInputs;
30use rustc_span::{SessionGlobals, Symbol, sym};
31use rustc_structures::CrateType;
32use rustc_target::spec::{Arch, Target};
33use tracing::info;
34
35use crate::diagnostics;
36use crate::passes::parse_crate_name;
37
38type MakeBackendFn = fn() -> Box<dyn CodegenBackend>;
40
41pub(crate) fn add_configuration(
47 cfg: &mut Cfg,
48 target_config: &TargetConfig,
49 target: &Target,
50 is_nightly_build: bool,
51 is_crt_static: bool,
52) {
53 cfg.extend(
55 target
56 .rust_target_features()
57 .iter()
58 .filter_map(|(feature, gate, _)| {
59 if gate.in_cfg()
60 && (is_nightly_build || gate.requires_nightly(true).is_none())
61 {
62 Some(Symbol::intern(feature))
63 } else {
64 None
65 }
66 })
67 .filter(|feature| target_config.internal_target_features.contains(&feature))
68 .map(|feature| (sym::target_feature, Some(feature))),
69 );
70
71 if target_config.has_reliable_f16 {
72 cfg.insert((sym::target_has_reliable_f16, None));
73 }
74 if target_config.has_reliable_f16_math {
75 cfg.insert((sym::target_has_reliable_f16_math, None));
76 }
77 if target_config.has_reliable_f16b {
78 cfg.insert((sym::target_has_reliable_f16b, None));
79 }
80 if target_config.has_reliable_f128 {
81 cfg.insert((sym::target_has_reliable_f128, None));
82 }
83 if target_config.has_reliable_f128_math {
84 cfg.insert((sym::target_has_reliable_f128_math, None));
85 }
86
87 if is_crt_static {
88 cfg.insert((sym::target_feature, Some(sym::crt_dash_static)));
89 }
90}
91
92pub(crate) fn check_abi_required_features(sess: &Session) {
95 let abi_feature_constraints = sess.target.abi_required_features();
96 for feature in
100 abi_feature_constraints.required.iter().chain(abi_feature_constraints.incompatible.iter())
101 {
102 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!(
103 sess.target.rust_target_features().iter().any(|(name, ..)| feature == name),
104 "target feature {feature} is required/incompatible for the current ABI but not a recognized feature for this target"
105 );
106 }
107
108 let hard_error = #[allow(non_exhaustive_omitted_patterns)] match sess.target.arch {
Arch::Arm | Arch::X86 => true,
_ => false,
}matches!(sess.target.arch, Arch::Arm | Arch::X86);
113
114 for feature in abi_feature_constraints.required {
115 if !sess.internal_target_features.contains(&Symbol::intern(feature)) {
116 let diag = diagnostics::AbiRequiredTargetFeature {
117 feature,
118 enabled: "enabled",
119 fcw: !hard_error,
120 };
121 if hard_error {
122 sess.dcx().emit_err(diag);
123 } else {
124 sess.dcx().emit_warn(diag);
125 }
126 }
127 }
128 for feature in abi_feature_constraints.incompatible {
129 if sess.internal_target_features.contains(&Symbol::intern(feature)) {
130 let diag = diagnostics::AbiRequiredTargetFeature {
131 feature,
132 enabled: "disabled",
133 fcw: !hard_error,
134 };
135 if hard_error {
136 sess.dcx().emit_err(diag);
137 } else {
138 sess.dcx().emit_warn(diag);
139 }
140 }
141 }
142}
143
144pub static STACK_SIZE: OnceLock<usize> = OnceLock::new();
145pub const DEFAULT_STACK_SIZE: usize = 17 * 1024 * 1024;
146
147fn init_stack_size(early_dcx: &EarlyDiagCtxt) -> usize {
148 *STACK_SIZE.get_or_init(|| {
150 env::var_os("RUST_MIN_STACK")
151 .as_ref()
152 .map(|os_str| os_str.to_string_lossy())
153 .filter(|s| !s.trim().is_empty())
157 .map(|s| {
161 let s = s.trim();
162 s.parse::<usize>().unwrap_or_else(|_| {
163 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!(
164 r#"`RUST_MIN_STACK` should be a number of bytes, but was "{s}""#,
165 ));
166 err.note("you can also unset `RUST_MIN_STACK` to use the default stack size");
167 err.emit_fatal()
168 })
169 })
170 .unwrap_or(DEFAULT_STACK_SIZE)
172 })
173}
174
175fn run_in_thread_with_globals<F: FnOnce(CurrentGcx) -> R + Send, R: Send>(
176 thread_stack_size: usize,
177 edition: Edition,
178 sm_inputs: SourceMapInputs,
179 extra_symbols: &[&'static str],
180 f: F,
181) -> R {
182 let builder = thread::Builder::new().name("rustc".to_string()).stack_size(thread_stack_size);
189
190 thread::scope(|s| {
193 let r = builder
196 .spawn_scoped(s, move || {
197 rustc_span::create_session_globals_then(
198 edition,
199 extra_symbols,
200 Some(sm_inputs),
201 || f(CurrentGcx::new()),
202 )
203 })
204 .unwrap()
205 .join();
206
207 match r {
208 Ok(v) => v,
209 Err(e) => std::panic::resume_unwind(e),
210 }
211 })
212}
213
214pub(crate) fn run_in_thread_pool_with_globals<F: FnOnce(CurrentGcx) -> R + Send, R: Send>(
215 thread_builder_diag: &EarlyDiagCtxt,
216 edition: Edition,
217 jobs: Jobs,
218 extra_symbols: &[&'static str],
219 sm_inputs: SourceMapInputs,
220 f: F,
221) -> R {
222 use std::process;
223
224 use rustc_data_structures::defer;
225 use rustc_middle::ty::tls;
226 use rustc_query_impl::break_query_cycle;
227
228 let thread_stack_size = init_stack_size(thread_builder_diag);
229
230 let jobs_frontend = jobs.frontend.or(NonZero::new(1)).unwrap();
231 let registry = sync::Registry::new(jobs_frontend);
232
233 let Some(proof) = sync::check_dyn_thread_safe() else {
234 {
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);
235 return run_in_thread_with_globals(
236 thread_stack_size,
237 edition,
238 sm_inputs,
239 extra_symbols,
240 |current_gcx| {
241 registry.register();
243
244 f(current_gcx)
245 },
246 );
247 };
248
249 let current_gcx = proof.derive(CurrentGcx::new());
250 let current_gcx2 = current_gcx.clone();
251
252 let proxy = Proxy::new();
253 let proxy_ = Arc::clone(&proxy);
254
255 let builder = rustc_thread_pool::ThreadPoolBuilder::new()
256 .thread_name(|_| "rustc".to_string())
257 .acquire_thread_handler(move || proxy.acquire_thread())
258 .release_thread_handler(move || proxy_.release_thread())
259 .num_threads(jobs_frontend.get())
260 .deadlock_handler(move || {
261 let current_gcx2 = current_gcx2.clone();
265 let registry = rustc_thread_pool::Registry::current();
266 let session_globals = rustc_span::with_session_globals(|session_globals| {
267 session_globals as *const SessionGlobals as usize
268 });
269 thread::Builder::new()
270 .name("rustc query cycle handler".to_string())
271 .spawn(move || {
272 let on_panic = defer(|| {
273 const MESSAGE: &str = "\
277internal compiler error: query cycle handler thread panicked, aborting process";
278 { ::std::io::_eprint(format_args!("{0}\n", MESSAGE)); };eprintln!("{MESSAGE}");
279 process::abort();
282 });
283
284 current_gcx2.access(|gcx| {
287 tls::enter_context(&tls::ImplicitCtxt::new(gcx), || {
288 tls::with(|tcx| {
289 let job_map = rustc_span::set_session_globals_then(
292 unsafe { &*(session_globals as *const SessionGlobals) },
293 || {
294 collect_active_query_jobs(
298 tcx,
299 CollectActiveJobsKind::FullNoContention,
300 )
301 },
302 );
303 break_query_cycle(job_map, ®istry);
304 })
305 })
306 });
307
308 on_panic.disable();
309 })
310 .unwrap();
311 })
312 .stack_size(thread_stack_size);
313
314 rustc_span::create_session_globals_then(edition, extra_symbols, Some(sm_inputs), || {
319 rustc_span::with_session_globals(|session_globals| {
320 let session_globals = proof.derive(session_globals);
321 builder
322 .build_scoped(
323 move |thread: rustc_thread_pool::ThreadBuilder| {
325 registry.register();
327
328 rustc_span::set_session_globals_then(session_globals.into_inner(), || {
329 thread.run()
330 })
331 },
332 move |pool: &rustc_thread_pool::ThreadPool| {
334 pool.install(|| f(current_gcx.into_inner()))
335 },
336 )
337 .unwrap_or_else(|err| {
338 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!(
339 "failed to spawn compiler thread pool: could not create {jobs_frontend} threads ({err})",
340 ));
341 diag.help(
342 "try lowering `-Z threads` or checking the operating system's resource limits",
343 );
344 diag.emit_fatal()
345 })
346 })
347 })
348}
349
350fn load_backend_from_dylib(early_dcx: &EarlyDiagCtxt, path: &Path) -> MakeBackendFn {
351 match unsafe { load_symbol_from_dylib::<MakeBackendFn>(path, "__rustc_codegen_backend") } {
352 Ok(backend_sym) => backend_sym,
353 Err(DylibError::DlOpen(path, err)) => {
354 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}");
355 early_dcx.early_fatal(err);
356 }
357 Err(DylibError::DlSym(_path, err)) => {
358 let e = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`__rustc_codegen_backend` symbol lookup in the codegen backend failed{0}",
err))
})format!(
359 "`__rustc_codegen_backend` symbol lookup in the codegen backend failed{err}",
360 );
361 early_dcx.early_fatal(e);
362 }
363 }
364}
365
366pub fn get_codegen_backend(
370 early_dcx: &EarlyDiagCtxt,
371 sysroot: &Sysroot,
372 backend_name: Option<&str>,
373 target: &Target,
374) -> Box<dyn CodegenBackend> {
375 static LOAD: OnceLock<unsafe fn() -> Box<dyn CodegenBackend>> = OnceLock::new();
376
377 let load = LOAD.get_or_init(|| {
378 let backend = backend_name
379 .or(target.default_codegen_backend.as_deref())
380 .or(::core::option::Option::Some("llvm")option_env!("CFG_DEFAULT_CODEGEN_BACKEND"))
381 .unwrap_or("dummy");
382
383 match backend {
384 filename if filename.contains('.') => {
385 load_backend_from_dylib(early_dcx, filename.as_ref())
386 }
387 "dummy" => || Box::new(DummyCodegenBackend),
388 #[cfg(feature = "llvm")]
389 "llvm" => rustc_codegen_llvm::LlvmCodegenBackend::new,
390 backend_name => get_codegen_sysroot(early_dcx, sysroot, backend_name),
391 }
392 });
393
394 unsafe { load() }
398}
399
400pub struct DummyCodegenBackend;
401
402impl CodegenBackend for DummyCodegenBackend {
403 fn name(&self) -> &'static str {
404 "dummy"
405 }
406
407 fn target_config(&self, sess: &EarlySession) -> TargetConfig {
408 let abi_required_features = sess.target.abi_required_features();
409 let internal_target_features = internal_target_features::<0>(
410 sess,
411 |_feature| Default::default(),
412 |feature| {
413 abi_required_features.required.contains(&feature)
418 },
419 );
420
421 TargetConfig {
422 internal_target_features,
423 has_reliable_f16: true,
424 has_reliable_f16_math: true,
425 has_reliable_f16b: true,
426 has_reliable_f128: true,
427 has_reliable_f128_math: true,
428 }
429 }
430
431 fn supported_crate_types(&self, _sess: &Session) -> Vec<CrateType> {
432 ::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]
437 }
438
439 fn target_cpu(&self, _sess: &Session) -> String {
440 String::new()
441 }
442
443 fn codegen_crate<'tcx>(&self, _tcx: TyCtxt<'tcx>) -> Box<dyn Any> {
444 Box::new(CompiledModules { modules: ::alloc::vec::Vec::new()vec![], allocator_module: None })
445 }
446
447 fn join_codegen(
448 &self,
449 ongoing_codegen: Box<dyn Any>,
450 _sess: &Session,
451 _incr_comp_session: Option<&IncrCompSession>,
452 _outputs: &OutputFilenames,
453 _crate_info: &CrateInfo,
454 ) -> (CompiledModules, WorkProductMap) {
455 (*ongoing_codegen.downcast().unwrap(), WorkProductMap::default())
456 }
457
458 fn link(
459 &self,
460 sess: &Session,
461 compiled_modules: CompiledModules,
462 crate_info: CrateInfo,
463 metadata: EncodedMetadata,
464 outputs: &OutputFilenames,
465 ) {
466 #[allow(rustc::bad_opt_access)]
468 if let Some(&crate_type) =
469 crate_info.crate_types.iter().find(|&&crate_type| crate_type != CrateType::Rlib)
470 && outputs.outputs.should_link()
471 {
472 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!(
473 "crate type {crate_type} not supported by the dummy codegen backend"
474 ));
475 }
476
477 link_binary(
478 sess,
479 &DummyArchiveBuilderBuilder,
480 compiled_modules,
481 crate_info,
482 metadata,
483 outputs,
484 self.name(),
485 );
486 }
487}
488
489struct DummyArchiveBuilderBuilder;
490
491impl ArchiveBuilderBuilder for DummyArchiveBuilderBuilder {
492 fn new_archive_builder<'a>(
493 &self,
494 sess: &'a Session,
495 ) -> Box<dyn rustc_codegen_ssa::back::archive::ArchiveBuilder + 'a> {
496 ArArchiveBuilderBuilder.new_archive_builder(sess)
497 }
498
499 fn create_dll_import_lib(
500 &self,
501 sess: &Session,
502 _lib_name: &str,
503 _items: Vec<rustc_codegen_ssa::back::archive::ImportLibraryItem>,
504 output_path: &Path,
505 ) {
506 ArArchiveBuilderBuilder.new_archive_builder(sess).build(output_path, None);
508 }
509}
510
511pub fn rustc_path<'a>(sysroot: &Sysroot) -> Option<&'a Path> {
515 static RUSTC_PATH: OnceLock<Option<PathBuf>> = OnceLock::new();
516
517 RUSTC_PATH
518 .get_or_init(|| {
519 let candidate = sysroot
520 .default
521 .join("bin"env!("RUSTC_INSTALL_BINDIR"))
522 .join(if falsecfg!(target_os = "windows") { "rustc.exe" } else { "rustc" });
523 candidate.exists().then_some(candidate)
524 })
525 .as_deref()
526}
527
528fn get_codegen_sysroot(
529 early_dcx: &EarlyDiagCtxt,
530 sysroot: &Sysroot,
531 backend_name: &str,
532) -> MakeBackendFn {
533 static LOADED: AtomicBool = AtomicBool::new(false);
539 if !!LOADED.fetch_or(true, Ordering::SeqCst) {
{
::core::panicking::panic_fmt(format_args!("cannot load the default codegen backend twice"));
}
};assert!(
540 !LOADED.fetch_or(true, Ordering::SeqCst),
541 "cannot load the default codegen backend twice"
542 );
543
544 let target = host_tuple();
545
546 let sysroot = sysroot
547 .all_paths()
548 .map(|sysroot| {
549 filesearch::make_target_lib_path(sysroot, target).with_file_name("codegen-backends")
550 })
551 .find(|f| {
552 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_interface/src/util.rs:552",
"rustc_interface::util", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("/rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_interface/src/util.rs"),
::tracing_core::__macro_support::Option::Some(552u32),
::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());
553 f.exists()
554 })
555 .unwrap_or_else(|| {
556 let candidates = sysroot
557 .all_paths()
558 .map(|p| p.display().to_string())
559 .collect::<Vec<_>>()
560 .join("\n* ");
561 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!(
562 "failed to find a `codegen-backends` folder in the sysroot candidates:\n\
563 * {candidates}"
564 );
565 early_dcx.early_fatal(err);
566 });
567
568 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_interface/src/util.rs:568",
"rustc_interface::util", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("/rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_interface/src/util.rs"),
::tracing_core::__macro_support::Option::Some(568u32),
::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());
569
570 let d = sysroot.read_dir().unwrap_or_else(|e| {
571 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!(
572 "failed to load default codegen backend, couldn't read `{}`: {e}",
573 sysroot.display(),
574 );
575 early_dcx.early_fatal(err);
576 });
577
578 let mut file: Option<PathBuf> = None;
579
580 let expected_names = &[
581 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("rustc_codegen_{0}-{1}",
backend_name, "1.101.0-nightly"))
})format!("rustc_codegen_{}-{}", backend_name, env!("CFG_RELEASE")),
582 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("rustc_codegen_{0}", backend_name))
})format!("rustc_codegen_{backend_name}"),
583 ];
584 for entry in d.filter_map(|e| e.ok()) {
585 let path = entry.path();
586 let Some(filename) = path.file_name().and_then(|s| s.to_str()) else { continue };
587 if !(filename.starts_with(DLL_PREFIX) && filename.ends_with(DLL_SUFFIX)) {
588 continue;
589 }
590 let name = &filename[DLL_PREFIX.len()..filename.len() - DLL_SUFFIX.len()];
591 if !expected_names.iter().any(|expected| expected == name) {
592 continue;
593 }
594 if let Some(ref prev) = file {
595 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!(
596 "duplicate codegen backends found\n\
597 first: {}\n\
598 second: {}\n\
599 ",
600 prev.display(),
601 path.display()
602 );
603 early_dcx.early_fatal(err);
604 }
605 file = Some(path.clone());
606 }
607
608 match file {
609 Some(ref s) => load_backend_from_dylib(early_dcx, s),
610 None => {
611 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}`");
612 early_dcx.early_fatal(err);
613 }
614 }
615}
616
617fn multiple_output_types_to_stdout(
618 output_types: &OutputTypes,
619 single_output_file_is_stdout: bool,
620) -> bool {
621 use std::io::IsTerminal;
622 if std::io::stdout().is_terminal() {
623 let named_text_types = output_types
626 .iter()
627 .filter(|(f, o)| f.is_text_output() && *o == &Some(OutFileName::Stdout))
628 .count();
629 let unnamed_text_types =
630 output_types.iter().filter(|(f, o)| f.is_text_output() && o.is_none()).count();
631 named_text_types > 1 || unnamed_text_types > 1 && single_output_file_is_stdout
632 } else {
633 let named_types =
635 output_types.values().filter(|o| *o == &Some(OutFileName::Stdout)).count();
636 let unnamed_types = output_types.values().filter(|o| o.is_none()).count();
637 named_types > 1 || unnamed_types > 1 && single_output_file_is_stdout
638 }
639}
640
641pub fn build_output_filenames(attrs: &[ast::Attribute], sess: &Session) -> OutputFilenames {
642 if multiple_output_types_to_stdout(
643 &sess.opts.output_types,
644 sess.io.output_file == Some(OutFileName::Stdout),
645 ) {
646 sess.dcx().emit_fatal(diagnostics::MultipleOutputTypesToStdout);
647 }
648
649 let crate_name =
650 sess.opts.crate_name.clone().or_else(|| {
651 parse_crate_name(sess, attrs, ShouldEmit::Nothing).map(|i| i.0.to_string())
652 });
653
654 let invocation_temp = sess
655 .opts
656 .incremental
657 .as_ref()
658 .map(|_| rng().next_u32().to_base_fixed_len(CASE_INSENSITIVE).to_string());
659
660 match sess.io.output_file {
661 None => {
662 let dirpath = sess.io.output_dir.clone().unwrap_or_default();
666
667 let stem = crate_name.clone().unwrap_or_else(|| sess.io.input.filestem().to_owned());
669
670 OutputFilenames::new(
671 dirpath,
672 crate_name.unwrap_or_else(|| stem.replace('-', "_")),
673 stem,
674 None,
675 sess.io.temps_dir.clone(),
676 invocation_temp,
677 sess.opts.unstable_opts.split_dwarf_out_dir.clone(),
678 sess.opts.cg.extra_filename.clone(),
679 sess.opts.output_types.clone(),
680 )
681 }
682
683 Some(ref out_file) => {
684 let unnamed_output_types =
685 sess.opts.output_types.values().filter(|a| a.is_none()).count();
686 let ofile = if unnamed_output_types > 1 {
687 sess.dcx().emit_warn(diagnostics::MultipleOutputTypesAdaption);
688 None
689 } else {
690 if !sess.opts.cg.extra_filename.is_empty() {
691 sess.dcx().emit_warn(diagnostics::IgnoringExtraFilename);
692 }
693 Some(out_file.clone())
694 };
695 if sess.io.output_dir.is_some() {
696 sess.dcx().emit_warn(diagnostics::IgnoringOutDir);
697 }
698
699 let out_filestem =
700 out_file.filestem().unwrap_or_default().to_str().unwrap().to_string();
701 OutputFilenames::new(
702 out_file.parent().unwrap_or_else(|| Path::new("")).to_path_buf(),
703 crate_name.unwrap_or_else(|| out_filestem.replace('-', "_")),
704 out_filestem,
705 ofile,
706 sess.io.temps_dir.clone(),
707 invocation_temp,
708 sess.opts.unstable_opts.split_dwarf_out_dir.clone(),
709 sess.opts.cg.extra_filename.clone(),
710 sess.opts.output_types.clone(),
711 )
712 }
713 }
714}
715
716pub macro version_str() {
718 option_env!("CFG_VERSION")
719}
720
721pub fn rustc_version_str() -> Option<&'static str> {
723 ::core::option::Option::Some("1.101.0-nightly (d080e7dff 2026-09-27)")version_str!()
724}