rustc_codegen_ssa/back/
write.rs

1use std::marker::PhantomData;
2use std::panic::AssertUnwindSafe;
3use std::path::{Path, PathBuf};
4use std::sync::Arc;
5use std::sync::mpsc::{Receiver, Sender, channel};
6use std::{fs, io, mem, str, thread};
7
8use rustc_abi::Size;
9use rustc_ast::attr;
10use rustc_data_structures::assert_matches;
11use rustc_data_structures::fx::FxIndexMap;
12use rustc_data_structures::jobserver::{self, Acquired};
13use rustc_data_structures::memmap::Mmap;
14use rustc_data_structures::profiling::{SelfProfilerRef, VerboseTimingGuard};
15use rustc_errors::emitter::Emitter;
16use rustc_errors::translation::Translator;
17use rustc_errors::{
18    Diag, DiagArgMap, DiagCtxt, DiagCtxtHandle, DiagMessage, ErrCode, FatalError, FatalErrorMarker,
19    Level, MultiSpan, Style, Suggestions, catch_fatal_errors,
20};
21use rustc_fs_util::link_or_copy;
22use rustc_incremental::{
23    copy_cgu_workproduct_to_incr_comp_cache_dir, in_incr_comp_dir, in_incr_comp_dir_sess,
24};
25use rustc_metadata::fs::copy_to_stdout;
26use rustc_middle::bug;
27use rustc_middle::dep_graph::{WorkProduct, WorkProductId};
28use rustc_middle::ty::TyCtxt;
29use rustc_session::Session;
30use rustc_session::config::{
31    self, CrateType, Lto, OutFileName, OutputFilenames, OutputType, Passes, SwitchWithOptPath,
32};
33use rustc_span::source_map::SourceMap;
34use rustc_span::{FileName, InnerSpan, Span, SpanData, sym};
35use rustc_target::spec::{MergeFunctions, SanitizerSet};
36use tracing::debug;
37
38use super::link::{self, ensure_removed};
39use super::lto::{self, SerializedModule};
40use crate::back::lto::check_lto_allowed;
41use crate::errors::ErrorCreatingRemarkDir;
42use crate::traits::*;
43use crate::{
44    CachedModuleCodegen, CodegenResults, CompiledModule, CrateInfo, ModuleCodegen, ModuleKind,
45    errors,
46};
47
48const PRE_LTO_BC_EXT: &str = "pre-lto.bc";
49
50/// What kind of object file to emit.
51#[derive(#[automatically_derived]
impl ::core::clone::Clone for EmitObj {
    #[inline]
    fn clone(&self) -> EmitObj {
        let _: ::core::clone::AssertParamIsClone<BitcodeSection>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for EmitObj { }Copy, #[automatically_derived]
impl ::core::cmp::PartialEq for EmitObj {
    #[inline]
    fn eq(&self, other: &EmitObj) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr &&
            match (self, other) {
                (EmitObj::ObjectCode(__self_0), EmitObj::ObjectCode(__arg1_0))
                    => __self_0 == __arg1_0,
                _ => true,
            }
    }
}PartialEq)]
52pub enum EmitObj {
53    // No object file.
54    None,
55
56    // Just uncompressed llvm bitcode. Provides easy compatibility with
57    // emscripten's ecc compiler, when used as the linker.
58    Bitcode,
59
60    // Object code, possibly augmented with a bitcode section.
61    ObjectCode(BitcodeSection),
62}
63
64/// What kind of llvm bitcode section to embed in an object file.
65#[derive(#[automatically_derived]
impl ::core::clone::Clone for BitcodeSection {
    #[inline]
    fn clone(&self) -> BitcodeSection { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for BitcodeSection { }Copy, #[automatically_derived]
impl ::core::cmp::PartialEq for BitcodeSection {
    #[inline]
    fn eq(&self, other: &BitcodeSection) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq)]
66pub enum BitcodeSection {
67    // No bitcode section.
68    None,
69
70    // A full, uncompressed bitcode section.
71    Full,
72}
73
74/// Module-specific configuration for `optimize_and_codegen`.
75pub struct ModuleConfig {
76    /// Names of additional optimization passes to run.
77    pub passes: Vec<String>,
78    /// Some(level) to optimize at a certain level, or None to run
79    /// absolutely no optimizations (used for the allocator module).
80    pub opt_level: Option<config::OptLevel>,
81
82    pub pgo_gen: SwitchWithOptPath,
83    pub pgo_use: Option<PathBuf>,
84    pub pgo_sample_use: Option<PathBuf>,
85    pub debug_info_for_profiling: bool,
86    pub instrument_coverage: bool,
87
88    pub sanitizer: SanitizerSet,
89    pub sanitizer_recover: SanitizerSet,
90    pub sanitizer_dataflow_abilist: Vec<String>,
91    pub sanitizer_memory_track_origins: usize,
92
93    // Flags indicating which outputs to produce.
94    pub emit_pre_lto_bc: bool,
95    pub emit_no_opt_bc: bool,
96    pub emit_bc: bool,
97    pub emit_ir: bool,
98    pub emit_asm: bool,
99    pub emit_obj: EmitObj,
100    pub emit_thin_lto: bool,
101    pub emit_thin_lto_summary: bool,
102
103    // Miscellaneous flags. These are mostly copied from command-line
104    // options.
105    pub verify_llvm_ir: bool,
106    pub lint_llvm_ir: bool,
107    pub no_prepopulate_passes: bool,
108    pub no_builtins: bool,
109    pub vectorize_loop: bool,
110    pub vectorize_slp: bool,
111    pub merge_functions: bool,
112    pub emit_lifetime_markers: bool,
113    pub llvm_plugins: Vec<String>,
114    pub autodiff: Vec<config::AutoDiff>,
115    pub offload: Vec<config::Offload>,
116}
117
118impl ModuleConfig {
119    fn new(kind: ModuleKind, tcx: TyCtxt<'_>, no_builtins: bool) -> ModuleConfig {
120        // If it's a regular module, use `$regular`, otherwise use `$other`.
121        // `$regular` and `$other` are evaluated lazily.
122        macro_rules! if_regular {
123            ($regular: expr, $other: expr) => {
124                if let ModuleKind::Regular = kind { $regular } else { $other }
125            };
126        }
127
128        let sess = tcx.sess;
129        let opt_level_and_size = if let ModuleKind::Regular = kind { Some(sess.opts.optimize) } else { None }if_regular!(Some(sess.opts.optimize), None);
130
131        let save_temps = sess.opts.cg.save_temps;
132
133        let should_emit_obj = sess.opts.output_types.contains_key(&OutputType::Exe)
134            || match kind {
135                ModuleKind::Regular => sess.opts.output_types.contains_key(&OutputType::Object),
136                ModuleKind::Allocator => false,
137            };
138
139        let emit_obj = if !should_emit_obj {
140            EmitObj::None
141        } else if sess.target.obj_is_bitcode
142            || (sess.opts.cg.linker_plugin_lto.enabled() && !no_builtins)
143        {
144            // This case is selected if the target uses objects as bitcode, or
145            // if linker plugin LTO is enabled. In the linker plugin LTO case
146            // the assumption is that the final link-step will read the bitcode
147            // and convert it to object code. This may be done by either the
148            // native linker or rustc itself.
149            //
150            // Note, however, that the linker-plugin-lto requested here is
151            // explicitly ignored for `#![no_builtins]` crates. These crates are
152            // specifically ignored by rustc's LTO passes and wouldn't work if
153            // loaded into the linker. These crates define symbols that LLVM
154            // lowers intrinsics to, and these symbol dependencies aren't known
155            // until after codegen. As a result any crate marked
156            // `#![no_builtins]` is assumed to not participate in LTO and
157            // instead goes on to generate object code.
158            EmitObj::Bitcode
159        } else if need_bitcode_in_object(tcx) {
160            EmitObj::ObjectCode(BitcodeSection::Full)
161        } else {
162            EmitObj::ObjectCode(BitcodeSection::None)
163        };
164
165        ModuleConfig {
166            passes: if let ModuleKind::Regular = kind {
    sess.opts.cg.passes.clone()
} else { ::alloc::vec::Vec::new() }if_regular!(sess.opts.cg.passes.clone(), vec![]),
167
168            opt_level: opt_level_and_size,
169
170            pgo_gen: if let ModuleKind::Regular = kind {
    sess.opts.cg.profile_generate.clone()
} else { SwitchWithOptPath::Disabled }if_regular!(
171                sess.opts.cg.profile_generate.clone(),
172                SwitchWithOptPath::Disabled
173            ),
174            pgo_use: if let ModuleKind::Regular = kind {
    sess.opts.cg.profile_use.clone()
} else { None }if_regular!(sess.opts.cg.profile_use.clone(), None),
175            pgo_sample_use: if let ModuleKind::Regular = kind {
    sess.opts.unstable_opts.profile_sample_use.clone()
} else { None }if_regular!(sess.opts.unstable_opts.profile_sample_use.clone(), None),
176            debug_info_for_profiling: sess.opts.unstable_opts.debug_info_for_profiling,
177            instrument_coverage: if let ModuleKind::Regular = kind {
    sess.instrument_coverage()
} else { false }if_regular!(sess.instrument_coverage(), false),
178
179            sanitizer: if let ModuleKind::Regular = kind {
    sess.sanitizers()
} else { SanitizerSet::empty() }if_regular!(sess.sanitizers(), SanitizerSet::empty()),
180            sanitizer_dataflow_abilist: if let ModuleKind::Regular = kind {
    sess.opts.unstable_opts.sanitizer_dataflow_abilist.clone()
} else { Vec::new() }if_regular!(
181                sess.opts.unstable_opts.sanitizer_dataflow_abilist.clone(),
182                Vec::new()
183            ),
184            sanitizer_recover: if let ModuleKind::Regular = kind {
    sess.opts.unstable_opts.sanitizer_recover
} else { SanitizerSet::empty() }if_regular!(
185                sess.opts.unstable_opts.sanitizer_recover,
186                SanitizerSet::empty()
187            ),
188            sanitizer_memory_track_origins: if let ModuleKind::Regular = kind {
    sess.opts.unstable_opts.sanitizer_memory_track_origins
} else { 0 }if_regular!(
189                sess.opts.unstable_opts.sanitizer_memory_track_origins,
190                0
191            ),
192
193            emit_pre_lto_bc: if let ModuleKind::Regular = kind {
    save_temps || need_pre_lto_bitcode_for_incr_comp(sess)
} else { false }if_regular!(
194                save_temps || need_pre_lto_bitcode_for_incr_comp(sess),
195                false
196            ),
197            emit_no_opt_bc: if let ModuleKind::Regular = kind { save_temps } else { false }if_regular!(save_temps, false),
198            emit_bc: if let ModuleKind::Regular = kind {
    save_temps || sess.opts.output_types.contains_key(&OutputType::Bitcode)
} else { save_temps }if_regular!(
199                save_temps || sess.opts.output_types.contains_key(&OutputType::Bitcode),
200                save_temps
201            ),
202            emit_ir: if let ModuleKind::Regular = kind {
    sess.opts.output_types.contains_key(&OutputType::LlvmAssembly)
} else { false }if_regular!(
203                sess.opts.output_types.contains_key(&OutputType::LlvmAssembly),
204                false
205            ),
206            emit_asm: if let ModuleKind::Regular = kind {
    sess.opts.output_types.contains_key(&OutputType::Assembly)
} else { false }if_regular!(
207                sess.opts.output_types.contains_key(&OutputType::Assembly),
208                false
209            ),
210            emit_obj,
211            // thin lto summaries prevent fat lto, so do not emit them if fat
212            // lto is requested. See PR #136840 for background information.
213            emit_thin_lto: sess.opts.unstable_opts.emit_thin_lto && sess.lto() != Lto::Fat,
214            emit_thin_lto_summary: if let ModuleKind::Regular = kind {
    sess.opts.output_types.contains_key(&OutputType::ThinLinkBitcode)
} else { false }if_regular!(
215                sess.opts.output_types.contains_key(&OutputType::ThinLinkBitcode),
216                false
217            ),
218
219            verify_llvm_ir: sess.verify_llvm_ir(),
220            lint_llvm_ir: sess.opts.unstable_opts.lint_llvm_ir,
221            no_prepopulate_passes: sess.opts.cg.no_prepopulate_passes,
222            no_builtins: no_builtins || sess.target.no_builtins,
223
224            // Copy what clang does by turning on loop vectorization at O2 and
225            // slp vectorization at O3.
226            vectorize_loop: !sess.opts.cg.no_vectorize_loops
227                && (sess.opts.optimize == config::OptLevel::More
228                    || sess.opts.optimize == config::OptLevel::Aggressive),
229            vectorize_slp: !sess.opts.cg.no_vectorize_slp
230                && sess.opts.optimize == config::OptLevel::Aggressive,
231
232            // Some targets (namely, NVPTX) interact badly with the
233            // MergeFunctions pass. This is because MergeFunctions can generate
234            // new function calls which may interfere with the target calling
235            // convention; e.g. for the NVPTX target, PTX kernels should not
236            // call other PTX kernels. MergeFunctions can also be configured to
237            // generate aliases instead, but aliases are not supported by some
238            // backends (again, NVPTX). Therefore, allow targets to opt out of
239            // the MergeFunctions pass, but otherwise keep the pass enabled (at
240            // O2 and O3) since it can be useful for reducing code size.
241            merge_functions: match sess
242                .opts
243                .unstable_opts
244                .merge_functions
245                .unwrap_or(sess.target.merge_functions)
246            {
247                MergeFunctions::Disabled => false,
248                MergeFunctions::Trampolines | MergeFunctions::Aliases => {
249                    use config::OptLevel::*;
250                    match sess.opts.optimize {
251                        Aggressive | More | SizeMin | Size => true,
252                        Less | No => false,
253                    }
254                }
255            },
256
257            emit_lifetime_markers: sess.emit_lifetime_markers(),
258            llvm_plugins: if let ModuleKind::Regular = kind {
    sess.opts.unstable_opts.llvm_plugins.clone()
} else { ::alloc::vec::Vec::new() }if_regular!(sess.opts.unstable_opts.llvm_plugins.clone(), vec![]),
259            autodiff: if let ModuleKind::Regular = kind {
    sess.opts.unstable_opts.autodiff.clone()
} else { ::alloc::vec::Vec::new() }if_regular!(sess.opts.unstable_opts.autodiff.clone(), vec![]),
260            offload: if let ModuleKind::Regular = kind {
    sess.opts.unstable_opts.offload.clone()
} else { ::alloc::vec::Vec::new() }if_regular!(sess.opts.unstable_opts.offload.clone(), vec![]),
261        }
262    }
263
264    pub fn bitcode_needed(&self) -> bool {
265        self.emit_bc
266            || self.emit_thin_lto_summary
267            || self.emit_obj == EmitObj::Bitcode
268            || self.emit_obj == EmitObj::ObjectCode(BitcodeSection::Full)
269    }
270
271    pub fn embed_bitcode(&self) -> bool {
272        self.emit_obj == EmitObj::ObjectCode(BitcodeSection::Full)
273    }
274}
275
276/// Configuration passed to the function returned by the `target_machine_factory`.
277pub struct TargetMachineFactoryConfig {
278    /// Split DWARF is enabled in LLVM by checking that `TM.MCOptions.SplitDwarfFile` isn't empty,
279    /// so the path to the dwarf object has to be provided when we create the target machine.
280    /// This can be ignored by backends which do not need it for their Split DWARF support.
281    pub split_dwarf_file: Option<PathBuf>,
282
283    /// The name of the output object file. Used for setting OutputFilenames in target options
284    /// so that LLVM can emit the CodeView S_OBJNAME record in pdb files
285    pub output_obj_file: Option<PathBuf>,
286}
287
288impl TargetMachineFactoryConfig {
289    pub fn new(
290        cgcx: &CodegenContext<impl WriteBackendMethods>,
291        module_name: &str,
292    ) -> TargetMachineFactoryConfig {
293        let split_dwarf_file = if cgcx.target_can_use_split_dwarf {
294            cgcx.output_filenames.split_dwarf_path(
295                cgcx.split_debuginfo,
296                cgcx.split_dwarf_kind,
297                module_name,
298                cgcx.invocation_temp.as_deref(),
299            )
300        } else {
301            None
302        };
303
304        let output_obj_file = Some(cgcx.output_filenames.temp_path_for_cgu(
305            OutputType::Object,
306            module_name,
307            cgcx.invocation_temp.as_deref(),
308        ));
309        TargetMachineFactoryConfig { split_dwarf_file, output_obj_file }
310    }
311}
312
313pub type TargetMachineFactoryFn<B> = Arc<
314    dyn Fn(
315            TargetMachineFactoryConfig,
316        ) -> Result<
317            <B as WriteBackendMethods>::TargetMachine,
318            <B as WriteBackendMethods>::TargetMachineError,
319        > + Send
320        + Sync,
321>;
322
323/// Additional resources used by optimize_and_codegen (not module specific)
324#[derive(#[automatically_derived]
impl<B: ::core::clone::Clone + WriteBackendMethods> ::core::clone::Clone for
    CodegenContext<B> {
    #[inline]
    fn clone(&self) -> CodegenContext<B> {
        CodegenContext {
            prof: ::core::clone::Clone::clone(&self.prof),
            lto: ::core::clone::Clone::clone(&self.lto),
            use_linker_plugin_lto: ::core::clone::Clone::clone(&self.use_linker_plugin_lto),
            dylib_lto: ::core::clone::Clone::clone(&self.dylib_lto),
            prefer_dynamic: ::core::clone::Clone::clone(&self.prefer_dynamic),
            save_temps: ::core::clone::Clone::clone(&self.save_temps),
            fewer_names: ::core::clone::Clone::clone(&self.fewer_names),
            time_trace: ::core::clone::Clone::clone(&self.time_trace),
            crate_types: ::core::clone::Clone::clone(&self.crate_types),
            output_filenames: ::core::clone::Clone::clone(&self.output_filenames),
            invocation_temp: ::core::clone::Clone::clone(&self.invocation_temp),
            module_config: ::core::clone::Clone::clone(&self.module_config),
            tm_factory: ::core::clone::Clone::clone(&self.tm_factory),
            msvc_imps_needed: ::core::clone::Clone::clone(&self.msvc_imps_needed),
            is_pe_coff: ::core::clone::Clone::clone(&self.is_pe_coff),
            target_can_use_split_dwarf: ::core::clone::Clone::clone(&self.target_can_use_split_dwarf),
            target_arch: ::core::clone::Clone::clone(&self.target_arch),
            target_is_like_darwin: ::core::clone::Clone::clone(&self.target_is_like_darwin),
            target_is_like_aix: ::core::clone::Clone::clone(&self.target_is_like_aix),
            target_is_like_gpu: ::core::clone::Clone::clone(&self.target_is_like_gpu),
            split_debuginfo: ::core::clone::Clone::clone(&self.split_debuginfo),
            split_dwarf_kind: ::core::clone::Clone::clone(&self.split_dwarf_kind),
            pointer_size: ::core::clone::Clone::clone(&self.pointer_size),
            remark: ::core::clone::Clone::clone(&self.remark),
            remark_dir: ::core::clone::Clone::clone(&self.remark_dir),
            incr_comp_session_dir: ::core::clone::Clone::clone(&self.incr_comp_session_dir),
            parallel: ::core::clone::Clone::clone(&self.parallel),
        }
    }
}Clone)]
325pub struct CodegenContext<B: WriteBackendMethods> {
326    // Resources needed when running LTO
327    pub prof: SelfProfilerRef,
328    pub lto: Lto,
329    pub use_linker_plugin_lto: bool,
330    pub dylib_lto: bool,
331    pub prefer_dynamic: bool,
332    pub save_temps: bool,
333    pub fewer_names: bool,
334    pub time_trace: bool,
335    pub crate_types: Vec<CrateType>,
336    pub output_filenames: Arc<OutputFilenames>,
337    pub invocation_temp: Option<String>,
338    pub module_config: Arc<ModuleConfig>,
339    pub tm_factory: TargetMachineFactoryFn<B>,
340    pub msvc_imps_needed: bool,
341    pub is_pe_coff: bool,
342    pub target_can_use_split_dwarf: bool,
343    pub target_arch: String,
344    pub target_is_like_darwin: bool,
345    pub target_is_like_aix: bool,
346    pub target_is_like_gpu: bool,
347    pub split_debuginfo: rustc_target::spec::SplitDebuginfo,
348    pub split_dwarf_kind: rustc_session::config::SplitDwarfKind,
349    pub pointer_size: Size,
350
351    /// LLVM optimizations for which we want to print remarks.
352    pub remark: Passes,
353    /// Directory into which should the LLVM optimization remarks be written.
354    /// If `None`, they will be written to stderr.
355    pub remark_dir: Option<PathBuf>,
356    /// The incremental compilation session directory, or None if we are not
357    /// compiling incrementally
358    pub incr_comp_session_dir: Option<PathBuf>,
359    /// `true` if the codegen should be run in parallel.
360    ///
361    /// Depends on [`ExtraBackendMethods::supports_parallel()`] and `-Zno_parallel_backend`.
362    pub parallel: bool,
363}
364
365fn generate_thin_lto_work<B: ExtraBackendMethods>(
366    cgcx: &CodegenContext<B>,
367    dcx: DiagCtxtHandle<'_>,
368    exported_symbols_for_lto: &[String],
369    each_linked_rlib_for_lto: &[PathBuf],
370    needs_thin_lto: Vec<(String, B::ThinBuffer)>,
371    import_only_modules: Vec<(SerializedModule<B::ModuleBuffer>, WorkProduct)>,
372) -> Vec<(ThinLtoWorkItem<B>, u64)> {
373    let _prof_timer = cgcx.prof.generic_activity("codegen_thin_generate_lto_work");
374
375    let (lto_modules, copy_jobs) = B::run_thin_lto(
376        cgcx,
377        dcx,
378        exported_symbols_for_lto,
379        each_linked_rlib_for_lto,
380        needs_thin_lto,
381        import_only_modules,
382    );
383    lto_modules
384        .into_iter()
385        .map(|module| {
386            let cost = module.cost();
387            (ThinLtoWorkItem::ThinLto(module), cost)
388        })
389        .chain(copy_jobs.into_iter().map(|wp| {
390            (
391                ThinLtoWorkItem::CopyPostLtoArtifacts(CachedModuleCodegen {
392                    name: wp.cgu_name.clone(),
393                    source: wp,
394                }),
395                0, // copying is very cheap
396            )
397        }))
398        .collect()
399}
400
401struct CompiledModules {
402    modules: Vec<CompiledModule>,
403    allocator_module: Option<CompiledModule>,
404}
405
406enum MaybeLtoModules<B: WriteBackendMethods> {
407    NoLto {
408        modules: Vec<CompiledModule>,
409        allocator_module: Option<CompiledModule>,
410    },
411    FatLto {
412        cgcx: CodegenContext<B>,
413        exported_symbols_for_lto: Arc<Vec<String>>,
414        each_linked_rlib_file_for_lto: Vec<PathBuf>,
415        needs_fat_lto: Vec<FatLtoInput<B>>,
416        lto_import_only_modules:
417            Vec<(SerializedModule<<B as WriteBackendMethods>::ModuleBuffer>, WorkProduct)>,
418    },
419    ThinLto {
420        cgcx: CodegenContext<B>,
421        exported_symbols_for_lto: Arc<Vec<String>>,
422        each_linked_rlib_file_for_lto: Vec<PathBuf>,
423        needs_thin_lto: Vec<(String, <B as WriteBackendMethods>::ThinBuffer)>,
424        lto_import_only_modules:
425            Vec<(SerializedModule<<B as WriteBackendMethods>::ModuleBuffer>, WorkProduct)>,
426    },
427}
428
429fn need_bitcode_in_object(tcx: TyCtxt<'_>) -> bool {
430    let sess = tcx.sess;
431    sess.opts.cg.embed_bitcode
432        && tcx.crate_types().contains(&CrateType::Rlib)
433        && sess.opts.output_types.contains_key(&OutputType::Exe)
434}
435
436fn need_pre_lto_bitcode_for_incr_comp(sess: &Session) -> bool {
437    if sess.opts.incremental.is_none() {
438        return false;
439    }
440
441    match sess.lto() {
442        Lto::No => false,
443        Lto::Fat | Lto::Thin | Lto::ThinLocal => true,
444    }
445}
446
447pub(crate) fn start_async_codegen<B: ExtraBackendMethods>(
448    backend: B,
449    tcx: TyCtxt<'_>,
450    target_cpu: String,
451    allocator_module: Option<ModuleCodegen<B::Module>>,
452) -> OngoingCodegen<B> {
453    let (coordinator_send, coordinator_receive) = channel();
454
455    let crate_attrs = tcx.hir_attrs(rustc_hir::CRATE_HIR_ID);
456    let no_builtins = attr::contains_name(crate_attrs, sym::no_builtins);
457
458    let crate_info = CrateInfo::new(tcx, target_cpu);
459
460    let regular_config = ModuleConfig::new(ModuleKind::Regular, tcx, no_builtins);
461    let allocator_config = ModuleConfig::new(ModuleKind::Allocator, tcx, no_builtins);
462
463    let (shared_emitter, shared_emitter_main) = SharedEmitter::new();
464    let (codegen_worker_send, codegen_worker_receive) = channel();
465
466    let coordinator_thread = start_executing_work(
467        backend.clone(),
468        tcx,
469        &crate_info,
470        shared_emitter,
471        codegen_worker_send,
472        coordinator_receive,
473        Arc::new(regular_config),
474        Arc::new(allocator_config),
475        allocator_module,
476        coordinator_send.clone(),
477    );
478
479    OngoingCodegen {
480        backend,
481        crate_info,
482
483        codegen_worker_receive,
484        shared_emitter_main,
485        coordinator: Coordinator {
486            sender: coordinator_send,
487            future: Some(coordinator_thread),
488            phantom: PhantomData,
489        },
490        output_filenames: Arc::clone(tcx.output_filenames(())),
491    }
492}
493
494fn copy_all_cgu_workproducts_to_incr_comp_cache_dir(
495    sess: &Session,
496    compiled_modules: &CompiledModules,
497) -> FxIndexMap<WorkProductId, WorkProduct> {
498    let mut work_products = FxIndexMap::default();
499
500    if sess.opts.incremental.is_none() {
501        return work_products;
502    }
503
504    let _timer = sess.timer("copy_all_cgu_workproducts_to_incr_comp_cache_dir");
505
506    for module in compiled_modules.modules.iter().filter(|m| m.kind == ModuleKind::Regular) {
507        let mut files = Vec::new();
508        if let Some(object_file_path) = &module.object {
509            files.push((OutputType::Object.extension(), object_file_path.as_path()));
510        }
511        if let Some(dwarf_object_file_path) = &module.dwarf_object {
512            files.push(("dwo", dwarf_object_file_path.as_path()));
513        }
514        if let Some(path) = &module.assembly {
515            files.push((OutputType::Assembly.extension(), path.as_path()));
516        }
517        if let Some(path) = &module.llvm_ir {
518            files.push((OutputType::LlvmAssembly.extension(), path.as_path()));
519        }
520        if let Some(path) = &module.bytecode {
521            files.push((OutputType::Bitcode.extension(), path.as_path()));
522        }
523        if let Some((id, product)) = copy_cgu_workproduct_to_incr_comp_cache_dir(
524            sess,
525            &module.name,
526            files.as_slice(),
527            &module.links_from_incr_cache,
528        ) {
529            work_products.insert(id, product);
530        }
531    }
532
533    work_products
534}
535
536fn produce_final_output_artifacts(
537    sess: &Session,
538    compiled_modules: &CompiledModules,
539    crate_output: &OutputFilenames,
540) {
541    let mut user_wants_bitcode = false;
542    let mut user_wants_objects = false;
543
544    // Produce final compile outputs.
545    let copy_gracefully = |from: &Path, to: &OutFileName| match to {
546        OutFileName::Stdout if let Err(e) = copy_to_stdout(from) => {
547            sess.dcx().emit_err(errors::CopyPath::new(from, to.as_path(), e));
548        }
549        OutFileName::Real(path) if let Err(e) = fs::copy(from, path) => {
550            sess.dcx().emit_err(errors::CopyPath::new(from, path, e));
551        }
552        _ => {}
553    };
554
555    let copy_if_one_unit = |output_type: OutputType, keep_numbered: bool| {
556        if let [module] = &compiled_modules.modules[..] {
557            // 1) Only one codegen unit. In this case it's no difficulty
558            //    to copy `foo.0.x` to `foo.x`.
559            let path = crate_output.temp_path_for_cgu(
560                output_type,
561                &module.name,
562                sess.invocation_temp.as_deref(),
563            );
564            let output = crate_output.path(output_type);
565            if !output_type.is_text_output() && output.is_tty() {
566                sess.dcx()
567                    .emit_err(errors::BinaryOutputToTty { shorthand: output_type.shorthand() });
568            } else {
569                copy_gracefully(&path, &output);
570            }
571            if !sess.opts.cg.save_temps && !keep_numbered {
572                // The user just wants `foo.x`, not `foo.#module-name#.x`.
573                ensure_removed(sess.dcx(), &path);
574            }
575        } else {
576            if crate_output.outputs.contains_explicit_name(&output_type) {
577                // 2) Multiple codegen units, with `--emit foo=some_name`. We have
578                //    no good solution for this case, so warn the user.
579                sess.dcx()
580                    .emit_warn(errors::IgnoringEmitPath { extension: output_type.extension() });
581            } else if crate_output.single_output_file.is_some() {
582                // 3) Multiple codegen units, with `-o some_name`. We have
583                //    no good solution for this case, so warn the user.
584                sess.dcx().emit_warn(errors::IgnoringOutput { extension: output_type.extension() });
585            } else {
586                // 4) Multiple codegen units, but no explicit name. We
587                //    just leave the `foo.0.x` files in place.
588                // (We don't have to do any work in this case.)
589            }
590        }
591    };
592
593    // Flag to indicate whether the user explicitly requested bitcode.
594    // Otherwise, we produced it only as a temporary output, and will need
595    // to get rid of it.
596    for output_type in crate_output.outputs.keys() {
597        match *output_type {
598            OutputType::Bitcode => {
599                user_wants_bitcode = true;
600                // Copy to .bc, but always keep the .0.bc. There is a later
601                // check to figure out if we should delete .0.bc files, or keep
602                // them for making an rlib.
603                copy_if_one_unit(OutputType::Bitcode, true);
604            }
605            OutputType::ThinLinkBitcode => {
606                copy_if_one_unit(OutputType::ThinLinkBitcode, false);
607            }
608            OutputType::LlvmAssembly => {
609                copy_if_one_unit(OutputType::LlvmAssembly, false);
610            }
611            OutputType::Assembly => {
612                copy_if_one_unit(OutputType::Assembly, false);
613            }
614            OutputType::Object => {
615                user_wants_objects = true;
616                copy_if_one_unit(OutputType::Object, true);
617            }
618            OutputType::Mir | OutputType::Metadata | OutputType::Exe | OutputType::DepInfo => {}
619        }
620    }
621
622    // Clean up unwanted temporary files.
623
624    // We create the following files by default:
625    //  - #crate#.#module-name#.bc
626    //  - #crate#.#module-name#.o
627    //  - #crate#.crate.metadata.bc
628    //  - #crate#.crate.metadata.o
629    //  - #crate#.o (linked from crate.##.o)
630    //  - #crate#.bc (copied from crate.##.bc)
631    // We may create additional files if requested by the user (through
632    // `-C save-temps` or `--emit=` flags).
633
634    if !sess.opts.cg.save_temps {
635        // Remove the temporary .#module-name#.o objects. If the user didn't
636        // explicitly request bitcode (with --emit=bc), and the bitcode is not
637        // needed for building an rlib, then we must remove .#module-name#.bc as
638        // well.
639
640        // Specific rules for keeping .#module-name#.bc:
641        //  - If the user requested bitcode (`user_wants_bitcode`), and
642        //    codegen_units > 1, then keep it.
643        //  - If the user requested bitcode but codegen_units == 1, then we
644        //    can toss .#module-name#.bc because we copied it to .bc earlier.
645        //  - If we're not building an rlib and the user didn't request
646        //    bitcode, then delete .#module-name#.bc.
647        // If you change how this works, also update back::link::link_rlib,
648        // where .#module-name#.bc files are (maybe) deleted after making an
649        // rlib.
650        let needs_crate_object = crate_output.outputs.contains_key(&OutputType::Exe);
651
652        let keep_numbered_bitcode = user_wants_bitcode && sess.codegen_units().as_usize() > 1;
653
654        let keep_numbered_objects =
655            needs_crate_object || (user_wants_objects && sess.codegen_units().as_usize() > 1);
656
657        for module in compiled_modules.modules.iter() {
658            if !keep_numbered_objects {
659                if let Some(ref path) = module.object {
660                    ensure_removed(sess.dcx(), path);
661                }
662
663                if let Some(ref path) = module.dwarf_object {
664                    ensure_removed(sess.dcx(), path);
665                }
666            }
667
668            if let Some(ref path) = module.bytecode {
669                if !keep_numbered_bitcode {
670                    ensure_removed(sess.dcx(), path);
671                }
672            }
673        }
674
675        if !user_wants_bitcode
676            && let Some(ref allocator_module) = compiled_modules.allocator_module
677            && let Some(ref path) = allocator_module.bytecode
678        {
679            ensure_removed(sess.dcx(), path);
680        }
681    }
682
683    if sess.opts.json_artifact_notifications {
684        if let [module] = &compiled_modules.modules[..] {
685            module.for_each_output(|_path, ty| {
686                if sess.opts.output_types.contains_key(&ty) {
687                    let descr = ty.shorthand();
688                    // for single cgu file is renamed to drop cgu specific suffix
689                    // so we regenerate it the same way
690                    let path = crate_output.path(ty);
691                    sess.dcx().emit_artifact_notification(path.as_path(), descr);
692                }
693            });
694        } else {
695            for module in &compiled_modules.modules {
696                module.for_each_output(|path, ty| {
697                    if sess.opts.output_types.contains_key(&ty) {
698                        let descr = ty.shorthand();
699                        sess.dcx().emit_artifact_notification(&path, descr);
700                    }
701                });
702            }
703        }
704    }
705
706    // We leave the following files around by default:
707    //  - #crate#.o
708    //  - #crate#.crate.metadata.o
709    //  - #crate#.bc
710    // These are used in linking steps and will be cleaned up afterward.
711}
712
713pub(crate) enum WorkItem<B: WriteBackendMethods> {
714    /// Optimize a newly codegened, totally unoptimized module.
715    Optimize(ModuleCodegen<B::Module>),
716    /// Copy the post-LTO artifacts from the incremental cache to the output
717    /// directory.
718    CopyPostLtoArtifacts(CachedModuleCodegen),
719}
720
721enum ThinLtoWorkItem<B: WriteBackendMethods> {
722    /// Copy the post-LTO artifacts from the incremental cache to the output
723    /// directory.
724    CopyPostLtoArtifacts(CachedModuleCodegen),
725    /// Performs thin-LTO on the given module.
726    ThinLto(lto::ThinModule<B>),
727}
728
729// `pthread_setname()` on *nix ignores anything beyond the first 15
730// bytes. Use short descriptions to maximize the space available for
731// the module name.
732#[cfg(not(windows))]
733fn desc(short: &str, _long: &str, name: &str) -> String {
734    // The short label is three bytes, and is followed by a space. That
735    // leaves 11 bytes for the CGU name. How we obtain those 11 bytes
736    // depends on the CGU name form.
737    //
738    // - Non-incremental, e.g. `regex.f10ba03eb5ec7975-cgu.0`: the part
739    //   before the `-cgu.0` is the same for every CGU, so use the
740    //   `cgu.0` part. The number suffix will be different for each
741    //   CGU.
742    //
743    // - Incremental (normal), e.g. `2i52vvl2hco29us0`: use the whole
744    //   name because each CGU will have a unique ASCII hash, and the
745    //   first 11 bytes will be enough to identify it.
746    //
747    // - Incremental (with `-Zhuman-readable-cgu-names`), e.g.
748    //   `regex.f10ba03eb5ec7975-re_builder.volatile`: use the whole
749    //   name. The first 11 bytes won't be enough to uniquely identify
750    //   it, but no obvious substring will, and this is a rarely used
751    //   option so it doesn't matter much.
752    //
753    match (&short.len(), &3) {
    (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!(short.len(), 3);
754    let name = if let Some(index) = name.find("-cgu.") {
755        &name[index + 1..] // +1 skips the leading '-'.
756    } else {
757        name
758    };
759    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} {1}", short, name))
    })format!("{short} {name}")
