Skip to main content

rustc_interface/
util.rs

1use std::any::Any;
2use std::env::consts::{DLL_PREFIX, DLL_SUFFIX};
3use std::path::{Path, PathBuf};
4use std::sync::atomic::{AtomicBool, Ordering};
5use std::sync::{Arc, OnceLock};
6use std::{env, thread};
7
8use rand::{RngCore, rng};
9use rustc_ast as ast;
10use rustc_attr_parsing::ShouldEmit;
11use rustc_codegen_ssa::back::archive::{ArArchiveBuilderBuilder, ArchiveBuilderBuilder};
12use rustc_codegen_ssa::back::link::link_binary;
13use rustc_codegen_ssa::target_features::cfg_target_feature;
14use rustc_codegen_ssa::traits::CodegenBackend;
15use rustc_codegen_ssa::{CompiledModules, CrateInfo, TargetConfig};
16use rustc_data_structures::base_n::{CASE_INSENSITIVE, ToBaseN};
17use rustc_data_structures::jobserver::Proxy;
18use rustc_data_structures::sync;
19use rustc_metadata::{DylibError, EncodedMetadata, load_symbol_from_dylib};
20use rustc_middle::dep_graph::WorkProductMap;
21use rustc_middle::ty::{CurrentGcx, TyCtxt};
22use rustc_query_impl::{CollectActiveJobsKind, collect_active_query_jobs};
23use rustc_session::config::{
24    Cfg, CrateType, OutFileName, OutputFilenames, OutputTypes, Sysroot, host_tuple,
25};
26use rustc_session::{EarlyDiagCtxt, Session, filesearch};
27use rustc_span::edition::Edition;
28use rustc_span::source_map::SourceMapInputs;
29use rustc_span::{SessionGlobals, Symbol, sym};
30use rustc_target::spec::Target;
31use tracing::info;
32
33use crate::errors;
34use crate::passes::parse_crate_name;
35
36/// Function pointer type that constructs a new CodegenBackend.
37type MakeBackendFn = fn() -> Box<dyn CodegenBackend>;
38
39/// Adds `target_feature = "..."` cfgs for a variety of platform
40/// specific features (SSE, NEON etc.).
41///
42/// This is performed by checking whether a set of permitted features
43/// is available on the target machine, by querying the codegen backend.
44pub(crate) fn add_configuration(
45    cfg: &mut Cfg,
46    sess: &mut Session,
47    codegen_backend: &dyn CodegenBackend,
48) {
49    let tf = sym::target_feature;
50    let tf_cfg = codegen_backend.target_config(sess);
51
52    sess.unstable_target_features.extend(tf_cfg.unstable_target_features.iter().copied());
53    sess.target_features.extend(tf_cfg.target_features.iter().copied());
54
55    cfg.extend(tf_cfg.target_features.into_iter().map(|feat| (tf, Some(feat))));
56
57    if tf_cfg.has_reliable_f16 {
58        cfg.insert((sym::target_has_reliable_f16, None));
59    }
60    if tf_cfg.has_reliable_f16_math {
61        cfg.insert((sym::target_has_reliable_f16_math, None));
62    }
63    if tf_cfg.has_reliable_f128 {
64        cfg.insert((sym::target_has_reliable_f128, None));
65    }
66    if tf_cfg.has_reliable_f128_math {
67        cfg.insert((sym::target_has_reliable_f128_math, None));
68    }
69
70    if sess.crt_static(None) {
71        cfg.insert((tf, Some(sym::crt_dash_static)));
72    }
73}
74
75/// Ensures that all target features required by the ABI are present.
76/// Must be called after `unstable_target_features` has been populated!
77pub(crate) fn check_abi_required_features(sess: &Session) {
78    let abi_feature_constraints = sess.target.abi_required_features();
79    // We check this against `unstable_target_features` as that is conveniently already
80    // back-translated to rustc feature names, taking into account `-Ctarget-cpu` and `-Ctarget-feature`.
81    // Just double-check that the features we care about are actually on our list.
82    for feature in
83        abi_feature_constraints.required.iter().chain(abi_feature_constraints.incompatible.iter())
84    {
85        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!(
86            sess.target.rust_target_features().iter().any(|(name, ..)| feature == name),
87            "target feature {feature} is required/incompatible for the current ABI but not a recognized feature for this target"
88        );
89    }
90
91    for feature in abi_feature_constraints.required {
92        if !sess.unstable_target_features.contains(&Symbol::intern(feature)) {
93            sess.dcx().emit_warn(errors::AbiRequiredTargetFeature { feature, enabled: "enabled" });
94        }
95    }
96    for feature in abi_feature_constraints.incompatible {
97        if sess.unstable_target_features.contains(&Symbol::intern(feature)) {
98            sess.dcx().emit_warn(errors::AbiRequiredTargetFeature { feature, enabled: "disabled" });
99        }
100    }
101}
102
103pub static STACK_SIZE: OnceLock<usize> = OnceLock::new();
104pub const DEFAULT_STACK_SIZE: usize = 8 * 1024 * 1024;
105
106fn init_stack_size(early_dcx: &EarlyDiagCtxt) -> usize {
107    // Obey the environment setting or default
108    *STACK_SIZE.get_or_init(|| {
109        env::var_os("RUST_MIN_STACK")
110            .as_ref()
111            .map(|os_str| os_str.to_string_lossy())
112            // if someone finds out `export RUST_MIN_STACK=640000` isn't enough stack
113            // they might try to "unset" it by running `RUST_MIN_STACK=  rustc code.rs`
114            // this is wrong, but std would nonetheless "do what they mean", so let's do likewise
115            .filter(|s| !s.trim().is_empty())
116            // rustc is a batch program, so error early on inputs which are unlikely to be intended
117            // so no one thinks we parsed them setting `RUST_MIN_STACK="64 megabytes"`
118            // FIXME: we could accept `RUST_MIN_STACK=64MB`, perhaps?
119            .map(|s| {
120                let s = s.trim();
121                s.parse::<usize>().unwrap_or_else(|_| {
122                    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!(
123                        r#"`RUST_MIN_STACK` should be a number of bytes, but was "{s}""#,
124                    ));
125                    err.note("you can also unset `RUST_MIN_STACK` to use the default stack size");
126                    err.emit()
127                })
128            })
129            // otherwise pick a consistent default
130            .unwrap_or(DEFAULT_STACK_SIZE)
131    })
132}
133
134fn run_in_thread_with_globals<F: FnOnce(CurrentGcx, Arc<Proxy>) -> R + Send, R: Send>(
135    thread_stack_size: usize,
136    edition: Edition,
137    sm_inputs: SourceMapInputs,
138    extra_symbols: &[&'static str],
139    f: F,
140) -> R {
141    // The "thread pool" is a single spawned thread in the non-parallel
142    // compiler. We run on a spawned thread instead of the main thread (a) to
143    // provide control over the stack size, and (b) to increase similarity with
144    // the parallel compiler, in particular to ensure there is no accidental
145    // sharing of data between the main thread and the compilation thread
146    // (which might cause problems for the parallel compiler).
147    let builder = thread::Builder::new().name("rustc".to_string()).stack_size(thread_stack_size);
148
149    // We build the session globals and run `f` on the spawned thread, because
150    // `SessionGlobals` does not impl `Send` in the non-parallel compiler.
151    thread::scope(|s| {
152        // `unwrap` is ok here because `spawn_scoped` only panics if the thread
153        // name contains null bytes.
154        let r = builder
155            .spawn_scoped(s, move || {
156                rustc_span::create_session_globals_then(
157                    edition,
158                    extra_symbols,
159                    Some(sm_inputs),
160                    || f(CurrentGcx::new(), Proxy::new()),
161                )
162            })
163            .unwrap()
164            .join();
165
166        match r {
167            Ok(v) => v,
168            Err(e) => std::panic::resume_unwind(e),
169        }
170    })
171}
172
173pub(crate) fn run_in_thread_pool_with_globals<
174    F: FnOnce(CurrentGcx, Arc<Proxy>) -> R + Send,
175    R: Send,
176>(
177    thread_builder_diag: &EarlyDiagCtxt,
178    edition: Edition,
179    threads: usize,
180    extra_symbols: &[&'static str],
181    sm_inputs: SourceMapInputs,
182    f: F,
183) -> R {
184    use std::process;
185
186    use rustc_data_structures::defer;
187    use rustc_middle::ty::tls;
188    use rustc_query_impl::break_query_cycle;
189
190    let thread_stack_size = init_stack_size(thread_builder_diag);
191
192    let registry = sync::Registry::new(std::num::NonZero::new(threads).unwrap());
193
194    let Some(proof) = sync::check_dyn_thread_safe() else {
195        return run_in_thread_with_globals(
196            thread_stack_size,
197            edition,
198            sm_inputs,
199            extra_symbols,
200            |current_gcx, jobserver_proxy| {
201                // Register the thread for use with the `WorkerLocal` type.
202                registry.register();
203
204                f(current_gcx, jobserver_proxy)
205            },
206        );
207    };
208
209    let current_gcx = proof.derive(CurrentGcx::new());
210    let current_gcx2 = current_gcx.clone();
211
212    let proxy = Proxy::new();
213
214    let proxy_ = Arc::clone(&proxy);
215    let proxy__ = Arc::clone(&proxy);
216    let builder = rustc_thread_pool::ThreadPoolBuilder::new()
217        .thread_name(|_| "rustc".to_string())
218        .acquire_thread_handler(move || proxy_.acquire_thread())
219        .release_thread_handler(move || proxy__.release_thread())
220        .num_threads(threads)
221        .deadlock_handler(move || {
222            // On deadlock, creates a new thread and forwards information in thread
223            // locals to it. The new thread runs the deadlock handler.
224
225            let current_gcx2 = current_gcx2.clone();
226            let registry = rustc_thread_pool::Registry::current();
227            let session_globals = rustc_span::with_session_globals(|session_globals| {
228                session_globals as *const SessionGlobals as usize
229            });
230            thread::Builder::new()
231                .name("rustc query cycle handler".to_string())
232                .spawn(move || {
233                    let on_panic = defer(|| {
234                        // Split this long string so that it doesn't cause rustfmt to
235                        // give up on the entire builder expression.
236                        // <https://github.com/rust-lang/rustfmt/issues/3863>
237                        const MESSAGE: &str = "\
238internal compiler error: query cycle handler thread panicked, aborting process";
239                        { ::std::io::_eprint(format_args!("{0}\n", MESSAGE)); };eprintln!("{MESSAGE}");
240                        // We need to abort here as we failed to resolve the deadlock,
241                        // otherwise the compiler could just hang,
242                        process::abort();
243                    });
244
245                    // Get a `GlobalCtxt` reference from `CurrentGcx` as we cannot rely on having a
246                    // `TyCtxt` TLS reference here.
247                    current_gcx2.access(|gcx| {
248                        tls::enter_context(&tls::ImplicitCtxt::new(gcx), || {
249                            tls::with(|tcx| {
250                                // Accessing session globals is sound as they outlive `GlobalCtxt`.
251                                // They are needed to hash query keys containing spans or symbols.
252                                let job_map = rustc_span::set_session_globals_then(
253                                    unsafe { &*(session_globals as *const SessionGlobals) },
254                                    || {
255                                        // Ensure there were no errors collecting all active jobs.
256                                        // We need the complete map to ensure we find a cycle to
257                                        // break.
258                                        collect_active_query_jobs(
259                                            tcx,
260                                            CollectActiveJobsKind::FullNoContention,
261                                        )
262                                    },
263                                );
264                                break_query_cycle(job_map, &registry);
265                            })
266                        })
267                    });
268
269                    on_panic.disable();
270                })
271                .unwrap();
272        })
273        .stack_size(thread_stack_size);
274
275    // We create the session globals on the main thread, then create the thread
276    // pool. Upon creation, each worker thread created gets a copy of the
277    // session globals in TLS. This is possible because `SessionGlobals` impls
278    // `Send` in the parallel compiler.
279    rustc_span::create_session_globals_then(edition, extra_symbols, Some(sm_inputs), || {
280        rustc_span::with_session_globals(|session_globals| {
281            let session_globals = proof.derive(session_globals);
282            builder
283                .build_scoped(
284                    // Initialize each new worker thread when created.
285                    move |thread: rustc_thread_pool::ThreadBuilder| {
286                        // Register the thread for use with the `WorkerLocal` type.
287                        registry.register();
288
289                        rustc_span::set_session_globals_then(session_globals.into_inner(), || {
290                            thread.run()
291                        })
292                    },
293                    // Run `f` on the first thread in the thread pool.
294                    move |pool: &rustc_thread_pool::ThreadPool| {
295                        pool.install(|| f(current_gcx.into_inner(), proxy))
296                    },
297                )
298                .unwrap_or_else(|err| {
299                    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})",
                threads, err))
    })format!(
300                        "failed to spawn compiler thread pool: could not create {threads} threads ({err})",
301                    ));
302                    diag.help(
303                        "try lowering `-Z threads` or checking the operating system's resource limits",
304                    );
305                    diag.emit()
306                })
307        })
308    })
309}
310
311fn load_backend_from_dylib(early_dcx: &EarlyDiagCtxt, path: &Path) -> MakeBackendFn {
312    match unsafe { load_symbol_from_dylib::<MakeBackendFn>(path, "__rustc_codegen_backend") } {
313        Ok(backend_sym) => backend_sym,
314        Err(DylibError::DlOpen(path, err)) => {
315            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}");
316            early_dcx.early_fatal(err);
317        }
318        Err(DylibError::DlSym(_path, err)) => {
319            let e = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`__rustc_codegen_backend` symbol lookup in the codegen backend failed{0}",
                err))
    })format!(
320                "`__rustc_codegen_backend` symbol lookup in the codegen backend failed{err}",
321            );
322            early_dcx.early_fatal(e);
323        }
324    }
325}
326
327/// Get the codegen backend based on the name and specified sysroot.
328///
329/// A name of `None` indicates that the default backend should be used.
330pub fn get_codegen_backend(
331    early_dcx: &EarlyDiagCtxt,
332    sysroot: &Sysroot,
333    backend_name: Option<&str>,
334    target: &Target,
335) -> Box<dyn CodegenBackend> {
336    static LOAD: OnceLock<unsafe fn() -> Box<dyn CodegenBackend>> = OnceLock::new();
337
338    let load = LOAD.get_or_init(|| {
339        let backend = backend_name
340            .or(target.default_codegen_backend.as_deref())
341            .or(::core::option::Option::Some("llvm")option_env!("CFG_DEFAULT_CODEGEN_BACKEND"))
342            .unwrap_or("dummy");
343
344        match backend {
345            filename if filename.contains('.') => {
346                load_backend_from_dylib(early_dcx, filename.as_ref())
347            }
348            "dummy" => || Box::new(DummyCodegenBackend { target_config_override: None }),
349            #[cfg(feature = "llvm")]
350            "llvm" => rustc_codegen_llvm::LlvmCodegenBackend::new,
351            backend_name => get_codegen_sysroot(early_dcx, sysroot, backend_name),
352        }
353    });
354
355    // SAFETY: In case of a builtin codegen backend this is safe. In case of an external codegen
356    // backend we hope that the backend links against the same rustc_driver version. If this is not
357    // the case, we get UB.
358    unsafe { load() }
359}
360
361pub struct DummyCodegenBackend {
362    pub target_config_override: Option<Box<dyn Fn(&Session) -> TargetConfig>>,
363}
364
365impl CodegenBackend for DummyCodegenBackend {
366    fn name(&self) -> &'static str {
367        "dummy"
368    }
369
370    fn target_config(&self, sess: &Session) -> TargetConfig {
371        if let Some(target_config_override) = &self.target_config_override {
372            return target_config_override(sess);
373        }
374
375        let abi_required_features = sess.target.abi_required_features();
376        let (target_features, unstable_target_features) = cfg_target_feature::<0>(
377            sess,
378            |_feature| Default::default(),
379            |feature| {
380                // This is a standin for the list of features a backend is expected to enable.
381                // It would be better to parse target.features instead and handle implied features,
382                // but target.features doesn't contain features that are enabled by default for an
383                // architecture or target cpu.
384                abi_required_features.required.contains(&feature)
385            },
386        );
387
388        TargetConfig {
389            target_features,
390            unstable_target_features,
391            has_reliable_f16: true,
392            has_reliable_f16_math: true,
393            has_reliable_f128: true,
394            has_reliable_f128_math: true,
395        }
396    }
397
398    fn supported_crate_types(&self, _sess: &Session) -> Vec<CrateType> {
399        // This includes bin despite failing on the link step to ensure that you
400        // can still get the frontend handling for binaries. For all library
401        // like crate types cargo will fallback to rlib unless you specifically
402        // say that only a different crate type must be used.
403        ::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]
404    }
405
406    fn target_cpu(&self, _sess: &Session) -> String {
407        String::new()
408    }
409
410    fn codegen_crate<'tcx>(&self, _tcx: TyCtxt<'tcx>) -> Box<dyn Any> {
411        Box::new(CompiledModules { modules: ::alloc::vec::Vec::new()vec![], allocator_module: None })
412    }
413
414    fn join_codegen(
415        &self,
416        ongoing_codegen: Box<dyn Any>,
417        _sess: &Session,
418        _outputs: &OutputFilenames,
419        _crate_info: &CrateInfo,
420    ) -> (CompiledModules, WorkProductMap) {
421        (*ongoing_codegen.downcast().unwrap(), WorkProductMap::default())
422    }
423
424    fn link(
425        &self,
426        sess: &Session,
427        compiled_modules: CompiledModules,
428        crate_info: CrateInfo,
429        metadata: EncodedMetadata,
430        outputs: &OutputFilenames,
431    ) {
432        // JUSTIFICATION: TyCtxt no longer available here
433        #[allow(rustc::bad_opt_access)]
434        if let Some(&crate_type) =
435            crate_info.crate_types.iter().find(|&&crate_type| crate_type != CrateType::Rlib)
436            && outputs.outputs.should_link()
437        {
438            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!(
439                "crate type {crate_type} not supported by the dummy codegen backend"
440            ));
441        }
442
443        link_binary(
444            sess,
445            &DummyArchiveBuilderBuilder,
446            compiled_modules,
447            crate_info,
448            metadata,
449            outputs,
450            self.name(),
451        );
452    }
453}
454
455struct DummyArchiveBuilderBuilder;
456
457impl ArchiveBuilderBuilder for DummyArchiveBuilderBuilder {
458    fn new_archive_builder<'a>(
459        &self,
460        sess: &'a Session,
461    ) -> Box<dyn rustc_codegen_ssa::back::archive::ArchiveBuilder + 'a> {
462        ArArchiveBuilderBuilder.new_archive_builder(sess)
463    }
464
465    fn create_dll_import_lib(
466        &self,
467        sess: &Session,
468        _lib_name: &str,
469        _items: Vec<rustc_codegen_ssa::back::archive::ImportLibraryItem>,
470        output_path: &Path,
471    ) {
472        // Build an empty static library to avoid calling an external dlltool on mingw
473        ArArchiveBuilderBuilder.new_archive_builder(sess).build(output_path, None);
474    }
475}
476
477// This is used for rustdoc, but it uses similar machinery to codegen backend
478// loading, so we leave the code here. It is potentially useful for other tools
479// that want to invoke the rustc binary while linking to rustc as well.
480pub fn rustc_path<'a>(sysroot: &Sysroot) -> Option<&'a Path> {
481    static RUSTC_PATH: OnceLock<Option<PathBuf>> = OnceLock::new();
482
483    RUSTC_PATH
484        .get_or_init(|| {
485            let candidate = sysroot
486                .default
487                .join("bin"env!("RUSTC_INSTALL_BINDIR"))
488                .join(if falsecfg!(target_os = "windows") { "rustc.exe" } else { "rustc" });
489            candidate.exists().then_some(candidate)
490        })
491        .as_deref()
492}
493
494fn get_codegen_sysroot(
495    early_dcx: &EarlyDiagCtxt,
496    sysroot: &Sysroot,
497    backend_name: &str,
498) -> MakeBackendFn {
499    // For now we only allow this function to be called once as it'll dlopen a
500    // few things, which seems to work best if we only do that once. In
501    // general this assertion never trips due to the once guard in `get_codegen_backend`,
502    // but there's a few manual calls to this function in this file we protect
503    // against.
504    static LOADED: AtomicBool = AtomicBool::new(false);
505    if !!LOADED.fetch_or(true, Ordering::SeqCst) {
    {
        ::core::panicking::panic_fmt(format_args!("cannot load the default codegen backend twice"));
    }
};assert!(
506        !LOADED.fetch_or(true, Ordering::SeqCst),
507        "cannot load the default codegen backend twice"
508    );
509
510    let target = host_tuple();
511
512    let sysroot = sysroot
513        .all_paths()
514        .map(|sysroot| {
515            filesearch::make_target_lib_path(sysroot, target).with_file_name("codegen-backends")
516        })
517        .find(|f| {
518            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_interface/src/util.rs:518",
                        "rustc_interface::util", ::tracing::Level::INFO,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_interface/src/util.rs"),
                        ::tracing_core::__macro_support::Option::Some(518u32),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("codegen backend candidate: {0}",
                                                    f.display()) as &dyn Value))])
            });
    } else { ; }
};info!("codegen backend candidate: {}", f.display());
519            f.exists()
520        })
521        .unwrap_or_else(|| {
522            let candidates = sysroot
523                .all_paths()
524                .map(|p| p.display().to_string())
525                .collect::<Vec<_>>()
526                .join("\n* ");
527            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!(
528                "failed to find a `codegen-backends` folder in the sysroot candidates:\n\
529                 * {candidates}"
530            );
531            early_dcx.early_fatal(err);
532        });
533
534    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_interface/src/util.rs:534",
                        "rustc_interface::util", ::tracing::Level::INFO,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_interface/src/util.rs"),
                        ::tracing_core::__macro_support::Option::Some(534u32),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("probing {0} for a codegen backend",
                                                    sysroot.display()) as &dyn Value))])
            });
    } else { ; }
};info!("probing {} for a codegen backend", sysroot.display());
535
536    let d = sysroot.read_dir().unwrap_or_else(|e| {
537        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!(
538            "failed to load default codegen backend, couldn't read `{}`: {e}",
539            sysroot.display(),
540        );
541        early_dcx.early_fatal(err);
542    });
543
544    let mut file: Option<PathBuf> = None;
545
546    let expected_names = &[
547        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("rustc_codegen_{0}-{1}",
                backend_name, "1.98.0-nightly"))
    })format!("rustc_codegen_{}-{}", backend_name, env!("CFG_RELEASE")),
