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