760}
761
762// Windows has no thread name length limit, so use more descriptive names.
763#[cfg(windows)]
764fn desc(_short: &str, long: &str, name: &str) -> String {
765    format!("{long} {name}")
766}
767
768impl<B: WriteBackendMethods> WorkItem<B> {
769    /// Generate a short description of this work item suitable for use as a thread name.
770    fn short_description(&self) -> String {
771        match self {
772            WorkItem::Optimize(m) => desc("opt", "optimize module", &m.name),
773            WorkItem::CopyPostLtoArtifacts(m) => desc("cpy", "copy LTO artifacts for", &m.name),
774        }
775    }
776}
777
778impl<B: WriteBackendMethods> ThinLtoWorkItem<B> {
779    /// Generate a short description of this work item suitable for use as a thread name.
780    fn short_description(&self) -> String {
781        match self {
782            ThinLtoWorkItem::CopyPostLtoArtifacts(m) => {
783                desc("cpy", "copy LTO artifacts for", &m.name)
784            }
785            ThinLtoWorkItem::ThinLto(m) => desc("lto", "thin-LTO module", m.name()),
786        }
787    }
788}
789
790/// A result produced by the backend.
791pub(crate) enum WorkItemResult<B: WriteBackendMethods> {
792    /// The backend has finished compiling a CGU, nothing more required.
793    Finished(CompiledModule),
794
795    /// The backend has finished compiling a CGU, which now needs to go through
796    /// fat LTO.
797    NeedsFatLto(FatLtoInput<B>),
798
799    /// The backend has finished compiling a CGU, which now needs to go through
800    /// thin LTO.
801    NeedsThinLto(String, B::ThinBuffer),
802}
803
804pub enum FatLtoInput<B: WriteBackendMethods> {
805    Serialized { name: String, buffer: SerializedModule<B::ModuleBuffer> },
806    InMemory(ModuleCodegen<B::Module>),
807}
808
809/// Actual LTO type we end up choosing based on multiple factors.
810pub(crate) enum ComputedLtoType {
811    No,
812    Thin,
813    Fat,
814}
815
816pub(crate) fn compute_per_cgu_lto_type(
817    sess_lto: &Lto,
818    linker_does_lto: bool,
819    sess_crate_types: &[CrateType],
820) -> ComputedLtoType {
821    // If the linker does LTO, we don't have to do it. Note that we
822    // keep doing full LTO, if it is requested, as not to break the
823    // assumption that the output will be a single module.
824
825    // We ignore a request for full crate graph LTO if the crate type
826    // is only an rlib, as there is no full crate graph to process,
827    // that'll happen later.
828    //
829    // This use case currently comes up primarily for targets that
830    // require LTO so the request for LTO is always unconditionally
831    // passed down to the backend, but we don't actually want to do
832    // anything about it yet until we've got a final product.
833    let is_rlib = #[allow(non_exhaustive_omitted_patterns)] match sess_crate_types {
    [CrateType::Rlib] => true,
    _ => false,
}matches!(sess_crate_types, [CrateType::Rlib]);
834
835    match sess_lto {
836        Lto::ThinLocal if !linker_does_lto => ComputedLtoType::Thin,
837        Lto::Thin if !linker_does_lto && !is_rlib => ComputedLtoType::Thin,
838        Lto::Fat if !is_rlib => ComputedLtoType::Fat,
839        _ => ComputedLtoType::No,
840    }
841}
842
843fn execute_optimize_work_item<B: ExtraBackendMethods>(
844    cgcx: &CodegenContext<B>,
845    shared_emitter: SharedEmitter,
846    mut module: ModuleCodegen<B::Module>,
847) -> WorkItemResult<B> {
848    let _timer = cgcx.prof.generic_activity_with_arg("codegen_module_optimize", &*module.name);
849
850    B::optimize(cgcx, &shared_emitter, &mut module, &cgcx.module_config);
851
852    // After we've done the initial round of optimizations we need to
853    // decide whether to synchronously codegen this module or ship it
854    // back to the coordinator thread for further LTO processing (which
855    // has to wait for all the initial modules to be optimized).
856
857    let lto_type =
858        compute_per_cgu_lto_type(&cgcx.lto, cgcx.use_linker_plugin_lto, &cgcx.crate_types);
859
860    // If we're doing some form of incremental LTO then we need to be sure to
861    // save our module to disk first.
862    let bitcode = if cgcx.module_config.emit_pre_lto_bc {
863        let filename = pre_lto_bitcode_filename(&module.name);
864        cgcx.incr_comp_session_dir.as_ref().map(|path| path.join(&filename))
865    } else {
866        None
867    };
868
869    match lto_type {
870        ComputedLtoType::No => {
871            let module = B::codegen(cgcx, &shared_emitter, module, &cgcx.module_config);
872            WorkItemResult::Finished(module)
873        }
874        ComputedLtoType::Thin => {
875            let (name, thin_buffer) = B::prepare_thin(module);
876            if let Some(path) = bitcode {
877                fs::write(&path, thin_buffer.data()).unwrap_or_else(|e| {
878                    {
    ::core::panicking::panic_fmt(format_args!("Error writing pre-lto-bitcode file `{0}`: {1}",
            path.display(), e));
};panic!("Error writing pre-lto-bitcode file `{}`: {}", path.display(), e);
879                });
880            }
881            WorkItemResult::NeedsThinLto(name, thin_buffer)
882        }
883        ComputedLtoType::Fat => match bitcode {
884            Some(path) => {
885                let (name, buffer) = B::serialize_module(module);
886                fs::write(&path, buffer.data()).unwrap_or_else(|e| {
887                    {
    ::core::panicking::panic_fmt(format_args!("Error writing pre-lto-bitcode file `{0}`: {1}",
            path.display(), e));
};panic!("Error writing pre-lto-bitcode file `{}`: {}", path.display(), e);
888                });
889                WorkItemResult::NeedsFatLto(FatLtoInput::Serialized {
890                    name,
891                    buffer: SerializedModule::Local(buffer),
892                })
893            }
894            None => WorkItemResult::NeedsFatLto(FatLtoInput::InMemory(module)),
895        },
896    }
897}
898
899fn execute_copy_from_cache_work_item<B: ExtraBackendMethods>(
900    cgcx: &CodegenContext<B>,
901    shared_emitter: SharedEmitter,
902    module: CachedModuleCodegen,
903) -> CompiledModule {
904    let _timer = cgcx
905        .prof
906        .generic_activity_with_arg("codegen_copy_artifacts_from_incr_cache", &*module.name);
907
908    let dcx = DiagCtxt::new(Box::new(shared_emitter));
909    let dcx = dcx.handle();
910
911    let incr_comp_session_dir = cgcx.incr_comp_session_dir.as_ref().unwrap();
912
913    let mut links_from_incr_cache = Vec::new();
914
915    let mut load_from_incr_comp_dir = |output_path: PathBuf, saved_path: &str| {
916        let source_file = in_incr_comp_dir(incr_comp_session_dir, saved_path);
917        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/back/write.rs:917",
                        "rustc_codegen_ssa::back::write", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/back/write.rs"),
                        ::tracing_core::__macro_support::Option::Some(917u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::write"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::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!("copying preexisting module `{0}` from {1:?} to {2}",
                                                    module.name, source_file, output_path.display()) as
                                            &dyn Value))])
            });
    } else { ; }
};debug!(
918            "copying preexisting module `{}` from {:?} to {}",
919            module.name,
920            source_file,
921            output_path.display()
922        );
923        match link_or_copy(&source_file, &output_path) {
924            Ok(_) => {
925                links_from_incr_cache.push(source_file);
926                Some(output_path)
927            }
928            Err(error) => {
929                dcx.emit_err(errors::CopyPathBuf { source_file, output_path, error });
930                None
931            }
932        }
933    };
934
935    let dwarf_object =
936        module.source.saved_files.get("dwo").as_ref().and_then(|saved_dwarf_object_file| {
937            let dwarf_obj_out = cgcx
938                .output_filenames
939                .split_dwarf_path(
940                    cgcx.split_debuginfo,
941                    cgcx.split_dwarf_kind,
942                    &module.name,
943                    cgcx.invocation_temp.as_deref(),
944                )
945                .expect(
946                    "saved dwarf object in work product but `split_dwarf_path` returned `None`",
947                );
948            load_from_incr_comp_dir(dwarf_obj_out, saved_dwarf_object_file)
949        });
950
951    let mut load_from_incr_cache = |perform, output_type: OutputType| {
952        if perform {
953            let saved_file = module.source.saved_files.get(output_type.extension())?;
954            let output_path = cgcx.output_filenames.temp_path_for_cgu(
955                output_type,
956                &module.name,
957                cgcx.invocation_temp.as_deref(),
958            );
959            load_from_incr_comp_dir(output_path, &saved_file)
960        } else {
961            None
962        }
963    };
964
965    let module_config = &cgcx.module_config;
966    let should_emit_obj = module_config.emit_obj != EmitObj::None;
967    let assembly = load_from_incr_cache(module_config.emit_asm, OutputType::Assembly);
968    let llvm_ir = load_from_incr_cache(module_config.emit_ir, OutputType::LlvmAssembly);
969    let bytecode = load_from_incr_cache(module_config.emit_bc, OutputType::Bitcode);
970    let object = load_from_incr_cache(should_emit_obj, OutputType::Object);
971    if should_emit_obj && object.is_none() {
972        dcx.emit_fatal(errors::NoSavedObjectFile { cgu_name: &module.name })
973    }
974
975    CompiledModule {
976        links_from_incr_cache,
977        kind: ModuleKind::Regular,
978        name: module.name,
979        object,
980        dwarf_object,
981        bytecode,
982        assembly,
983        llvm_ir,
984    }
985}
986
987fn do_fat_lto<B: ExtraBackendMethods>(
988    cgcx: &CodegenContext<B>,
989    shared_emitter: SharedEmitter,
990    exported_symbols_for_lto: &[String],
991    each_linked_rlib_for_lto: &[PathBuf],
992    mut needs_fat_lto: Vec<FatLtoInput<B>>,
993    import_only_modules: Vec<(SerializedModule<B::ModuleBuffer>, WorkProduct)>,
994) -> CompiledModule {
995    let _timer = cgcx.prof.verbose_generic_activity("LLVM_fatlto");
996
997    let dcx = DiagCtxt::new(Box::new(shared_emitter.clone()));
998    let dcx = dcx.handle();
999
1000    check_lto_allowed(&cgcx, dcx);
1001
1002    for (module, wp) in import_only_modules {
1003        needs_fat_lto.push(FatLtoInput::Serialized { name: wp.cgu_name, buffer: module })
1004    }
1005
1006    let module = B::run_and_optimize_fat_lto(
1007        cgcx,
1008        &shared_emitter,
1009        exported_symbols_for_lto,
1010        each_linked_rlib_for_lto,
1011        needs_fat_lto,
1012    );
1013    B::codegen(cgcx, &shared_emitter, module, &cgcx.module_config)
1014}
1015
1016fn do_thin_lto<'a, B: ExtraBackendMethods>(
1017    cgcx: &'a CodegenContext<B>,
1018    shared_emitter: SharedEmitter,
1019    exported_symbols_for_lto: Arc<Vec<String>>,
1020    each_linked_rlib_for_lto: Vec<PathBuf>,
1021    needs_thin_lto: Vec<(String, <B as WriteBackendMethods>::ThinBuffer)>,
1022    lto_import_only_modules: Vec<(
1023        SerializedModule<<B as WriteBackendMethods>::ModuleBuffer>,
1024        WorkProduct,
1025    )>,
1026) -> Vec<CompiledModule> {
1027    let _timer = cgcx.prof.verbose_generic_activity("LLVM_thinlto");
1028
1029    let dcx = DiagCtxt::new(Box::new(shared_emitter.clone()));
1030    let dcx = dcx.handle();
1031
1032    check_lto_allowed(&cgcx, dcx);
1033
1034    let (coordinator_send, coordinator_receive) = channel();
1035
1036    // First up, convert our jobserver into a helper thread so we can use normal
1037    // mpsc channels to manage our messages and such.
1038    // After we've requested tokens then we'll, when we can,
1039    // get tokens on `coordinator_receive` which will
1040    // get managed in the main loop below.
1041    let coordinator_send2 = coordinator_send.clone();
1042    let helper = jobserver::client()
1043        .into_helper_thread(move |token| {
1044            drop(coordinator_send2.send(ThinLtoMessage::Token(token)));
1045        })
1046        .expect("failed to spawn helper thread");
1047
1048    let mut work_items = ::alloc::vec::Vec::new()vec![];
1049
1050    // We have LTO work to do. Perform the serial work here of
1051    // figuring out what we're going to LTO and then push a
1052    // bunch of work items onto our queue to do LTO. This all
1053    // happens on the coordinator thread but it's very quick so
1054    // we don't worry about tokens.
1055    for (work, cost) in generate_thin_lto_work(
1056        cgcx,
1057        dcx,
1058        &exported_symbols_for_lto,
1059        &each_linked_rlib_for_lto,
1060        needs_thin_lto,
1061        lto_import_only_modules,
1062    ) {
1063        let insertion_index =
1064            work_items.binary_search_by_key(&cost, |&(_, cost)| cost).unwrap_or_else(|e| e);
1065        work_items.insert(insertion_index, (work, cost));
1066        if cgcx.parallel {
1067            helper.request_token();
1068        }
1069    }
1070
1071    let mut codegen_aborted = None;
1072
1073    // These are the Jobserver Tokens we currently hold. Does not include
1074    // the implicit Token the compiler process owns no matter what.
1075    let mut tokens = ::alloc::vec::Vec::new()vec![];
1076
1077    // Amount of tokens that are used (including the implicit token).
1078    let mut used_token_count = 0;
1079
1080    let mut compiled_modules = ::alloc::vec::Vec::new()vec![];
1081
1082    // Run the message loop while there's still anything that needs message
1083    // processing. Note that as soon as codegen is aborted we simply want to
1084    // wait for all existing work to finish, so many of the conditions here
1085    // only apply if codegen hasn't been aborted as they represent pending
1086    // work to be done.
1087    loop {
1088        if codegen_aborted.is_none() {
1089            if used_token_count == 0 && work_items.is_empty() {
1090                // All codegen work is done.
1091                break;
1092            }
1093
1094            // Spin up what work we can, only doing this while we've got available
1095            // parallelism slots and work left to spawn.
1096            while used_token_count < tokens.len() + 1
1097                && let Some((item, _)) = work_items.pop()
1098            {
1099                spawn_thin_lto_work(&cgcx, shared_emitter.clone(), coordinator_send.clone(), item);
1100                used_token_count += 1;
1101            }
1102        } else {
1103            // Don't queue up any more work if codegen was aborted, we're
1104            // just waiting for our existing children to finish.
1105            if used_token_count == 0 {
1106                break;
1107            }
1108        }
1109
1110        // Relinquish accidentally acquired extra tokens. Subtract 1 for the implicit token.
1111        tokens.truncate(used_token_count.saturating_sub(1));
1112
1113        match coordinator_receive.recv().unwrap() {
1114            // Save the token locally and the next turn of the loop will use
1115            // this to spawn a new unit of work, or it may get dropped
1116            // immediately if we have no more work to spawn.
1117            ThinLtoMessage::Token(token) => match token {
1118                Ok(token) => {
1119                    tokens.push(token);
1120                }
1121                Err(e) => {
1122                    let msg = &::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("failed to acquire jobserver token: {0}",
                e))
    })format!("failed to acquire jobserver token: {e}");
1123                    shared_emitter.fatal(msg);
1124                    codegen_aborted = Some(FatalError);
1125                }
1126            },
1127
1128            ThinLtoMessage::WorkItem { result } => {
1129                // If a thread exits successfully then we drop a token associated
1130                // with that worker and update our `used_token_count` count.
1131                // We may later re-acquire a token to continue running more work.
1132                // We may also not actually drop a token here if the worker was
1133                // running with an "ephemeral token".
1134                used_token_count -= 1;
1135
1136                match result {
1137                    Ok(compiled_module) => compiled_modules.push(compiled_module),
1138                    Err(Some(WorkerFatalError)) => {
1139                        // Like `CodegenAborted`, wait for remaining work to finish.
1140                        codegen_aborted = Some(FatalError);
1141                    }
1142                    Err(None) => {
1143                        // If the thread failed that means it panicked, so
1144                        // we abort immediately.
1145                        ::rustc_middle::util::bug::bug_fmt(format_args!("worker thread panicked"));bug!("worker thread panicked");
1146                    }
1147                }
1148            }
1149        }
1150    }
1151
1152    if let Some(codegen_aborted) = codegen_aborted {
1153        codegen_aborted.raise();
1154    }
1155
1156    compiled_modules
1157}
1158
1159fn execute_thin_lto_work_item<B: ExtraBackendMethods>(
1160    cgcx: &CodegenContext<B>,
1161    shared_emitter: SharedEmitter,
1162    module: lto::ThinModule<B>,
1163) -> CompiledModule {
1164    let _timer = cgcx.prof.generic_activity_with_arg("codegen_module_perform_lto", module.name());
1165
1166    let module = B::optimize_thin(cgcx, &shared_emitter, module);
1167    B::codegen(cgcx, &shared_emitter, module, &cgcx.module_config)
1168}
1169
1170/// Messages sent to the coordinator.
1171pub(crate) enum Message<B: WriteBackendMethods> {
1172    /// A jobserver token has become available. Sent from the jobserver helper
1173    /// thread.
1174    Token(io::Result<Acquired>),
1175
1176    /// The backend has finished processing a work item for a codegen unit.
1177    /// Sent from a backend worker thread.
1178    WorkItem { result: Result<WorkItemResult<B>, Option<WorkerFatalError>> },
1179
1180    /// The frontend has finished generating something (backend IR or a
1181    /// post-LTO artifact) for a codegen unit, and it should be passed to the
1182    /// backend. Sent from the main thread.
1183    CodegenDone { llvm_work_item: WorkItem<B>, cost: u64 },
1184
1185    /// Similar to `CodegenDone`, but for reusing a pre-LTO artifact
1186    /// Sent from the main thread.
1187    AddImportOnlyModule {
1188        module_data: SerializedModule<B::ModuleBuffer>,
1189        work_product: WorkProduct,
1190    },
1191
1192    /// The frontend has finished generating everything for all codegen units.
1193    /// Sent from the main thread.
1194    CodegenComplete,
1195
1196    /// Some normal-ish compiler error occurred, and codegen should be wound
1197    /// down. Sent from the main thread.
1198    CodegenAborted,
1199}
1200
1201/// Messages sent to the coordinator.
1202pub(crate) enum ThinLtoMessage {
1203    /// A jobserver token has become available. Sent from the jobserver helper
1204    /// thread.
1205    Token(io::Result<Acquired>),
1206
1207    /// The backend has finished processing a work item for a codegen unit.
1208    /// Sent from a backend worker thread.
1209    WorkItem { result: Result<CompiledModule, Option<WorkerFatalError>> },
1210}
1211
1212/// A message sent from the coordinator thread to the main thread telling it to
1213/// process another codegen unit.
1214pub struct CguMessage;
1215
1216// A cut-down version of `rustc_errors::DiagInner` that impls `Send`, which
1217// can be used to send diagnostics from codegen threads to the main thread.
1218// It's missing the following fields from `rustc_errors::DiagInner`.
1219// - `span`: it doesn't impl `Send`.
1220// - `suggestions`: it doesn't impl `Send`, and isn't used for codegen
1221//   diagnostics.
1222// - `sort_span`: it doesn't impl `Send`.
1223// - `is_lint`: lints aren't relevant during codegen.
1224// - `emitted_at`: not used for codegen diagnostics.
1225struct Diagnostic {
1226    span: Vec<SpanData>,
1227    level: Level,
1228    messages: Vec<(DiagMessage, Style)>,
1229    code: Option<ErrCode>,
1230    children: Vec<Subdiagnostic>,
1231    args: DiagArgMap,
1232}
1233
1234// A cut-down version of `rustc_errors::Subdiag` that impls `Send`. It's
1235// missing the following fields from `rustc_errors::Subdiag`.
1236// - `span`: it doesn't impl `Send`.
1237struct Subdiagnostic {
1238    level: Level,
1239    messages: Vec<(DiagMessage, Style)>,
1240}
1241
1242#[derive(#[automatically_derived]
impl ::core::cmp::PartialEq for MainThreadState {
    #[inline]
    fn eq(&self, other: &MainThreadState) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq, #[automatically_derived]
impl ::core::clone::Clone for MainThreadState {
    #[inline]
    fn clone(&self) -> MainThreadState { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for MainThreadState { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for MainThreadState {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                MainThreadState::Idle => "Idle",
                MainThreadState::Codegenning => "Codegenning",
                MainThreadState::Lending => "Lending",
            })
    }
}Debug)]
1243enum MainThreadState {
1244    /// Doing nothing.
1245    Idle,
1246
1247    /// Doing codegen, i.e. MIR-to-LLVM-IR conversion.
1248    Codegenning,
1249
1250    /// Idle, but lending the compiler process's Token to an LLVM thread so it can do useful work.
1251    Lending,
1252}
1253
1254fn start_executing_work<B: ExtraBackendMethods>(
1255    backend: B,
1256    tcx: TyCtxt<'_>,
1257    crate_info: &CrateInfo,
1258    shared_emitter: SharedEmitter,
1259    codegen_worker_send: Sender<CguMessage>,
1260    coordinator_receive: Receiver<Message<B>>,
1261    regular_config: Arc<ModuleConfig>,
1262    allocator_config: Arc<ModuleConfig>,
1263    mut allocator_module: Option<ModuleCodegen<B::Module>>,
1264    coordinator_send: Sender<Message<B>>,
1265) -> thread::JoinHandle<Result<MaybeLtoModules<B>, ()>> {
1266    let sess = tcx.sess;
1267
1268    let mut each_linked_rlib_for_lto = Vec::new();
1269    let mut each_linked_rlib_file_for_lto = Vec::new();
1270    drop(link::each_linked_rlib(crate_info, None, &mut |cnum, path| {
1271        if link::ignored_for_lto(sess, crate_info, cnum) {
1272            return;
1273        }
1274        each_linked_rlib_for_lto.push(cnum);
1275        each_linked_rlib_file_for_lto.push(path.to_path_buf());
1276    }));
1277
1278    // Compute the set of symbols we need to retain when doing LTO (if we need to)
1279    let exported_symbols_for_lto =
1280        Arc::new(lto::exported_symbols_for_lto(tcx, &each_linked_rlib_for_lto));
1281
1282    // First up, convert our jobserver into a helper thread so we can use normal
1283    // mpsc channels to manage our messages and such.
1284    // After we've requested tokens then we'll, when we can,
1285    // get tokens on `coordinator_receive` which will
1286    // get managed in the main loop below.
1287    let coordinator_send2 = coordinator_send.clone();
1288    let helper = jobserver::client()
1289        .into_helper_thread(move |token| {
1290            drop(coordinator_send2.send(Message::Token::<B>(token)));
1291        })
1292        .expect("failed to spawn helper thread");
1293
1294    let ol = tcx.backend_optimization_level(());
1295    let backend_features = tcx.global_backend_features(());
1296
1297    let remark_dir = if let Some(ref dir) = sess.opts.unstable_opts.remark_dir {
1298        let result = fs::create_dir_all(dir).and_then(|_| dir.canonicalize());
1299        match result {
1300            Ok(dir) => Some(dir),
1301            Err(error) => sess.dcx().emit_fatal(ErrorCreatingRemarkDir { error }),
1302        }
1303    } else {
1304        None
1305    };
1306
1307    let cgcx = CodegenContext::<B> {
1308        crate_types: tcx.crate_types().to_vec(),
1309        lto: sess.lto(),
1310        use_linker_plugin_lto: sess.opts.cg.linker_plugin_lto.enabled(),
1311        dylib_lto: sess.opts.unstable_opts.dylib_lto,
1312        prefer_dynamic: sess.opts.cg.prefer_dynamic,
1313        fewer_names: sess.fewer_names(),
1314        save_temps: sess.opts.cg.save_temps,
1315        time_trace: sess.opts.unstable_opts.llvm_time_trace,
1316        prof: sess.prof.clone(),
1317        remark: sess.opts.cg.remark.clone(),
1318        remark_dir,
1319        incr_comp_session_dir: sess.incr_comp_session_dir_opt().map(|r| r.clone()),
1320        output_filenames: Arc::clone(tcx.output_filenames(())),
1321        module_config: regular_config,
1322        tm_factory: backend.target_machine_factory(tcx.sess, ol, backend_features),
1323        msvc_imps_needed: msvc_imps_needed(tcx),
1324        is_pe_coff: tcx.sess.target.is_like_windows,
1325        target_can_use_split_dwarf: tcx.sess.target_can_use_split_dwarf(),
1326        target_arch: tcx.sess.target.arch.to_string(),
1327        target_is_like_darwin: tcx.sess.target.is_like_darwin,
1328        target_is_like_aix: tcx.sess.target.is_like_aix,
1329        target_is_like_gpu: tcx.sess.target.is_like_gpu,
1330        split_debuginfo: tcx.sess.split_debuginfo(),
1331        split_dwarf_kind: tcx.sess.opts.unstable_opts.split_dwarf_kind,
1332        parallel: backend.supports_parallel() && !sess.opts.unstable_opts.no_parallel_backend,
1333        pointer_size: tcx.data_layout.pointer_size(),
1334        invocation_temp: sess.invocation_temp.clone(),
1335    };
1336
1337    // This is the "main loop" of parallel work happening for parallel codegen.
1338    // It's here that we manage parallelism, schedule work, and work with
1339    // messages coming from clients.
1340    //
1341    // There are a few environmental pre-conditions that shape how the system
1342    // is set up:
1343    //
1344    // - Error reporting can only happen on the main thread because that's the
1345    //   only place where we have access to the compiler `Session`.
1346    // - LLVM work can be done on any thread.
1347    // - Codegen can only happen on the main thread.
1348    // - Each thread doing substantial work must be in possession of a `Token`
1349    //   from the `Jobserver`.
1350    // - The compiler process always holds one `Token`. Any additional `Tokens`
1351    //   have to be requested from the `Jobserver`.
1352    //
1353    // Error Reporting
1354    // ===============
1355    // The error reporting restriction is handled separately from the rest: We
1356    // set up a `SharedEmitter` that holds an open channel to the main thread.
1357    // When an error occurs on any thread, the shared emitter will send the
1358    // error message to the receiver main thread (`SharedEmitterMain`). The
1359    // main thread will periodically query this error message queue and emit
1360    // any error messages it has received. It might even abort compilation if
1361    // it has received a fatal error. In this case we rely on all other threads
1362    // being torn down automatically with the main thread.
1363    // Since the main thread will often be busy doing codegen work, error
1364    // reporting will be somewhat delayed, since the message queue can only be
1365    // checked in between two work packages.
1366    //
1367    // Work Processing Infrastructure
1368    // ==============================
1369    // The work processing infrastructure knows three major actors:
1370    //
1371    // - the coordinator thread,
1372    // - the main thread, and
1373    // - LLVM worker threads
1374    //
1375    // The coordinator thread is running a message loop. It instructs the main
1376    // thread about what work to do when, and it will spawn off LLVM worker
1377    // threads as open LLVM WorkItems become available.
1378    //
1379    // The job of the main thread is to codegen CGUs into LLVM work packages
1380    // (since the main thread is the only thread that can do this). The main
1381    // thread will block until it receives a message from the coordinator, upon
1382    // which it will codegen one CGU, send it to the coordinator and block
1383    // again. This way the coordinator can control what the main thread is
1384    // doing.
1385    //
1386    // The coordinator keeps a queue of LLVM WorkItems, and when a `Token` is
1387    // available, it will spawn off a new LLVM worker thread and let it process
1388    // a WorkItem. When a LLVM worker thread is done with its WorkItem,
1389    // it will just shut down, which also frees all resources associated with
1390    // the given LLVM module, and sends a message to the coordinator that the
1391    // WorkItem has been completed.
1392    //
1393    // Work Scheduling
1394    // ===============
1395    // The scheduler's goal is to minimize the time it takes to complete all
1396    // work there is, however, we also want to keep memory consumption low
1397    // if possible. These two goals are at odds with each other: If memory
1398    // consumption were not an issue, we could just let the main thread produce
1399    // LLVM WorkItems at full speed, assuring maximal utilization of
1400    // Tokens/LLVM worker threads. However, since codegen is usually faster
1401    // than LLVM processing, the queue of LLVM WorkItems would fill up and each
1402    // WorkItem potentially holds on to a substantial amount of memory.
1403    //
1404    // So the actual goal is to always produce just enough LLVM WorkItems as
1405    // not to starve our LLVM worker threads. That means, once we have enough
1406    // WorkItems in our queue, we can block the main thread, so it does not
1407    // produce more until we need them.
1408    //
1409    // Doing LLVM Work on the Main Thread
1410    // ----------------------------------
1411    // Since the main thread owns the compiler process's implicit `Token`, it is
1412    // wasteful to keep it blocked without doing any work. Therefore, what we do
1413    // in this case is: We spawn off an additional LLVM worker thread that helps
1414    // reduce the queue. The work it is doing corresponds to the implicit
1415    // `Token`. The coordinator will mark the main thread as being busy with
1416    // LLVM work. (The actual work happens on another OS thread but we just care
1417    // about `Tokens`, not actual threads).
1418    //
1419    // When any LLVM worker thread finishes while the main thread is marked as
1420    // "busy with LLVM work", we can do a little switcheroo: We give the Token
1421    // of the just finished thread to the LLVM worker thread that is working on
1422    // behalf of the main thread's implicit Token, thus freeing up the main
1423    // thread again. The coordinator can then again decide what the main thread
1424    // should do. This allows the coordinator to make decisions at more points
1425    // in time.
1426    //
1427    // Striking a Balance between Throughput and Memory Consumption
1428    // ------------------------------------------------------------
1429    // Since our two goals, (1) use as many Tokens as possible and (2) keep
1430    // memory consumption as low as possible, are in conflict with each other,
1431    // we have to find a trade off between them. Right now, the goal is to keep
1432    // all workers busy, which means that no worker should find the queue empty
1433    // when it is ready to start.
1434    // How do we do achieve this? Good question :) We actually never know how
1435    // many `Tokens` are potentially available so it's hard to say how much to
1436    // fill up the queue before switching the main thread to LLVM work. Also we
1437    // currently don't have a means to estimate how long a running LLVM worker
1438    // will still be busy with it's current WorkItem. However, we know the
1439    // maximal count of available Tokens that makes sense (=the number of CPU
1440    // cores), so we can take a conservative guess. The heuristic we use here
1441    // is implemented in the `queue_full_enough()` function.
1442    //
1443    // Some Background on Jobservers
1444    // -----------------------------
1445    // It's worth also touching on the management of parallelism here. We don't
1446    // want to just spawn a thread per work item because while that's optimal
1447    // parallelism it may overload a system with too many threads or violate our
1448    // configuration for the maximum amount of cpu to use for this process. To
1449    // manage this we use the `jobserver` crate.
1450    //
1451    // Job servers are an artifact of GNU make and are used to manage
1452    // parallelism between processes. A jobserver is a glorified IPC semaphore
1453    // basically. Whenever we want to run some work we acquire the semaphore,
1454    // and whenever we're done with that work we release the semaphore. In this
1455    // manner we can ensure that the maximum number of parallel workers is
1456    // capped at any one point in time.
1457    //
1458    // LTO and the coordinator thread
1459    // ------------------------------
1460    //
1461    // The final job the coordinator thread is responsible for is managing LTO
1462    // and how that works. When LTO is requested what we'll do is collect all
1463    // optimized LLVM modules into a local vector on the coordinator. Once all
1464    // modules have been codegened and optimized we hand this to the `lto`
1465    // module for further optimization. The `lto` module will return back a list
1466    // of more modules to work on, which the coordinator will continue to spawn
1467    // work for.
1468    //
1469    // Each LLVM module is automatically sent back to the coordinator for LTO if
1470    // necessary. There's already optimizations in place to avoid sending work
1471    // back to the coordinator if LTO isn't requested.
1472    return B::spawn_named_thread(cgcx.time_trace, "coordinator".to_string(), move || {
1473        // This is where we collect codegen units that have gone all the way
1474        // through codegen and LLVM.
1475        let mut compiled_modules = ::alloc::vec::Vec::new()vec![];
1476        let mut needs_fat_lto = Vec::new();
1477        let mut needs_thin_lto = Vec::new();
1478        let mut lto_import_only_modules = Vec::new();
1479
1480        /// Possible state transitions:
1481        /// - Ongoing -> Completed
1482        /// - Ongoing -> Aborted
1483        /// - Completed -> Aborted
1484        #[derive(#[automatically_derived]
impl ::core::fmt::Debug for CodegenState {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                CodegenState::Ongoing => "Ongoing",
                CodegenState::Completed => "Completed",
                CodegenState::Aborted => "Aborted",
            })
    }
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for CodegenState {
    #[inline]
    fn eq(&self, other: &CodegenState) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq)]