548        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("rustc_codegen_{0}", backend_name))
    })format!("rustc_codegen_{backend_name}"),
549    ];
550    for entry in d.filter_map(|e| e.ok()) {
551        let path = entry.path();
552        let Some(filename) = path.file_name().and_then(|s| s.to_str()) else { continue };
553        if !(filename.starts_with(DLL_PREFIX) && filename.ends_with(DLL_SUFFIX)) {
554            continue;
555        }
556        let name = &filename[DLL_PREFIX.len()..filename.len() - DLL_SUFFIX.len()];
557        if !expected_names.iter().any(|expected| expected == name) {
558            continue;
559        }
560        if let Some(ref prev) = file {
561            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!(
562                "duplicate codegen backends found\n\
563                               first:  {}\n\
564                               second: {}\n\
565            ",
566                prev.display(),
567                path.display()
568            );
569            early_dcx.early_fatal(err);
570        }
571        file = Some(path.clone());
572    }
573
574    match file {
575        Some(ref s) => load_backend_from_dylib(early_dcx, s),
576        None => {
577            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}`");
578            early_dcx.early_fatal(err);
579        }
580    }
581}
582
583fn multiple_output_types_to_stdout(
584    output_types: &OutputTypes,
585    single_output_file_is_stdout: bool,
586) -> bool {
587    use std::io::IsTerminal;
588    if std::io::stdout().is_terminal() {
589        // If stdout is a tty, check if multiple text output types are
590        // specified by `--emit foo=- --emit bar=-` or `-o - --emit foo,bar`
591        let named_text_types = output_types
592            .iter()
593            .filter(|(f, o)| f.is_text_output() && *o == &Some(OutFileName::Stdout))
594            .count();
595        let unnamed_text_types =
596            output_types.iter().filter(|(f, o)| f.is_text_output() && o.is_none()).count();
597        named_text_types > 1 || unnamed_text_types > 1 && single_output_file_is_stdout
598    } else {
599        // Otherwise, all the output types should be checked
600        let named_types =
601            output_types.values().filter(|o| *o == &Some(OutFileName::Stdout)).count();
602        let unnamed_types = output_types.values().filter(|o| o.is_none()).count();
603        named_types > 1 || unnamed_types > 1 && single_output_file_is_stdout
604    }
605}
606
607pub fn build_output_filenames(attrs: &[ast::Attribute], sess: &Session) -> OutputFilenames {
608    if multiple_output_types_to_stdout(
609        &sess.opts.output_types,
610        sess.io.output_file == Some(OutFileName::Stdout),
611    ) {
612        sess.dcx().emit_fatal(errors::MultipleOutputTypesToStdout);
613    }
614
615    let crate_name =
616        sess.opts.crate_name.clone().or_else(|| {
617            parse_crate_name(sess, attrs, ShouldEmit::Nothing).map(|i| i.0.to_string())
618        });
619
620    let invocation_temp = sess
621        .opts
622        .incremental
623        .as_ref()
624        .map(|_| rng().next_u32().to_base_fixed_len(CASE_INSENSITIVE).to_string());
625
626    match sess.io.output_file {
627        None => {
628            // "-" as input file will cause the parser to read from stdin so we
629            // have to make up a name
630            // We want to toss everything after the final '.'
631            let dirpath = sess.io.output_dir.clone().unwrap_or_default();
632
633            // If a crate name is present, we use it as the link name
634            let stem = crate_name.clone().unwrap_or_else(|| sess.io.input.filestem().to_owned());
635
636            OutputFilenames::new(
637                dirpath,
638                crate_name.unwrap_or_else(|| stem.replace('-', "_")),
639                stem,
640                None,
641                sess.io.temps_dir.clone(),
642                invocation_temp,
643                sess.opts.unstable_opts.split_dwarf_out_dir.clone(),
644                sess.opts.cg.extra_filename.clone(),
645                sess.opts.output_types.clone(),
646            )
647        }
648
649        Some(ref out_file) => {
650            let unnamed_output_types =
651                sess.opts.output_types.values().filter(|a| a.is_none()).count();
652            let ofile = if unnamed_output_types > 1 {
653                sess.dcx().emit_warn(errors::MultipleOutputTypesAdaption);
654                None
655            } else {
656                if !sess.opts.cg.extra_filename.is_empty() {
657                    sess.dcx().emit_warn(errors::IgnoringExtraFilename);
658                }
659                Some(out_file.clone())
660            };
661            if sess.io.output_dir.is_some() {
662                sess.dcx().emit_warn(errors::IgnoringOutDir);
663            }
664
665            let out_filestem =
666                out_file.filestem().unwrap_or_default().to_str().unwrap().to_string();
667            OutputFilenames::new(
668                out_file.parent().unwrap_or_else(|| Path::new("")).to_path_buf(),
669                crate_name.unwrap_or_else(|| out_filestem.replace('-', "_")),
670                out_filestem,
671                ofile,
672                sess.io.temps_dir.clone(),
673                invocation_temp,
674                sess.opts.unstable_opts.split_dwarf_out_dir.clone(),
675                sess.opts.cg.extra_filename.clone(),
676                sess.opts.output_types.clone(),
677            )
678        }
679    }
680}
681
682/// Returns a version string such as "1.46.0 (04488afe3 2020-08-24)" when invoked by an in-tree tool.
683pub macro version_str() {
684    option_env!("CFG_VERSION")
685}
686
687/// Returns the version string for `rustc` itself (which may be different from a tool version).
688pub fn rustc_version_str() -> Option<&'static str> {
689    ::core::option::Option::Some("1.98.0-nightly (beae78130 2026-06-09)")version_str!()
690}