1485        enum CodegenState {
1486            Ongoing,
1487            Completed,
1488            Aborted,
1489        }
1490        use CodegenState::*;
1491        let mut codegen_state = Ongoing;
1492
1493        // This is the queue of LLVM work items that still need processing.
1494        let mut work_items = Vec::<(WorkItem<B>, u64)>::new();
1495
1496        // This are the Jobserver Tokens we currently hold. Does not include
1497        // the implicit Token the compiler process owns no matter what.
1498        let mut tokens = Vec::new();
1499
1500        let mut main_thread_state = MainThreadState::Idle;
1501
1502        // How many LLVM worker threads are running while holding a Token. This
1503        // *excludes* any that the main thread is lending a Token to.
1504        let mut running_with_own_token = 0;
1505
1506        // How many LLVM worker threads are running in total. This *includes*
1507        // any that the main thread is lending a Token to.
1508        let running_with_any_token = |main_thread_state, running_with_own_token| {
1509            running_with_own_token
1510                + if main_thread_state == MainThreadState::Lending { 1 } else { 0 }
1511        };
1512
1513        let mut llvm_start_time: Option<VerboseTimingGuard<'_>> = None;
1514
1515        if let Some(allocator_module) = &mut allocator_module {
1516            B::optimize(&cgcx, &shared_emitter, allocator_module, &allocator_config);
1517        }
1518
1519        // Run the message loop while there's still anything that needs message
1520        // processing. Note that as soon as codegen is aborted we simply want to
1521        // wait for all existing work to finish, so many of the conditions here
1522        // only apply if codegen hasn't been aborted as they represent pending
1523        // work to be done.
1524        loop {
1525            // While there are still CGUs to be codegened, the coordinator has
1526            // to decide how to utilize the compiler processes implicit Token:
1527            // For codegenning more CGU or for running them through LLVM.
1528            if codegen_state == Ongoing {
1529                if main_thread_state == MainThreadState::Idle {
1530                    // Compute the number of workers that will be running once we've taken as many
1531                    // items from the work queue as we can, plus one for the main thread. It's not
1532                    // critically important that we use this instead of just
1533                    // `running_with_own_token`, but it prevents the `queue_full_enough` heuristic
1534                    // from fluctuating just because a worker finished up and we decreased the
1535                    // `running_with_own_token` count, even though we're just going to increase it
1536                    // right after this when we put a new worker to work.
1537                    let extra_tokens = tokens.len().checked_sub(running_with_own_token).unwrap();
1538                    let additional_running = std::cmp::min(extra_tokens, work_items.len());
1539                    let anticipated_running = running_with_own_token + additional_running + 1;
1540
1541                    if !queue_full_enough(work_items.len(), anticipated_running) {
1542                        // The queue is not full enough, process more codegen units:
1543                        if codegen_worker_send.send(CguMessage).is_err() {
1544                            {
    ::core::panicking::panic_fmt(format_args!("Could not send CguMessage to main thread"));
}panic!("Could not send CguMessage to main thread")
1545                        }
1546                        main_thread_state = MainThreadState::Codegenning;
1547                    } else {
1548                        // The queue is full enough to not let the worker
1549                        // threads starve. Use the implicit Token to do some
1550                        // LLVM work too.
1551                        let (item, _) =
1552                            work_items.pop().expect("queue empty - queue_full_enough() broken?");
1553                        main_thread_state = MainThreadState::Lending;
1554                        spawn_work(
1555                            &cgcx,
1556                            shared_emitter.clone(),
1557                            coordinator_send.clone(),
1558                            &mut llvm_start_time,
1559                            item,
1560                        );
1561                    }
1562                }
1563            } else if codegen_state == Completed {
1564                if running_with_any_token(main_thread_state, running_with_own_token) == 0
1565                    && work_items.is_empty()
1566                {
1567                    // All codegen work is done.
1568                    break;
1569                }
1570
1571                // In this branch, we know that everything has been codegened,
1572                // so it's just a matter of determining whether the implicit
1573                // Token is free to use for LLVM work.
1574                match main_thread_state {
1575                    MainThreadState::Idle => {
1576                        if let Some((item, _)) = work_items.pop() {
1577                            main_thread_state = MainThreadState::Lending;
1578                            spawn_work(
1579                                &cgcx,
1580                                shared_emitter.clone(),
1581                                coordinator_send.clone(),
1582                                &mut llvm_start_time,
1583                                item,
1584                            );
1585                        } else {
1586                            // There is no unstarted work, so let the main thread
1587                            // take over for a running worker. Otherwise the
1588                            // implicit token would just go to waste.
1589                            // We reduce the `running` counter by one. The
1590                            // `tokens.truncate()` below will take care of
1591                            // giving the Token back.
1592                            if !(running_with_own_token > 0) {
    ::core::panicking::panic("assertion failed: running_with_own_token > 0")
};assert!(running_with_own_token > 0);
1593                            running_with_own_token -= 1;
1594                            main_thread_state = MainThreadState::Lending;
1595                        }
1596                    }
1597                    MainThreadState::Codegenning => ::rustc_middle::util::bug::bug_fmt(format_args!("codegen worker should not be codegenning after codegen was already completed"))bug!(
1598                        "codegen worker should not be codegenning after \
1599                              codegen was already completed"
1600                    ),
1601                    MainThreadState::Lending => {
1602                        // Already making good use of that token
1603                    }
1604                }
1605            } else {
1606                // Don't queue up any more work if codegen was aborted, we're
1607                // just waiting for our existing children to finish.
1608                if !(codegen_state == Aborted) {
    ::core::panicking::panic("assertion failed: codegen_state == Aborted")
};assert!(codegen_state == Aborted);
1609                if running_with_any_token(main_thread_state, running_with_own_token) == 0 {
1610                    break;
1611                }
1612            }
1613
1614            // Spin up what work we can, only doing this while we've got available
1615            // parallelism slots and work left to spawn.
1616            if codegen_state != Aborted {
1617                while running_with_own_token < tokens.len()
1618                    && let Some((item, _)) = work_items.pop()
1619                {
1620                    spawn_work(
1621                        &cgcx,
1622                        shared_emitter.clone(),
1623                        coordinator_send.clone(),
1624                        &mut llvm_start_time,
1625                        item,
1626                    );
1627                    running_with_own_token += 1;
1628                }
1629            }
1630
1631            // Relinquish accidentally acquired extra tokens.
1632            tokens.truncate(running_with_own_token);
1633
1634            match coordinator_receive.recv().unwrap() {
1635                // Save the token locally and the next turn of the loop will use
1636                // this to spawn a new unit of work, or it may get dropped
1637                // immediately if we have no more work to spawn.
1638                Message::Token(token) => {
1639                    match token {
1640                        Ok(token) => {
1641                            tokens.push(token);
1642
1643                            if main_thread_state == MainThreadState::Lending {
1644                                // If the main thread token is used for LLVM work
1645                                // at the moment, we turn that thread into a regular
1646                                // LLVM worker thread, so the main thread is free
1647                                // to react to codegen demand.
1648                                main_thread_state = MainThreadState::Idle;
1649                                running_with_own_token += 1;
1650                            }
1651                        }
1652                        Err(e) => {
1653                            let msg = &::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("failed to acquire jobserver token: {0}",
                e))
    })format!("failed to acquire jobserver token: {e}");
1654                            shared_emitter.fatal(msg);
1655                            codegen_state = Aborted;
1656                        }
1657                    }
1658                }
1659
1660                Message::CodegenDone { llvm_work_item, cost } => {
1661                    // We keep the queue sorted by estimated processing cost,
1662                    // so that more expensive items are processed earlier. This
1663                    // is good for throughput as it gives the main thread more
1664                    // time to fill up the queue and it avoids scheduling
1665                    // expensive items to the end.
1666                    // Note, however, that this is not ideal for memory
1667                    // consumption, as LLVM module sizes are not evenly
1668                    // distributed.
1669                    let insertion_index = work_items.binary_search_by_key(&cost, |&(_, cost)| cost);
1670                    let insertion_index = match insertion_index {
1671                        Ok(idx) | Err(idx) => idx,
1672                    };
1673                    work_items.insert(insertion_index, (llvm_work_item, cost));
1674
1675                    if cgcx.parallel {
1676                        helper.request_token();
1677                    }
1678                    match (&main_thread_state, &MainThreadState::Codegenning) {
    (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!(main_thread_state, MainThreadState::Codegenning);
1679                    main_thread_state = MainThreadState::Idle;
1680                }
1681
1682                Message::CodegenComplete => {
1683                    if codegen_state != Aborted {
1684                        codegen_state = Completed;
1685                    }
1686                    match (&main_thread_state, &MainThreadState::Codegenning) {
    (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!(main_thread_state, MainThreadState::Codegenning);
1687                    main_thread_state = MainThreadState::Idle;
1688                }
1689
1690                // If codegen is aborted that means translation was aborted due
1691                // to some normal-ish compiler error. In this situation we want
1692                // to exit as soon as possible, but we want to make sure all
1693                // existing work has finished. Flag codegen as being done, and
1694                // then conditions above will ensure no more work is spawned but
1695                // we'll keep executing this loop until `running_with_own_token`
1696                // hits 0.
1697                Message::CodegenAborted => {
1698                    codegen_state = Aborted;
1699                }
1700
1701                Message::WorkItem { result } => {
1702                    // If a thread exits successfully then we drop a token associated
1703                    // with that worker and update our `running_with_own_token` count.
1704                    // We may later re-acquire a token to continue running more work.
1705                    // We may also not actually drop a token here if the worker was
1706                    // running with an "ephemeral token".
1707                    if main_thread_state == MainThreadState::Lending {
1708                        main_thread_state = MainThreadState::Idle;
1709                    } else {
1710                        running_with_own_token -= 1;
1711                    }
1712
1713                    match result {
1714                        Ok(WorkItemResult::Finished(compiled_module)) => {
1715                            compiled_modules.push(compiled_module);
1716                        }
1717                        Ok(WorkItemResult::NeedsFatLto(fat_lto_input)) => {
1718                            if !needs_thin_lto.is_empty() {
    ::core::panicking::panic("assertion failed: needs_thin_lto.is_empty()")
};assert!(needs_thin_lto.is_empty());
1719                            needs_fat_lto.push(fat_lto_input);
1720                        }
1721                        Ok(WorkItemResult::NeedsThinLto(name, thin_buffer)) => {
1722                            if !needs_fat_lto.is_empty() {
    ::core::panicking::panic("assertion failed: needs_fat_lto.is_empty()")
};assert!(needs_fat_lto.is_empty());
1723                            needs_thin_lto.push((name, thin_buffer));
1724                        }
1725                        Err(Some(WorkerFatalError)) => {
1726                            // Like `CodegenAborted`, wait for remaining work to finish.
1727                            codegen_state = Aborted;
1728                        }
1729                        Err(None) => {
1730                            // If the thread failed that means it panicked, so
1731                            // we abort immediately.
1732                            ::rustc_middle::util::bug::bug_fmt(format_args!("worker thread panicked"));bug!("worker thread panicked");
1733                        }
1734                    }
1735                }
1736
1737                Message::AddImportOnlyModule { module_data, work_product } => {
1738                    match (&codegen_state, &Ongoing) {
    (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!(codegen_state, Ongoing);
1739                    match (&main_thread_state, &MainThreadState::Codegenning) {
    (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!(main_thread_state, MainThreadState::Codegenning);
1740                    lto_import_only_modules.push((module_data, work_product));
1741                    main_thread_state = MainThreadState::Idle;
1742                }
1743            }
1744        }
1745
1746        // Drop to print timings
1747        drop(llvm_start_time);
1748
1749        if codegen_state == Aborted {
1750            return Err(());
1751        }
1752
1753        drop(codegen_state);
1754        drop(tokens);
1755        drop(helper);
1756        if !work_items.is_empty() {
    ::core::panicking::panic("assertion failed: work_items.is_empty()")
};assert!(work_items.is_empty());
1757
1758        if !needs_fat_lto.is_empty() {
1759            if !compiled_modules.is_empty() {
    ::core::panicking::panic("assertion failed: compiled_modules.is_empty()")
};assert!(compiled_modules.is_empty());
1760            if !needs_thin_lto.is_empty() {
    ::core::panicking::panic("assertion failed: needs_thin_lto.is_empty()")
};assert!(needs_thin_lto.is_empty());
1761
1762            if let Some(allocator_module) = allocator_module.take() {
1763                needs_fat_lto.push(FatLtoInput::InMemory(allocator_module));
1764            }
1765
1766            return Ok(MaybeLtoModules::FatLto {
1767                cgcx,
1768                exported_symbols_for_lto,
1769                each_linked_rlib_file_for_lto,
1770                needs_fat_lto,
1771                lto_import_only_modules,
1772            });
1773        } else if !needs_thin_lto.is_empty() || !lto_import_only_modules.is_empty() {
1774            if !compiled_modules.is_empty() {
    ::core::panicking::panic("assertion failed: compiled_modules.is_empty()")
};assert!(compiled_modules.is_empty());
1775            if !needs_fat_lto.is_empty() {
    ::core::panicking::panic("assertion failed: needs_fat_lto.is_empty()")
};assert!(needs_fat_lto.is_empty());
1776
1777            if cgcx.lto == Lto::ThinLocal {
1778                compiled_modules.extend(do_thin_lto(
1779                    &cgcx,
1780                    shared_emitter.clone(),
1781                    exported_symbols_for_lto,
1782                    each_linked_rlib_file_for_lto,
1783                    needs_thin_lto,
1784                    lto_import_only_modules,
1785                ));
1786            } else {
1787                if let Some(allocator_module) = allocator_module.take() {
1788                    let (name, thin_buffer) = B::prepare_thin(allocator_module);
1789                    needs_thin_lto.push((name, thin_buffer));
1790                }
1791
1792                return Ok(MaybeLtoModules::ThinLto {
1793                    cgcx,
1794                    exported_symbols_for_lto,
1795                    each_linked_rlib_file_for_lto,
1796                    needs_thin_lto,
1797                    lto_import_only_modules,
1798                });
1799            }
1800        }
1801
1802        Ok(MaybeLtoModules::NoLto {
1803            modules: compiled_modules,
1804            allocator_module: allocator_module.map(|allocator_module| {
1805                B::codegen(&cgcx, &shared_emitter, allocator_module, &allocator_config)
1806            }),
1807        })
1808    })
1809    .expect("failed to spawn coordinator thread");
1810
1811    // A heuristic that determines if we have enough LLVM WorkItems in the
1812    // queue so that the main thread can do LLVM work instead of codegen
1813    fn queue_full_enough(items_in_queue: usize, workers_running: usize) -> bool {
1814        // This heuristic scales ahead-of-time codegen according to available
1815        // concurrency, as measured by `workers_running`. The idea is that the
1816        // more concurrency we have available, the more demand there will be for
1817        // work items, and the fuller the queue should be kept to meet demand.
1818        // An important property of this approach is that we codegen ahead of
1819        // time only as much as necessary, so as to keep fewer LLVM modules in
1820        // memory at once, thereby reducing memory consumption.
1821        //
1822        // When the number of workers running is less than the max concurrency
1823        // available to us, this heuristic can cause us to instruct the main
1824        // thread to work on an LLVM item (that is, tell it to "LLVM") instead
1825        // of codegen, even though it seems like it *should* be codegenning so
1826        // that we can create more work items and spawn more LLVM workers.
1827        //
1828        // But this is not a problem. When the main thread is told to LLVM,
1829        // according to this heuristic and how work is scheduled, there is
1830        // always at least one item in the queue, and therefore at least one
1831        // pending jobserver token request. If there *is* more concurrency
1832        // available, we will immediately receive a token, which will upgrade
1833        // the main thread's LLVM worker to a real one (conceptually), and free
1834        // up the main thread to codegen if necessary. On the other hand, if
1835        // there isn't more concurrency, then the main thread working on an LLVM
1836        // item is appropriate, as long as the queue is full enough for demand.
1837        //
1838        // Speaking of which, how full should we keep the queue? Probably less
1839        // full than you'd think. A lot has to go wrong for the queue not to be
1840        // full enough and for that to have a negative effect on compile times.
1841        //
1842        // Workers are unlikely to finish at exactly the same time, so when one
1843        // finishes and takes another work item off the queue, we often have
1844        // ample time to codegen at that point before the next worker finishes.
1845        // But suppose that codegen takes so long that the workers exhaust the
1846        // queue, and we have one or more workers that have nothing to work on.
1847        // Well, it might not be so bad. Of all the LLVM modules we create and
1848        // optimize, one has to finish last. It's not necessarily the case that
1849        // by losing some concurrency for a moment, we delay the point at which
1850        // that last LLVM module is finished and the rest of compilation can
1851        // proceed. Also, when we can't take advantage of some concurrency, we
1852        // give tokens back to the job server. That enables some other rustc to
1853        // potentially make use of the available concurrency. That could even
1854        // *decrease* overall compile time if we're lucky. But yes, if no other
1855        // rustc can make use of the concurrency, then we've squandered it.
1856        //
1857        // However, keeping the queue full is also beneficial when we have a
1858        // surge in available concurrency. Then items can be taken from the
1859        // queue immediately, without having to wait for codegen.
1860        //
1861        // So, the heuristic below tries to keep one item in the queue for every
1862        // four running workers. Based on limited benchmarking, this appears to
1863        // be more than sufficient to avoid increasing compilation times.
1864        let quarter_of_workers = workers_running - 3 * workers_running / 4;
1865        items_in_queue > 0 && items_in_queue >= quarter_of_workers
1866    }
1867}
1868
1869/// `FatalError` is explicitly not `Send`.
1870#[must_use]
1871pub(crate) struct WorkerFatalError;
1872
1873fn spawn_work<'a, B: ExtraBackendMethods>(
1874    cgcx: &'a CodegenContext<B>,
1875    shared_emitter: SharedEmitter,
1876    coordinator_send: Sender<Message<B>>,
1877    llvm_start_time: &mut Option<VerboseTimingGuard<'a>>,
1878    work: WorkItem<B>,
1879) {
1880    if llvm_start_time.is_none() {
1881        *llvm_start_time = Some(cgcx.prof.verbose_generic_activity("LLVM_passes"));
1882    }
1883
1884    let cgcx = cgcx.clone();
1885
1886    B::spawn_named_thread(cgcx.time_trace, work.short_description(), move || {
1887        let result = std::panic::catch_unwind(AssertUnwindSafe(|| match work {
1888            WorkItem::Optimize(m) => execute_optimize_work_item(&cgcx, shared_emitter, m),
1889            WorkItem::CopyPostLtoArtifacts(m) => WorkItemResult::Finished(
1890                execute_copy_from_cache_work_item(&cgcx, shared_emitter, m),
1891            ),
1892        }));
1893
1894        let msg = match result {
1895            Ok(result) => Message::WorkItem::<B> { result: Ok(result) },
1896
1897            // We ignore any `FatalError` coming out of `execute_work_item`, as a
1898            // diagnostic was already sent off to the main thread - just surface
1899            // that there was an error in this worker.
1900            Err(err) if err.is::<FatalErrorMarker>() => {
1901                Message::WorkItem::<B> { result: Err(Some(WorkerFatalError)) }
1902            }
1903
1904            Err(_) => Message::WorkItem::<B> { result: Err(None) },
1905        };
1906        drop(coordinator_send.send(msg));
1907    })
1908    .expect("failed to spawn work thread");
1909}
1910
1911fn spawn_thin_lto_work<'a, B: ExtraBackendMethods>(
1912    cgcx: &'a CodegenContext<B>,
1913    shared_emitter: SharedEmitter,
1914    coordinator_send: Sender<ThinLtoMessage>,
1915    work: ThinLtoWorkItem<B>,
1916) {
1917    let cgcx = cgcx.clone();
1918
1919    B::spawn_named_thread(cgcx.time_trace, work.short_description(), move || {
1920        let result = std::panic::catch_unwind(AssertUnwindSafe(|| match work {
1921            ThinLtoWorkItem::CopyPostLtoArtifacts(m) => {
1922                execute_copy_from_cache_work_item(&cgcx, shared_emitter, m)
1923            }
1924            ThinLtoWorkItem::ThinLto(m) => execute_thin_lto_work_item(&cgcx, shared_emitter, m),
1925        }));
1926
1927        let msg = match result {
1928            Ok(result) => ThinLtoMessage::WorkItem { result: Ok(result) },
1929
1930            // We ignore any `FatalError` coming out of `execute_work_item`, as a
1931            // diagnostic was already sent off to the main thread - just surface
1932            // that there was an error in this worker.
1933            Err(err) if err.is::<FatalErrorMarker>() => {
1934                ThinLtoMessage::WorkItem { result: Err(Some(WorkerFatalError)) }
1935            }
1936
1937            Err(_) => ThinLtoMessage::WorkItem { result: Err(None) },
1938        };
1939        drop(coordinator_send.send(msg));
1940    })
1941    .expect("failed to spawn work thread");
1942}
1943
1944enum SharedEmitterMessage {
1945    Diagnostic(Diagnostic),
1946    InlineAsmError(InlineAsmError),
1947    Fatal(String),
1948}
1949
1950pub struct InlineAsmError {
1951    pub span: SpanData,
1952    pub msg: String,
1953    pub level: Level,
1954    pub source: Option<(String, Vec<InnerSpan>)>,
1955}
1956
1957#[derive(#[automatically_derived]
impl ::core::clone::Clone for SharedEmitter {
    #[inline]
    fn clone(&self) -> SharedEmitter {
        SharedEmitter { sender: ::core::clone::Clone::clone(&self.sender) }
    }
}Clone)]
1958pub struct SharedEmitter {
1959    sender: Sender<SharedEmitterMessage>,
1960}
1961
1962pub struct SharedEmitterMain {
1963    receiver: Receiver<SharedEmitterMessage>,
1964}
1965
1966impl SharedEmitter {
1967    fn new() -> (SharedEmitter, SharedEmitterMain) {
1968        let (sender, receiver) = channel();
1969
1970        (SharedEmitter { sender }, SharedEmitterMain { receiver })
1971    }
1972
1973    pub fn inline_asm_error(&self, err: InlineAsmError) {
1974        drop(self.sender.send(SharedEmitterMessage::InlineAsmError(err)));
1975    }
1976
1977    fn fatal(&self, msg: &str) {
1978        drop(self.sender.send(SharedEmitterMessage::Fatal(msg.to_string())));
1979    }
1980}
1981
1982impl Emitter for SharedEmitter {
1983    fn emit_diagnostic(
1984        &mut self,
1985        mut diag: rustc_errors::DiagInner,
1986        _registry: &rustc_errors::registry::Registry,
1987    ) {
1988        // Check that we aren't missing anything interesting when converting to
1989        // the cut-down local `DiagInner`.
1990        if !!diag.span.has_span_labels() {
    ::core::panicking::panic("assertion failed: !diag.span.has_span_labels()")
};assert!(!diag.span.has_span_labels());
1991        match (&diag.suggestions, &Suggestions::Enabled(::alloc::vec::Vec::new())) {
    (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!(diag.suggestions, Suggestions::Enabled(vec![]));
1992        match (&diag.sort_span, &rustc_span::DUMMY_SP) {
    (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!(diag.sort_span, rustc_span::DUMMY_SP);
1993        match (&diag.is_lint, &None) {
    (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!(diag.is_lint, None);
1994        // No sensible check for `diag.emitted_at`.
1995
1996        let args = mem::replace(&mut diag.args, DiagArgMap::default());
1997        drop(
1998            self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
1999                span: diag.span.primary_spans().iter().map(|span| span.data()).collect::<Vec<_>>(),
2000                level: diag.level(),
2001                messages: diag.messages,
2002                code: diag.code,
2003                children: diag
2004                    .children
2005                    .into_iter()
2006                    .map(|child| Subdiagnostic { level: child.level, messages: child.messages })
2007                    .collect(),
2008                args,
2009            })),
2010        );
2011    }
2012
2013    fn source_map(&self) -> Option<&SourceMap> {
2014        None
2015    }
2016
2017    fn translator(&self) -> &Translator {
2018        {
    ::core::panicking::panic_fmt(format_args!("shared emitter attempted to translate a diagnostic"));
};panic!("shared emitter attempted to translate a diagnostic");
2019    }
2020}
2021
2022impl SharedEmitterMain {
2023    fn check(&self, sess: &Session, blocking: bool) {
2024        loop {
2025            let message = if blocking {
2026                match self.receiver.recv() {
2027                    Ok(message) => Ok(message),
2028                    Err(_) => Err(()),
2029                }
2030            } else {
2031                match self.receiver.try_recv() {
2032                    Ok(message) => Ok(message),
2033                    Err(_) => Err(()),
2034                }
2035            };
2036
2037            match message {
2038                Ok(SharedEmitterMessage::Diagnostic(diag)) => {
2039                    // The diagnostic has been received on the main thread.
2040                    // Convert it back to a full `Diagnostic` and emit.
2041                    let dcx = sess.dcx();
2042                    let mut d =
2043                        rustc_errors::DiagInner::new_with_messages(diag.level, diag.messages);
2044                    d.span = MultiSpan::from_spans(
2045                        diag.span.into_iter().map(|span| span.span()).collect(),
2046                    );
2047                    d.code = diag.code; // may be `None`, that's ok
2048                    d.children = diag
2049                        .children
2050                        .into_iter()
2051                        .map(|sub| rustc_errors::Subdiag {
2052                            level: sub.level,
2053                            messages: sub.messages,
2054                            span: MultiSpan::new(),
2055                        })
2056                        .collect();
2057                    d.args = diag.args;
2058                    dcx.emit_diagnostic(d);
2059                    sess.dcx().abort_if_errors();
2060                }
2061                Ok(SharedEmitterMessage::InlineAsmError(inner)) => {
2062                    match inner.level {
    Level::Error | Level::Warning | Level::Note => {}
    ref left_val => {
        ::core::panicking::assert_matches_failed(left_val,
            "Level::Error | Level::Warning | Level::Note",
            ::core::option::Option::None);
    }
};assert_matches!(inner.level, Level::Error | Level::Warning | Level::Note);
2063                    let mut err = Diag::<()>::new(sess.dcx(), inner.level, inner.msg);
2064                    if !inner.span.is_dummy() {
2065                        err.span(inner.span.span());
2066                    }
2067
2068                    // Point to the generated assembly if it is available.
2069                    if let Some((buffer, spans)) = inner.source {
2070                        let source = sess
2071                            .source_map()
2072                            .new_source_file(FileName::inline_asm_source_code(&buffer), buffer);
2073                        let spans: Vec<_> = spans
2074                            .iter()
2075                            .map(|sp| {
2076                                Span::with_root_ctxt(
2077                                    source.normalized_byte_pos(sp.start as u32),
2078                                    source.normalized_byte_pos(sp.end as u32),
2079                                )
2080                            })
2081                            .collect();
2082                        err.span_note(spans, "instantiated into assembly here");
2083                    }
2084
2085                    err.emit();
2086                }
2087                Ok(SharedEmitterMessage::Fatal(msg)) => {
2088                    sess.dcx().fatal(msg);
2089                }
2090                Err(_) => {
2091                    break;
2092                }
2093            }
2094        }
2095    }
2096}
2097
2098pub struct Coordinator<B: ExtraBackendMethods> {
2099    sender: Sender<Message<B>>,
2100    future: Option<thread::JoinHandle<Result<MaybeLtoModules<B>, ()>>>,
2101    // Only used for the Message type.
2102    phantom: PhantomData<B>,
2103}
2104
2105impl<B: ExtraBackendMethods> Coordinator<B> {
2106    fn join(mut self) -> std::thread::Result<Result<MaybeLtoModules<B>, ()>> {
2107        self.future.take().unwrap().join()
2108    }
2109}
2110
2111impl<B: ExtraBackendMethods> Drop for Coordinator<B> {
2112    fn drop(&mut self) {
2113        if let Some(future) = self.future.take() {
2114            // If we haven't joined yet, signal to the coordinator that it should spawn no more
2115            // work, and wait for worker threads to finish.
2116            drop(self.sender.send(Message::CodegenAborted::<B>));
2117            drop(future.join());
2118        }
2119    }
2120}
2121
2122pub struct OngoingCodegen<B: ExtraBackendMethods> {
2123    pub backend: B,
2124    pub crate_info: CrateInfo,
2125    pub output_filenames: Arc<OutputFilenames>,
2126    // Field order below is intended to terminate the coordinator thread before two fields below
2127    // drop and prematurely close channels used by coordinator thread. See `Coordinator`'s
2128    // `Drop` implementation for more info.
2129    pub coordinator: Coordinator<B>,
2130    pub codegen_worker_receive: Receiver<CguMessage>,
2131    pub shared_emitter_main: SharedEmitterMain,
2132}
2133
2134impl<B: ExtraBackendMethods> OngoingCodegen<B> {
2135    pub fn join(self, sess: &Session) -> (CodegenResults, FxIndexMap<WorkProductId, WorkProduct>) {
2136        self.shared_emitter_main.check(sess, true);
2137
2138        let maybe_lto_modules = sess.time("join_worker_thread", || match self.coordinator.join() {
2139            Ok(Ok(maybe_lto_modules)) => maybe_lto_modules,
2140            Ok(Err(())) => {
2141                sess.dcx().abort_if_errors();
2142                {
    ::core::panicking::panic_fmt(format_args!("expected abort due to worker thread errors"));
}panic!("expected abort due to worker thread errors")
2143            }
2144            Err(_) => {
2145                ::rustc_middle::util::bug::bug_fmt(format_args!("panic during codegen/LLVM phase"));bug!("panic during codegen/LLVM phase");
2146            }
2147        });
2148
2149        sess.dcx().abort_if_errors();
2150
2151        let (shared_emitter, shared_emitter_main) = SharedEmitter::new();
2152
2153        // Catch fatal errors to ensure shared_emitter_main.check() can emit the actual diagnostics
2154        let compiled_modules = catch_fatal_errors(|| match maybe_lto_modules {
2155            MaybeLtoModules::NoLto { modules, allocator_module } => {
2156                drop(shared_emitter);
2157                CompiledModules { modules, allocator_module }
2158            }
2159            MaybeLtoModules::FatLto {
2160                cgcx,
2161                exported_symbols_for_lto,
2162                each_linked_rlib_file_for_lto,
2163                needs_fat_lto,
2164                lto_import_only_modules,
2165            } => CompiledModules {
2166                modules: <[_]>::into_vec(::alloc::boxed::box_new([do_fat_lto(&cgcx, shared_emitter,
                    &exported_symbols_for_lto, &each_linked_rlib_file_for_lto,
                    needs_fat_lto, lto_import_only_modules)]))vec![do_fat_lto(
2167                    &cgcx,
2168                    shared_emitter,
2169                    &exported_symbols_for_lto,
2170                    &each_linked_rlib_file_for_lto,
2171                    needs_fat_lto,
2172                    lto_import_only_modules,
2173                )],
2174                allocator_module: None,
2175            },
2176            MaybeLtoModules::ThinLto {
2177                cgcx,
2178                exported_symbols_for_lto,
2179                each_linked_rlib_file_for_lto,
2180                needs_thin_lto,
2181                lto_import_only_modules,
2182            } => CompiledModules {
2183                modules: do_thin_lto(
2184                    &cgcx,
2185                    shared_emitter,
2186                    exported_symbols_for_lto,
2187                    each_linked_rlib_file_for_lto,
2188                    needs_thin_lto,
2189                    lto_import_only_modules,
2190                ),
2191                allocator_module: None,
2192            },
2193        });
2194
2195        shared_emitter_main.check(sess, true);
2196
2197        sess.dcx().abort_if_errors();
2198
2199        let mut compiled_modules =
2200            compiled_modules.expect("fatal error emitted but not sent to SharedEmitter");
2201
2202        // Regardless of what order these modules completed in, report them to
2203        // the backend in the same order every time to ensure that we're handing
2204        // out deterministic results.
2205        compiled_modules.modules.sort_by(|a, b| a.name.cmp(&b.name));
2206
2207        let work_products =
2208            copy_all_cgu_workproducts_to_incr_comp_cache_dir(sess, &compiled_modules);
2209        produce_final_output_artifacts(sess, &compiled_modules, &self.output_filenames);
2210
2211        // FIXME: time_llvm_passes support - does this use a global context or
2212        // something?
2213        if sess.codegen_units().as_usize() == 1 && sess.opts.unstable_opts.time_llvm_passes {
2214            self.backend.print_pass_timings()
2215        }
2216
2217        if sess.print_llvm_stats() {
2218            self.backend.print_statistics()
2219        }
2220
2221        (
2222            CodegenResults {
2223                crate_info: self.crate_info,
2224
2225                modules: compiled_modules.modules,
2226                allocator_module: compiled_modules.allocator_module,
2227            },
2228            work_products,
2229        )
2230    }
2231
2232    pub(crate) fn codegen_finished(&self, tcx: TyCtxt<'_>) {
2233        self.wait_for_signal_to_codegen_item();
2234        self.check_for_errors(tcx.sess);
2235        drop(self.coordinator.sender.send(Message::CodegenComplete::<B>));
2236    }
2237
2238    pub(crate) fn check_for_errors(&self, sess: &Session) {
2239        self.shared_emitter_main.check(sess, false);
2240    }
2241
2242    pub(crate) fn wait_for_signal_to_codegen_item(&self) {
2243        match self.codegen_worker_receive.recv() {
2244            Ok(CguMessage) => {
2245                // Ok to proceed.
2246            }
2247            Err(_) => {
2248                // One of the LLVM threads must have panicked, fall through so
2249                // error handling can be reached.
2250            }
2251        }
2252    }
2253}
2254
2255pub(crate) fn submit_codegened_module_to_llvm<B: ExtraBackendMethods>(
2256    coordinator: &Coordinator<B>,
2257    module: ModuleCodegen<B::Module>,
2258    cost: u64,
2259) {
2260    let llvm_work_item = WorkItem::Optimize(module);
2261    drop(coordinator.sender.send(Message::CodegenDone::<B> { llvm_work_item, cost }));
2262}
2263
2264pub(crate) fn submit_post_lto_module_to_llvm<B: ExtraBackendMethods>(
2265    coordinator: &Coordinator<B>,
2266    module: CachedModuleCodegen,
2267) {
2268    let llvm_work_item = WorkItem::CopyPostLtoArtifacts(module);
2269    drop(coordinator.sender.send(Message::CodegenDone::<B> { llvm_work_item, cost: 0 }));
2270}
2271
2272pub(crate) fn submit_pre_lto_module_to_llvm<B: ExtraBackendMethods>(
2273    tcx: TyCtxt<'_>,
2274    coordinator: &Coordinator<B>,
2275    module: CachedModuleCodegen,
2276) {
2277    let filename = pre_lto_bitcode_filename(&module.name);
2278    let bc_path = in_incr_comp_dir_sess(tcx.sess, &filename);
2279    let file = fs::File::open(&bc_path)
2280        .unwrap_or_else(|e| {
    ::core::panicking::panic_fmt(format_args!("failed to open bitcode file `{0}`: {1}",
            bc_path.display(), e));
}panic!("failed to open bitcode file `{}`: {}", bc_path.display(), e));
2281
2282    let mmap = unsafe {
2283        Mmap::map(file).unwrap_or_else(|e| {
2284            {
    ::core::panicking::panic_fmt(format_args!("failed to mmap bitcode file `{0}`: {1}",
            bc_path.display(), e));
}panic!("failed to mmap bitcode file `{}`: {}", bc_path.display(), e)
2285        })
2286    };
2287    // Schedule the module to be loaded
2288    drop(coordinator.sender.send(Message::AddImportOnlyModule::<B> {
2289        module_data: SerializedModule::FromUncompressedFile(mmap),
2290        work_product: module.source,
2291    }));
2292}
2293
2294fn pre_lto_bitcode_filename(module_name: &str) -> String {
2295    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}.{1}", module_name,
                PRE_LTO_BC_EXT))
    })format!("{module_name}.{PRE_LTO_BC_EXT}")
2296}
2297
2298fn msvc_imps_needed(tcx: TyCtxt<'_>) -> bool {
2299    // This should never be true (because it's not supported). If it is true,
2300    // something is wrong with commandline arg validation.
2301    if !!(tcx.sess.opts.cg.linker_plugin_lto.enabled() &&
                        tcx.sess.target.is_like_windows &&
                    tcx.sess.opts.cg.prefer_dynamic) {
    ::core::panicking::panic("assertion failed: !(tcx.sess.opts.cg.linker_plugin_lto.enabled() &&\n                tcx.sess.target.is_like_windows &&\n            tcx.sess.opts.cg.prefer_dynamic)")
};assert!(
2302        !(tcx.sess.opts.cg.linker_plugin_lto.enabled()
2303            && tcx.sess.target.is_like_windows
2304            && tcx.sess.opts.cg.prefer_dynamic)
2305    );
2306
2307    // We need to generate _imp__ symbol if we are generating an rlib or we include one
2308    // indirectly from ThinLTO. In theory these are not needed as ThinLTO could resolve
2309    // these, but it currently does not do so.
2310    let can_have_static_objects =
2311        tcx.sess.lto() == Lto::Thin || tcx.crate_types().contains(&CrateType::Rlib);
2312
2313    tcx.sess.target.is_like_windows &&
2314    can_have_static_objects   &&
2315    // ThinLTO can't handle this workaround in all cases, so we don't
2316    // emit the `__imp_` symbols. Instead we make them unnecessary by disallowing
2317    // dynamic linking when linker plugin LTO is enabled.
2318    !tcx.sess.opts.cg.linker_plugin_lto.enabled()
2319}