rustc_codegen_ssa/back/
write.rs

1use std::assert_matches::assert_matches;
2use std::marker::PhantomData;
3use std::panic::AssertUnwindSafe;
4use std::path::{Path, PathBuf};
5use std::sync::Arc;
6use std::sync::mpsc::{Receiver, Sender, channel};
7use std::{fs, io, mem, str, thread};
8
9use rustc_abi::Size;
10use rustc_ast::attr;
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, DiagMessage, ErrCode, FatalErrorMarker, Level, MultiSpan, Style,
19    Suggestions,
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(Clone, Copy, 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(Clone, Copy, 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_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_regular!(sess.opts.cg.passes.clone(), vec![]),
167
168            opt_level: opt_level_and_size,
169
170            pgo_gen: if_regular!(
171                sess.opts.cg.profile_generate.clone(),
172                SwitchWithOptPath::Disabled
173            ),
174            pgo_use: if_regular!(sess.opts.cg.profile_use.clone(), None),
175            pgo_sample_use: 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_regular!(sess.instrument_coverage(), false),
178
179            sanitizer: if_regular!(sess.opts.unstable_opts.sanitizer, SanitizerSet::empty()),
180            sanitizer_dataflow_abilist: if_regular!(
181                sess.opts.unstable_opts.sanitizer_dataflow_abilist.clone(),
182                Vec::new()
183            ),
184            sanitizer_recover: if_regular!(
185                sess.opts.unstable_opts.sanitizer_recover,
186                SanitizerSet::empty()
187            ),
188            sanitizer_memory_track_origins: if_regular!(
189                sess.opts.unstable_opts.sanitizer_memory_track_origins,
190                0
191            ),
192
193            emit_pre_lto_bc: if_regular!(
194                save_temps || need_pre_lto_bitcode_for_incr_comp(sess),
195                false
196            ),
197            emit_no_opt_bc: if_regular!(save_temps, false),
198            emit_bc: if_regular!(
199                save_temps || sess.opts.output_types.contains_key(&OutputType::Bitcode),
200                save_temps
201            ),
202            emit_ir: if_regular!(
203                sess.opts.output_types.contains_key(&OutputType::LlvmAssembly),
204                false
205            ),
206            emit_asm: 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_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_regular!(sess.opts.unstable_opts.llvm_plugins.clone(), vec![]),
259            autodiff: if_regular!(sess.opts.unstable_opts.autodiff.clone(), vec![]),
260            offload: 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(Clone)]
325pub struct CodegenContext<B: WriteBackendMethods> {
326    // Resources needed when running LTO
327    pub prof: SelfProfilerRef,
328    pub lto: Lto,
329    pub save_temps: bool,
330    pub fewer_names: bool,
331    pub time_trace: bool,
332    pub opts: Arc<config::Options>,
333    pub crate_types: Vec<CrateType>,
334    pub output_filenames: Arc<OutputFilenames>,
335    pub invocation_temp: Option<String>,
336    pub regular_module_config: Arc<ModuleConfig>,
337    pub allocator_module_config: Arc<ModuleConfig>,
338    pub tm_factory: TargetMachineFactoryFn<B>,
339    pub msvc_imps_needed: bool,
340    pub is_pe_coff: bool,
341    pub target_can_use_split_dwarf: bool,
342    pub target_arch: String,
343    pub target_is_like_darwin: bool,
344    pub target_is_like_aix: bool,
345    pub split_debuginfo: rustc_target::spec::SplitDebuginfo,
346    pub split_dwarf_kind: rustc_session::config::SplitDwarfKind,
347    pub pointer_size: Size,
348
349    /// All commandline args used to invoke the compiler, with @file args fully expanded.
350    /// This will only be used within debug info, e.g. in the pdb file on windows
351    /// This is mainly useful for other tools that reads that debuginfo to figure out
352    /// how to call the compiler with the same arguments.
353    pub expanded_args: Vec<String>,
354
355    /// Emitter to use for diagnostics produced during codegen.
356    pub diag_emitter: SharedEmitter,
357    /// LLVM optimizations for which we want to print remarks.
358    pub remark: Passes,
359    /// Directory into which should the LLVM optimization remarks be written.
360    /// If `None`, they will be written to stderr.
361    pub remark_dir: Option<PathBuf>,
362    /// The incremental compilation session directory, or None if we are not
363    /// compiling incrementally
364    pub incr_comp_session_dir: Option<PathBuf>,
365    /// `true` if the codegen should be run in parallel.
366    ///
367    /// Depends on [`ExtraBackendMethods::supports_parallel()`] and `-Zno_parallel_backend`.
368    pub parallel: bool,
369}
370
371impl<B: WriteBackendMethods> CodegenContext<B> {
372    pub fn create_dcx(&self) -> DiagCtxt {
373        DiagCtxt::new(Box::new(self.diag_emitter.clone()))
374    }
375
376    pub fn config(&self, kind: ModuleKind) -> &ModuleConfig {
377        match kind {
378            ModuleKind::Regular => &self.regular_module_config,
379            ModuleKind::Allocator => &self.allocator_module_config,
380        }
381    }
382}
383
384fn generate_thin_lto_work<B: ExtraBackendMethods>(
385    cgcx: &CodegenContext<B>,
386    exported_symbols_for_lto: &[String],
387    each_linked_rlib_for_lto: &[PathBuf],
388    needs_thin_lto: Vec<(String, B::ThinBuffer)>,
389    import_only_modules: Vec<(SerializedModule<B::ModuleBuffer>, WorkProduct)>,
390) -> Vec<(WorkItem<B>, u64)> {
391    let _prof_timer = cgcx.prof.generic_activity("codegen_thin_generate_lto_work");
392
393    let (lto_modules, copy_jobs) = B::run_thin_lto(
394        cgcx,
395        exported_symbols_for_lto,
396        each_linked_rlib_for_lto,
397        needs_thin_lto,
398        import_only_modules,
399    );
400    lto_modules
401        .into_iter()
402        .map(|module| {
403            let cost = module.cost();
404            (WorkItem::ThinLto(module), cost)
405        })
406        .chain(copy_jobs.into_iter().map(|wp| {
407            (
408                WorkItem::CopyPostLtoArtifacts(CachedModuleCodegen {
409                    name: wp.cgu_name.clone(),
410                    source: wp,
411                }),
412                0, // copying is very cheap
413            )
414        }))
415        .collect()
416}
417
418struct CompiledModules {
419    modules: Vec<CompiledModule>,
420    allocator_module: Option<CompiledModule>,
421}
422
423fn need_bitcode_in_object(tcx: TyCtxt<'_>) -> bool {
424    let sess = tcx.sess;
425    sess.opts.cg.embed_bitcode
426        && tcx.crate_types().contains(&CrateType::Rlib)
427        && sess.opts.output_types.contains_key(&OutputType::Exe)
428}
429
430fn need_pre_lto_bitcode_for_incr_comp(sess: &Session) -> bool {
431    if sess.opts.incremental.is_none() {
432        return false;
433    }
434
435    match sess.lto() {
436        Lto::No => false,
437        Lto::Fat | Lto::Thin | Lto::ThinLocal => true,
438    }
439}
440
441pub(crate) fn start_async_codegen<B: ExtraBackendMethods>(
442    backend: B,
443    tcx: TyCtxt<'_>,
444    target_cpu: String,
445) -> OngoingCodegen<B> {
446    let (coordinator_send, coordinator_receive) = channel();
447
448    let crate_attrs = tcx.hir_attrs(rustc_hir::CRATE_HIR_ID);
449    let no_builtins = attr::contains_name(crate_attrs, sym::no_builtins);
450
451    let crate_info = CrateInfo::new(tcx, target_cpu);
452
453    let regular_config = ModuleConfig::new(ModuleKind::Regular, tcx, no_builtins);
454    let allocator_config = ModuleConfig::new(ModuleKind::Allocator, tcx, no_builtins);
455
456    let (shared_emitter, shared_emitter_main) = SharedEmitter::new();
457    let (codegen_worker_send, codegen_worker_receive) = channel();
458
459    let coordinator_thread = start_executing_work(
460        backend.clone(),
461        tcx,
462        &crate_info,
463        shared_emitter,
464        codegen_worker_send,
465        coordinator_receive,
466        Arc::new(regular_config),
467        Arc::new(allocator_config),
468        coordinator_send.clone(),
469    );
470
471    OngoingCodegen {
472        backend,
473        crate_info,
474
475        codegen_worker_receive,
476        shared_emitter_main,
477        coordinator: Coordinator {
478            sender: coordinator_send,
479            future: Some(coordinator_thread),
480            phantom: PhantomData,
481        },
482        output_filenames: Arc::clone(tcx.output_filenames(())),
483    }
484}
485
486fn copy_all_cgu_workproducts_to_incr_comp_cache_dir(
487    sess: &Session,
488    compiled_modules: &CompiledModules,
489) -> FxIndexMap<WorkProductId, WorkProduct> {
490    let mut work_products = FxIndexMap::default();
491
492    if sess.opts.incremental.is_none() {
493        return work_products;
494    }
495
496    let _timer = sess.timer("copy_all_cgu_workproducts_to_incr_comp_cache_dir");
497
498    for module in compiled_modules.modules.iter().filter(|m| m.kind == ModuleKind::Regular) {
499        let mut files = Vec::new();
500        if let Some(object_file_path) = &module.object {
501            files.push((OutputType::Object.extension(), object_file_path.as_path()));
502        }
503        if let Some(dwarf_object_file_path) = &module.dwarf_object {
504            files.push(("dwo", dwarf_object_file_path.as_path()));
505        }
506        if let Some(path) = &module.assembly {
507            files.push((OutputType::Assembly.extension(), path.as_path()));
508        }
509        if let Some(path) = &module.llvm_ir {
510            files.push((OutputType::LlvmAssembly.extension(), path.as_path()));
511        }
512        if let Some(path) = &module.bytecode {
513            files.push((OutputType::Bitcode.extension(), path.as_path()));
514        }
515        if let Some((id, product)) = copy_cgu_workproduct_to_incr_comp_cache_dir(
516            sess,
517            &module.name,
518            files.as_slice(),
519            &module.links_from_incr_cache,
520        ) {
521            work_products.insert(id, product);
522        }
523    }
524
525    work_products
526}
527
528fn produce_final_output_artifacts(
529    sess: &Session,
530    compiled_modules: &CompiledModules,
531    crate_output: &OutputFilenames,
532) {
533    let mut user_wants_bitcode = false;
534    let mut user_wants_objects = false;
535
536    // Produce final compile outputs.
537    let copy_gracefully = |from: &Path, to: &OutFileName| match to {
538        OutFileName::Stdout if let Err(e) = copy_to_stdout(from) => {
539            sess.dcx().emit_err(errors::CopyPath::new(from, to.as_path(), e));
540        }
541        OutFileName::Real(path) if let Err(e) = fs::copy(from, path) => {
542            sess.dcx().emit_err(errors::CopyPath::new(from, path, e));
543        }
544        _ => {}
545    };
546
547    let copy_if_one_unit = |output_type: OutputType, keep_numbered: bool| {
548        if let [module] = &compiled_modules.modules[..] {
549            // 1) Only one codegen unit. In this case it's no difficulty
550            //    to copy `foo.0.x` to `foo.x`.
551            let path = crate_output.temp_path_for_cgu(
552                output_type,
553                &module.name,
554                sess.invocation_temp.as_deref(),
555            );
556            let output = crate_output.path(output_type);
557            if !output_type.is_text_output() && output.is_tty() {
558                sess.dcx()
559                    .emit_err(errors::BinaryOutputToTty { shorthand: output_type.shorthand() });
560            } else {
561                copy_gracefully(&path, &output);
562            }
563            if !sess.opts.cg.save_temps && !keep_numbered {
564                // The user just wants `foo.x`, not `foo.#module-name#.x`.
565                ensure_removed(sess.dcx(), &path);
566            }
567        } else {
568            if crate_output.outputs.contains_explicit_name(&output_type) {
569                // 2) Multiple codegen units, with `--emit foo=some_name`. We have
570                //    no good solution for this case, so warn the user.
571                sess.dcx()
572                    .emit_warn(errors::IgnoringEmitPath { extension: output_type.extension() });
573            } else if crate_output.single_output_file.is_some() {
574                // 3) Multiple codegen units, with `-o some_name`. We have
575                //    no good solution for this case, so warn the user.
576                sess.dcx().emit_warn(errors::IgnoringOutput { extension: output_type.extension() });
577            } else {
578                // 4) Multiple codegen units, but no explicit name. We
579                //    just leave the `foo.0.x` files in place.
580                // (We don't have to do any work in this case.)
581            }
582        }
583    };
584
585    // Flag to indicate whether the user explicitly requested bitcode.
586    // Otherwise, we produced it only as a temporary output, and will need
587    // to get rid of it.
588    for output_type in crate_output.outputs.keys() {
589        match *output_type {
590            OutputType::Bitcode => {
591                user_wants_bitcode = true;
592                // Copy to .bc, but always keep the .0.bc. There is a later
593                // check to figure out if we should delete .0.bc files, or keep
594                // them for making an rlib.
595                copy_if_one_unit(OutputType::Bitcode, true);
596            }
597            OutputType::ThinLinkBitcode => {
598                copy_if_one_unit(OutputType::ThinLinkBitcode, false);
599            }
600            OutputType::LlvmAssembly => {
601                copy_if_one_unit(OutputType::LlvmAssembly, false);
602            }
603            OutputType::Assembly => {
604                copy_if_one_unit(OutputType::Assembly, false);
605            }
606            OutputType::Object => {
607                user_wants_objects = true;
608                copy_if_one_unit(OutputType::Object, true);
609            }
610            OutputType::Mir | OutputType::Metadata | OutputType::Exe | OutputType::DepInfo => {}
611        }
612    }
613
614    // Clean up unwanted temporary files.
615
616    // We create the following files by default:
617    //  - #crate#.#module-name#.bc
618    //  - #crate#.#module-name#.o
619    //  - #crate#.crate.metadata.bc
620    //  - #crate#.crate.metadata.o
621    //  - #crate#.o (linked from crate.##.o)
622    //  - #crate#.bc (copied from crate.##.bc)
623    // We may create additional files if requested by the user (through
624    // `-C save-temps` or `--emit=` flags).
625
626    if !sess.opts.cg.save_temps {
627        // Remove the temporary .#module-name#.o objects. If the user didn't
628        // explicitly request bitcode (with --emit=bc), and the bitcode is not
629        // needed for building an rlib, then we must remove .#module-name#.bc as
630        // well.
631
632        // Specific rules for keeping .#module-name#.bc:
633        //  - If the user requested bitcode (`user_wants_bitcode`), and
634        //    codegen_units > 1, then keep it.
635        //  - If the user requested bitcode but codegen_units == 1, then we
636        //    can toss .#module-name#.bc because we copied it to .bc earlier.
637        //  - If we're not building an rlib and the user didn't request
638        //    bitcode, then delete .#module-name#.bc.
639        // If you change how this works, also update back::link::link_rlib,
640        // where .#module-name#.bc files are (maybe) deleted after making an
641        // rlib.
642        let needs_crate_object = crate_output.outputs.contains_key(&OutputType::Exe);
643
644        let keep_numbered_bitcode = user_wants_bitcode && sess.codegen_units().as_usize() > 1;
645
646        let keep_numbered_objects =
647            needs_crate_object || (user_wants_objects && sess.codegen_units().as_usize() > 1);
648
649        for module in compiled_modules.modules.iter() {
650            if !keep_numbered_objects {
651                if let Some(ref path) = module.object {
652                    ensure_removed(sess.dcx(), path);
653                }
654
655                if let Some(ref path) = module.dwarf_object {
656                    ensure_removed(sess.dcx(), path);
657                }
658            }
659
660            if let Some(ref path) = module.bytecode {
661                if !keep_numbered_bitcode {
662                    ensure_removed(sess.dcx(), path);
663                }
664            }
665        }
666
667        if !user_wants_bitcode
668            && let Some(ref allocator_module) = compiled_modules.allocator_module
669            && let Some(ref path) = allocator_module.bytecode
670        {
671            ensure_removed(sess.dcx(), path);
672        }
673    }
674
675    if sess.opts.json_artifact_notifications {
676        if let [module] = &compiled_modules.modules[..] {
677            module.for_each_output(|_path, ty| {
678                if sess.opts.output_types.contains_key(&ty) {
679                    let descr = ty.shorthand();
680                    // for single cgu file is renamed to drop cgu specific suffix
681                    // so we regenerate it the same way
682                    let path = crate_output.path(ty);
683                    sess.dcx().emit_artifact_notification(path.as_path(), descr);
684                }
685            });
686        } else {
687            for module in &compiled_modules.modules {
688                module.for_each_output(|path, ty| {
689                    if sess.opts.output_types.contains_key(&ty) {
690                        let descr = ty.shorthand();
691                        sess.dcx().emit_artifact_notification(&path, descr);
692                    }
693                });
694            }
695        }
696    }
697
698    // We leave the following files around by default:
699    //  - #crate#.o
700    //  - #crate#.crate.metadata.o
701    //  - #crate#.bc
702    // These are used in linking steps and will be cleaned up afterward.
703}
704
705pub(crate) enum WorkItem<B: WriteBackendMethods> {
706    /// Optimize a newly codegened, totally unoptimized module.
707    Optimize(ModuleCodegen<B::Module>),
708    /// Copy the post-LTO artifacts from the incremental cache to the output
709    /// directory.
710    CopyPostLtoArtifacts(CachedModuleCodegen),
711    /// Performs fat LTO on the given module.
712    FatLto {
713        exported_symbols_for_lto: Arc<Vec<String>>,
714        each_linked_rlib_for_lto: Vec<PathBuf>,
715        needs_fat_lto: Vec<FatLtoInput<B>>,
716        import_only_modules: Vec<(SerializedModule<B::ModuleBuffer>, WorkProduct)>,
717    },
718    /// Performs thin-LTO on the given module.
719    ThinLto(lto::ThinModule<B>),
720}
721
722impl<B: WriteBackendMethods> WorkItem<B> {
723    fn module_kind(&self) -> ModuleKind {
724        match *self {
725            WorkItem::Optimize(ref m) => m.kind,
726            WorkItem::CopyPostLtoArtifacts(_) | WorkItem::FatLto { .. } | WorkItem::ThinLto(_) => {
727                ModuleKind::Regular
728            }
729        }
730    }
731
732    /// Generate a short description of this work item suitable for use as a thread name.
733    fn short_description(&self) -> String {
734        // `pthread_setname()` on *nix ignores anything beyond the first 15
735        // bytes. Use short descriptions to maximize the space available for
736        // the module name.
737        #[cfg(not(windows))]
738        fn desc(short: &str, _long: &str, name: &str) -> String {
739            // The short label is three bytes, and is followed by a space. That
740            // leaves 11 bytes for the CGU name. How we obtain those 11 bytes
741            // depends on the CGU name form.
742            //
743            // - Non-incremental, e.g. `regex.f10ba03eb5ec7975-cgu.0`: the part
744            //   before the `-cgu.0` is the same for every CGU, so use the
745            //   `cgu.0` part. The number suffix will be different for each
746            //   CGU.
747            //
748            // - Incremental (normal), e.g. `2i52vvl2hco29us0`: use the whole
749            //   name because each CGU will have a unique ASCII hash, and the
750            //   first 11 bytes will be enough to identify it.
751            //
752            // - Incremental (with `-Zhuman-readable-cgu-names`), e.g.
753            //   `regex.f10ba03eb5ec7975-re_builder.volatile`: use the whole
754            //   name. The first 11 bytes won't be enough to uniquely identify
755            //   it, but no obvious substring will, and this is a rarely used
756            //   option so it doesn't matter much.
757            //
758            assert_eq!(short.len(), 3);
759            let name = if let Some(index) = name.find("-cgu.") {
760                &name[index + 1..] // +1 skips the leading '-'.
761            } else {
762                name
763            };
764            format!("{short} {name}")
765        }
766
767        // Windows has no thread name length limit, so use more descriptive names.
768        #[cfg(windows)]
769        fn desc(_short: &str, long: &str, name: &str) -> String {
770            format!("{long} {name}")
771        }
772
773        match self {
774            WorkItem::Optimize(m) => desc("opt", "optimize module", &m.name),
775            WorkItem::CopyPostLtoArtifacts(m) => desc("cpy", "copy LTO artifacts for", &m.name),
776            WorkItem::FatLto { .. } => desc("lto", "fat LTO module", "everything"),
777            WorkItem::ThinLto(m) => desc("lto", "thin-LTO module", m.name()),
778        }
779    }
780}
781
782/// A result produced by the backend.
783pub(crate) enum WorkItemResult<B: WriteBackendMethods> {
784    /// The backend has finished compiling a CGU, nothing more required.
785    Finished(CompiledModule),
786
787    /// The backend has finished compiling a CGU, which now needs to go through
788    /// fat LTO.
789    NeedsFatLto(FatLtoInput<B>),
790
791    /// The backend has finished compiling a CGU, which now needs to go through
792    /// thin LTO.
793    NeedsThinLto(String, B::ThinBuffer),
794}
795
796pub enum FatLtoInput<B: WriteBackendMethods> {
797    Serialized { name: String, buffer: SerializedModule<B::ModuleBuffer> },
798    InMemory(ModuleCodegen<B::Module>),
799}
800
801/// Actual LTO type we end up choosing based on multiple factors.
802pub(crate) enum ComputedLtoType {
803    No,
804    Thin,
805    Fat,
806}
807
808pub(crate) fn compute_per_cgu_lto_type(
809    sess_lto: &Lto,
810    opts: &config::Options,
811    sess_crate_types: &[CrateType],
812    module_kind: ModuleKind,
813) -> ComputedLtoType {
814    // If the linker does LTO, we don't have to do it. Note that we
815    // keep doing full LTO, if it is requested, as not to break the
816    // assumption that the output will be a single module.
817    let linker_does_lto = opts.cg.linker_plugin_lto.enabled();
818
819    // When we're automatically doing ThinLTO for multi-codegen-unit
820    // builds we don't actually want to LTO the allocator modules if
821    // it shows up. This is due to various linker shenanigans that
822    // we'll encounter later.
823    let is_allocator = module_kind == ModuleKind::Allocator;
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 = matches!(sess_crate_types, [CrateType::Rlib]);
834
835    match sess_lto {
836        Lto::ThinLocal if !linker_does_lto && !is_allocator => 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    mut module: ModuleCodegen<B::Module>,
846    module_config: &ModuleConfig,
847) -> WorkItemResult<B> {
848    let dcx = cgcx.create_dcx();
849    let dcx = dcx.handle();
850
851    B::optimize(cgcx, dcx, &mut module, module_config);
852
853    // After we've done the initial round of optimizations we need to
854    // decide whether to synchronously codegen this module or ship it
855    // back to the coordinator thread for further LTO processing (which
856    // has to wait for all the initial modules to be optimized).
857
858    let lto_type = compute_per_cgu_lto_type(&cgcx.lto, &cgcx.opts, &cgcx.crate_types, module.kind);
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.config(module.kind).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, module, module_config);
872            WorkItemResult::Finished(module)
873        }
874        ComputedLtoType::Thin => {
875            let (name, thin_buffer) = B::prepare_thin(module, false);
876            if let Some(path) = bitcode {
877                fs::write(&path, thin_buffer.data()).unwrap_or_else(|e| {
878                    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                    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    module: CachedModuleCodegen,
902    module_config: &ModuleConfig,
903) -> WorkItemResult<B> {
904    let incr_comp_session_dir = cgcx.incr_comp_session_dir.as_ref().unwrap();
905
906    let mut links_from_incr_cache = Vec::new();
907
908    let mut load_from_incr_comp_dir = |output_path: PathBuf, saved_path: &str| {
909        let source_file = in_incr_comp_dir(incr_comp_session_dir, saved_path);
910        debug!(
911            "copying preexisting module `{}` from {:?} to {}",
912            module.name,
913            source_file,
914            output_path.display()
915        );
916        match link_or_copy(&source_file, &output_path) {
917            Ok(_) => {
918                links_from_incr_cache.push(source_file);
919                Some(output_path)
920            }
921            Err(error) => {
922                cgcx.create_dcx().handle().emit_err(errors::CopyPathBuf {
923                    source_file,
924                    output_path,
925                    error,
926                });
927                None
928            }
929        }
930    };
931
932    let dwarf_object =
933        module.source.saved_files.get("dwo").as_ref().and_then(|saved_dwarf_object_file| {
934            let dwarf_obj_out = cgcx
935                .output_filenames
936                .split_dwarf_path(
937                    cgcx.split_debuginfo,
938                    cgcx.split_dwarf_kind,
939                    &module.name,
940                    cgcx.invocation_temp.as_deref(),
941                )
942                .expect(
943                    "saved dwarf object in work product but `split_dwarf_path` returned `None`",
944                );
945            load_from_incr_comp_dir(dwarf_obj_out, saved_dwarf_object_file)
946        });
947
948    let mut load_from_incr_cache = |perform, output_type: OutputType| {
949        if perform {
950            let saved_file = module.source.saved_files.get(output_type.extension())?;
951            let output_path = cgcx.output_filenames.temp_path_for_cgu(
952                output_type,
953                &module.name,
954                cgcx.invocation_temp.as_deref(),
955            );
956            load_from_incr_comp_dir(output_path, &saved_file)
957        } else {
958            None
959        }
960    };
961
962    let should_emit_obj = module_config.emit_obj != EmitObj::None;
963    let assembly = load_from_incr_cache(module_config.emit_asm, OutputType::Assembly);
964    let llvm_ir = load_from_incr_cache(module_config.emit_ir, OutputType::LlvmAssembly);
965    let bytecode = load_from_incr_cache(module_config.emit_bc, OutputType::Bitcode);
966    let object = load_from_incr_cache(should_emit_obj, OutputType::Object);
967    if should_emit_obj && object.is_none() {
968        cgcx.create_dcx().handle().emit_fatal(errors::NoSavedObjectFile { cgu_name: &module.name })
969    }
970
971    WorkItemResult::Finished(CompiledModule {
972        links_from_incr_cache,
973        name: module.name,
974        kind: ModuleKind::Regular,
975        object,
976        dwarf_object,
977        bytecode,
978        assembly,
979        llvm_ir,
980    })
981}
982
983fn execute_fat_lto_work_item<B: ExtraBackendMethods>(
984    cgcx: &CodegenContext<B>,
985    exported_symbols_for_lto: &[String],
986    each_linked_rlib_for_lto: &[PathBuf],
987    mut needs_fat_lto: Vec<FatLtoInput<B>>,
988    import_only_modules: Vec<(SerializedModule<B::ModuleBuffer>, WorkProduct)>,
989    module_config: &ModuleConfig,
990) -> WorkItemResult<B> {
991    for (module, wp) in import_only_modules {
992        needs_fat_lto.push(FatLtoInput::Serialized { name: wp.cgu_name, buffer: module })
993    }
994
995    let module = B::run_and_optimize_fat_lto(
996        cgcx,
997        exported_symbols_for_lto,
998        each_linked_rlib_for_lto,
999        needs_fat_lto,
1000    );
1001    let module = B::codegen(cgcx, module, module_config);
1002    WorkItemResult::Finished(module)
1003}
1004
1005fn execute_thin_lto_work_item<B: ExtraBackendMethods>(
1006    cgcx: &CodegenContext<B>,
1007    module: lto::ThinModule<B>,
1008    module_config: &ModuleConfig,
1009) -> WorkItemResult<B> {
1010    let module = B::optimize_thin(cgcx, module);
1011    let module = B::codegen(cgcx, module, module_config);
1012    WorkItemResult::Finished(module)
1013}
1014
1015/// Messages sent to the coordinator.
1016pub(crate) enum Message<B: WriteBackendMethods> {
1017    /// A jobserver token has become available. Sent from the jobserver helper
1018    /// thread.
1019    Token(io::Result<Acquired>),
1020
1021    /// The backend has finished processing a work item for a codegen unit.
1022    /// Sent from a backend worker thread.
1023    WorkItem { result: Result<WorkItemResult<B>, Option<WorkerFatalError>> },
1024
1025    /// The frontend has finished generating something (backend IR or a
1026    /// post-LTO artifact) for a codegen unit, and it should be passed to the
1027    /// backend. Sent from the main thread.
1028    CodegenDone { llvm_work_item: WorkItem<B>, cost: u64 },
1029
1030    /// Similar to `CodegenDone`, but for reusing a pre-LTO artifact
1031    /// Sent from the main thread.
1032    AddImportOnlyModule {
1033        module_data: SerializedModule<B::ModuleBuffer>,
1034        work_product: WorkProduct,
1035    },
1036
1037    /// The frontend has finished generating everything for all codegen units.
1038    /// Sent from the main thread.
1039    CodegenComplete,
1040
1041    /// Some normal-ish compiler error occurred, and codegen should be wound
1042    /// down. Sent from the main thread.
1043    CodegenAborted,
1044}
1045
1046/// A message sent from the coordinator thread to the main thread telling it to
1047/// process another codegen unit.
1048pub struct CguMessage;
1049
1050// A cut-down version of `rustc_errors::DiagInner` that impls `Send`, which
1051// can be used to send diagnostics from codegen threads to the main thread.
1052// It's missing the following fields from `rustc_errors::DiagInner`.
1053// - `span`: it doesn't impl `Send`.
1054// - `suggestions`: it doesn't impl `Send`, and isn't used for codegen
1055//   diagnostics.
1056// - `sort_span`: it doesn't impl `Send`.
1057// - `is_lint`: lints aren't relevant during codegen.
1058// - `emitted_at`: not used for codegen diagnostics.
1059struct Diagnostic {
1060    level: Level,
1061    messages: Vec<(DiagMessage, Style)>,
1062    code: Option<ErrCode>,
1063    children: Vec<Subdiagnostic>,
1064    args: DiagArgMap,
1065}
1066
1067// A cut-down version of `rustc_errors::Subdiag` that impls `Send`. It's
1068// missing the following fields from `rustc_errors::Subdiag`.
1069// - `span`: it doesn't impl `Send`.
1070pub(crate) struct Subdiagnostic {
1071    level: Level,
1072    messages: Vec<(DiagMessage, Style)>,
1073}
1074
1075#[derive(PartialEq, Clone, Copy, Debug)]
1076enum MainThreadState {
1077    /// Doing nothing.
1078    Idle,
1079
1080    /// Doing codegen, i.e. MIR-to-LLVM-IR conversion.
1081    Codegenning,
1082
1083    /// Idle, but lending the compiler process's Token to an LLVM thread so it can do useful work.
1084    Lending,
1085}
1086
1087fn start_executing_work<B: ExtraBackendMethods>(
1088    backend: B,
1089    tcx: TyCtxt<'_>,
1090    crate_info: &CrateInfo,
1091    shared_emitter: SharedEmitter,
1092    codegen_worker_send: Sender<CguMessage>,
1093    coordinator_receive: Receiver<Message<B>>,
1094    regular_config: Arc<ModuleConfig>,
1095    allocator_config: Arc<ModuleConfig>,
1096    tx_to_llvm_workers: Sender<Message<B>>,
1097) -> thread::JoinHandle<Result<CompiledModules, ()>> {
1098    let coordinator_send = tx_to_llvm_workers;
1099    let sess = tcx.sess;
1100
1101    let mut each_linked_rlib_for_lto = Vec::new();
1102    let mut each_linked_rlib_file_for_lto = Vec::new();
1103    drop(link::each_linked_rlib(crate_info, None, &mut |cnum, path| {
1104        if link::ignored_for_lto(sess, crate_info, cnum) {
1105            return;
1106        }
1107        each_linked_rlib_for_lto.push(cnum);
1108        each_linked_rlib_file_for_lto.push(path.to_path_buf());
1109    }));
1110
1111    // Compute the set of symbols we need to retain when doing LTO (if we need to)
1112    let exported_symbols_for_lto =
1113        Arc::new(lto::exported_symbols_for_lto(tcx, &each_linked_rlib_for_lto));
1114
1115    // First up, convert our jobserver into a helper thread so we can use normal
1116    // mpsc channels to manage our messages and such.
1117    // After we've requested tokens then we'll, when we can,
1118    // get tokens on `coordinator_receive` which will
1119    // get managed in the main loop below.
1120    let coordinator_send2 = coordinator_send.clone();
1121    let helper = jobserver::client()
1122        .into_helper_thread(move |token| {
1123            drop(coordinator_send2.send(Message::Token::<B>(token)));
1124        })
1125        .expect("failed to spawn helper thread");
1126
1127    let ol =
1128        if tcx.sess.opts.unstable_opts.no_codegen || !tcx.sess.opts.output_types.should_codegen() {
1129            // If we know that we won’t be doing codegen, create target machines without optimisation.
1130            config::OptLevel::No
1131        } else {
1132            tcx.backend_optimization_level(())
1133        };
1134    let backend_features = tcx.global_backend_features(());
1135
1136    let remark_dir = if let Some(ref dir) = sess.opts.unstable_opts.remark_dir {
1137        let result = fs::create_dir_all(dir).and_then(|_| dir.canonicalize());
1138        match result {
1139            Ok(dir) => Some(dir),
1140            Err(error) => sess.dcx().emit_fatal(ErrorCreatingRemarkDir { error }),
1141        }
1142    } else {
1143        None
1144    };
1145
1146    let cgcx = CodegenContext::<B> {
1147        crate_types: tcx.crate_types().to_vec(),
1148        lto: sess.lto(),
1149        fewer_names: sess.fewer_names(),
1150        save_temps: sess.opts.cg.save_temps,
1151        time_trace: sess.opts.unstable_opts.llvm_time_trace,
1152        opts: Arc::new(sess.opts.clone()),
1153        prof: sess.prof.clone(),
1154        remark: sess.opts.cg.remark.clone(),
1155        remark_dir,
1156        incr_comp_session_dir: sess.incr_comp_session_dir_opt().map(|r| r.clone()),
1157        expanded_args: tcx.sess.expanded_args.clone(),
1158        diag_emitter: shared_emitter.clone(),
1159        output_filenames: Arc::clone(tcx.output_filenames(())),
1160        regular_module_config: regular_config,
1161        allocator_module_config: allocator_config,
1162        tm_factory: backend.target_machine_factory(tcx.sess, ol, backend_features),
1163        msvc_imps_needed: msvc_imps_needed(tcx),
1164        is_pe_coff: tcx.sess.target.is_like_windows,
1165        target_can_use_split_dwarf: tcx.sess.target_can_use_split_dwarf(),
1166        target_arch: tcx.sess.target.arch.to_string(),
1167        target_is_like_darwin: tcx.sess.target.is_like_darwin,
1168        target_is_like_aix: tcx.sess.target.is_like_aix,
1169        split_debuginfo: tcx.sess.split_debuginfo(),
1170        split_dwarf_kind: tcx.sess.opts.unstable_opts.split_dwarf_kind,
1171        parallel: backend.supports_parallel() && !sess.opts.unstable_opts.no_parallel_backend,
1172        pointer_size: tcx.data_layout.pointer_size(),
1173        invocation_temp: sess.invocation_temp.clone(),
1174    };
1175
1176    // This is the "main loop" of parallel work happening for parallel codegen.
1177    // It's here that we manage parallelism, schedule work, and work with
1178    // messages coming from clients.
1179    //
1180    // There are a few environmental pre-conditions that shape how the system
1181    // is set up:
1182    //
1183    // - Error reporting can only happen on the main thread because that's the
1184    //   only place where we have access to the compiler `Session`.
1185    // - LLVM work can be done on any thread.
1186    // - Codegen can only happen on the main thread.
1187    // - Each thread doing substantial work must be in possession of a `Token`
1188    //   from the `Jobserver`.
1189    // - The compiler process always holds one `Token`. Any additional `Tokens`
1190    //   have to be requested from the `Jobserver`.
1191    //
1192    // Error Reporting
1193    // ===============
1194    // The error reporting restriction is handled separately from the rest: We
1195    // set up a `SharedEmitter` that holds an open channel to the main thread.
1196    // When an error occurs on any thread, the shared emitter will send the
1197    // error message to the receiver main thread (`SharedEmitterMain`). The
1198    // main thread will periodically query this error message queue and emit
1199    // any error messages it has received. It might even abort compilation if
1200    // it has received a fatal error. In this case we rely on all other threads
1201    // being torn down automatically with the main thread.
1202    // Since the main thread will often be busy doing codegen work, error
1203    // reporting will be somewhat delayed, since the message queue can only be
1204    // checked in between two work packages.
1205    //
1206    // Work Processing Infrastructure
1207    // ==============================
1208    // The work processing infrastructure knows three major actors:
1209    //
1210    // - the coordinator thread,
1211    // - the main thread, and
1212    // - LLVM worker threads
1213    //
1214    // The coordinator thread is running a message loop. It instructs the main
1215    // thread about what work to do when, and it will spawn off LLVM worker
1216    // threads as open LLVM WorkItems become available.
1217    //
1218    // The job of the main thread is to codegen CGUs into LLVM work packages
1219    // (since the main thread is the only thread that can do this). The main
1220    // thread will block until it receives a message from the coordinator, upon
1221    // which it will codegen one CGU, send it to the coordinator and block
1222    // again. This way the coordinator can control what the main thread is
1223    // doing.
1224    //
1225    // The coordinator keeps a queue of LLVM WorkItems, and when a `Token` is
1226    // available, it will spawn off a new LLVM worker thread and let it process
1227    // a WorkItem. When a LLVM worker thread is done with its WorkItem,
1228    // it will just shut down, which also frees all resources associated with
1229    // the given LLVM module, and sends a message to the coordinator that the
1230    // WorkItem has been completed.
1231    //
1232    // Work Scheduling
1233    // ===============
1234    // The scheduler's goal is to minimize the time it takes to complete all
1235    // work there is, however, we also want to keep memory consumption low
1236    // if possible. These two goals are at odds with each other: If memory
1237    // consumption were not an issue, we could just let the main thread produce
1238    // LLVM WorkItems at full speed, assuring maximal utilization of
1239    // Tokens/LLVM worker threads. However, since codegen is usually faster
1240    // than LLVM processing, the queue of LLVM WorkItems would fill up and each
1241    // WorkItem potentially holds on to a substantial amount of memory.
1242    //
1243    // So the actual goal is to always produce just enough LLVM WorkItems as
1244    // not to starve our LLVM worker threads. That means, once we have enough
1245    // WorkItems in our queue, we can block the main thread, so it does not
1246    // produce more until we need them.
1247    //
1248    // Doing LLVM Work on the Main Thread
1249    // ----------------------------------
1250    // Since the main thread owns the compiler process's implicit `Token`, it is
1251    // wasteful to keep it blocked without doing any work. Therefore, what we do
1252    // in this case is: We spawn off an additional LLVM worker thread that helps
1253    // reduce the queue. The work it is doing corresponds to the implicit
1254    // `Token`. The coordinator will mark the main thread as being busy with
1255    // LLVM work. (The actual work happens on another OS thread but we just care
1256    // about `Tokens`, not actual threads).
1257    //
1258    // When any LLVM worker thread finishes while the main thread is marked as
1259    // "busy with LLVM work", we can do a little switcheroo: We give the Token
1260    // of the just finished thread to the LLVM worker thread that is working on
1261    // behalf of the main thread's implicit Token, thus freeing up the main
1262    // thread again. The coordinator can then again decide what the main thread
1263    // should do. This allows the coordinator to make decisions at more points
1264    // in time.
1265    //
1266    // Striking a Balance between Throughput and Memory Consumption
1267    // ------------------------------------------------------------
1268    // Since our two goals, (1) use as many Tokens as possible and (2) keep
1269    // memory consumption as low as possible, are in conflict with each other,
1270    // we have to find a trade off between them. Right now, the goal is to keep
1271    // all workers busy, which means that no worker should find the queue empty
1272    // when it is ready to start.
1273    // How do we do achieve this? Good question :) We actually never know how
1274    // many `Tokens` are potentially available so it's hard to say how much to
1275    // fill up the queue before switching the main thread to LLVM work. Also we
1276    // currently don't have a means to estimate how long a running LLVM worker
1277    // will still be busy with it's current WorkItem. However, we know the
1278    // maximal count of available Tokens that makes sense (=the number of CPU
1279    // cores), so we can take a conservative guess. The heuristic we use here
1280    // is implemented in the `queue_full_enough()` function.
1281    //
1282    // Some Background on Jobservers
1283    // -----------------------------
1284    // It's worth also touching on the management of parallelism here. We don't
1285    // want to just spawn a thread per work item because while that's optimal
1286    // parallelism it may overload a system with too many threads or violate our
1287    // configuration for the maximum amount of cpu to use for this process. To
1288    // manage this we use the `jobserver` crate.
1289    //
1290    // Job servers are an artifact of GNU make and are used to manage
1291    // parallelism between processes. A jobserver is a glorified IPC semaphore
1292    // basically. Whenever we want to run some work we acquire the semaphore,
1293    // and whenever we're done with that work we release the semaphore. In this
1294    // manner we can ensure that the maximum number of parallel workers is
1295    // capped at any one point in time.
1296    //
1297    // LTO and the coordinator thread
1298    // ------------------------------
1299    //
1300    // The final job the coordinator thread is responsible for is managing LTO
1301    // and how that works. When LTO is requested what we'll do is collect all
1302    // optimized LLVM modules into a local vector on the coordinator. Once all
1303    // modules have been codegened and optimized we hand this to the `lto`
1304    // module for further optimization. The `lto` module will return back a list
1305    // of more modules to work on, which the coordinator will continue to spawn
1306    // work for.
1307    //
1308    // Each LLVM module is automatically sent back to the coordinator for LTO if
1309    // necessary. There's already optimizations in place to avoid sending work
1310    // back to the coordinator if LTO isn't requested.
1311    return B::spawn_named_thread(cgcx.time_trace, "coordinator".to_string(), move || {
1312        // This is where we collect codegen units that have gone all the way
1313        // through codegen and LLVM.
1314        let mut compiled_modules = vec![];
1315        let mut compiled_allocator_module = None;
1316        let mut needs_fat_lto = Vec::new();
1317        let mut needs_thin_lto = Vec::new();
1318        let mut lto_import_only_modules = Vec::new();
1319        let mut started_lto = false;
1320
1321        /// Possible state transitions:
1322        /// - Ongoing -> Completed
1323        /// - Ongoing -> Aborted
1324        /// - Completed -> Aborted
1325        #[derive(Debug, PartialEq)]
1326        enum CodegenState {
1327            Ongoing,
1328            Completed,
1329            Aborted,
1330        }
1331        use CodegenState::*;
1332        let mut codegen_state = Ongoing;
1333
1334        // This is the queue of LLVM work items that still need processing.
1335        let mut work_items = Vec::<(WorkItem<B>, u64)>::new();
1336
1337        // This are the Jobserver Tokens we currently hold. Does not include
1338        // the implicit Token the compiler process owns no matter what.
1339        let mut tokens = Vec::new();
1340
1341        let mut main_thread_state = MainThreadState::Idle;
1342
1343        // How many LLVM worker threads are running while holding a Token. This
1344        // *excludes* any that the main thread is lending a Token to.
1345        let mut running_with_own_token = 0;
1346
1347        // How many LLVM worker threads are running in total. This *includes*
1348        // any that the main thread is lending a Token to.
1349        let running_with_any_token = |main_thread_state, running_with_own_token| {
1350            running_with_own_token
1351                + if main_thread_state == MainThreadState::Lending { 1 } else { 0 }
1352        };
1353
1354        let mut llvm_start_time: Option<VerboseTimingGuard<'_>> = None;
1355
1356        // Run the message loop while there's still anything that needs message
1357        // processing. Note that as soon as codegen is aborted we simply want to
1358        // wait for all existing work to finish, so many of the conditions here
1359        // only apply if codegen hasn't been aborted as they represent pending
1360        // work to be done.
1361        loop {
1362            // While there are still CGUs to be codegened, the coordinator has
1363            // to decide how to utilize the compiler processes implicit Token:
1364            // For codegenning more CGU or for running them through LLVM.
1365            if codegen_state == Ongoing {
1366                if main_thread_state == MainThreadState::Idle {
1367                    // Compute the number of workers that will be running once we've taken as many
1368                    // items from the work queue as we can, plus one for the main thread. It's not
1369                    // critically important that we use this instead of just
1370                    // `running_with_own_token`, but it prevents the `queue_full_enough` heuristic
1371                    // from fluctuating just because a worker finished up and we decreased the
1372                    // `running_with_own_token` count, even though we're just going to increase it
1373                    // right after this when we put a new worker to work.
1374                    let extra_tokens = tokens.len().checked_sub(running_with_own_token).unwrap();
1375                    let additional_running = std::cmp::min(extra_tokens, work_items.len());
1376                    let anticipated_running = running_with_own_token + additional_running + 1;
1377
1378                    if !queue_full_enough(work_items.len(), anticipated_running) {
1379                        // The queue is not full enough, process more codegen units:
1380                        if codegen_worker_send.send(CguMessage).is_err() {
1381                            panic!("Could not send CguMessage to main thread")
1382                        }
1383                        main_thread_state = MainThreadState::Codegenning;
1384                    } else {
1385                        // The queue is full enough to not let the worker
1386                        // threads starve. Use the implicit Token to do some
1387                        // LLVM work too.
1388                        let (item, _) =
1389                            work_items.pop().expect("queue empty - queue_full_enough() broken?");
1390                        main_thread_state = MainThreadState::Lending;
1391                        spawn_work(&cgcx, coordinator_send.clone(), &mut llvm_start_time, item);
1392                    }
1393                }
1394            } else if codegen_state == Completed {
1395                if running_with_any_token(main_thread_state, running_with_own_token) == 0
1396                    && work_items.is_empty()
1397                {
1398                    // All codegen work is done. Do we have LTO work to do?
1399                    if needs_fat_lto.is_empty()
1400                        && needs_thin_lto.is_empty()
1401                        && lto_import_only_modules.is_empty()
1402                    {
1403                        // Nothing more to do!
1404                        break;
1405                    }
1406
1407                    // We have LTO work to do. Perform the serial work here of
1408                    // figuring out what we're going to LTO and then push a
1409                    // bunch of work items onto our queue to do LTO. This all
1410                    // happens on the coordinator thread but it's very quick so
1411                    // we don't worry about tokens.
1412                    assert!(!started_lto);
1413                    started_lto = true;
1414
1415                    let needs_fat_lto = mem::take(&mut needs_fat_lto);
1416                    let needs_thin_lto = mem::take(&mut needs_thin_lto);
1417                    let import_only_modules = mem::take(&mut lto_import_only_modules);
1418                    let each_linked_rlib_file_for_lto =
1419                        mem::take(&mut each_linked_rlib_file_for_lto);
1420
1421                    check_lto_allowed(&cgcx);
1422
1423                    if !needs_fat_lto.is_empty() {
1424                        assert!(needs_thin_lto.is_empty());
1425
1426                        work_items.push((
1427                            WorkItem::FatLto {
1428                                exported_symbols_for_lto: Arc::clone(&exported_symbols_for_lto),
1429                                each_linked_rlib_for_lto: each_linked_rlib_file_for_lto,
1430                                needs_fat_lto,
1431                                import_only_modules,
1432                            },
1433                            0,
1434                        ));
1435                        if cgcx.parallel {
1436                            helper.request_token();
1437                        }
1438                    } else {
1439                        for (work, cost) in generate_thin_lto_work(
1440                            &cgcx,
1441                            &exported_symbols_for_lto,
1442                            &each_linked_rlib_file_for_lto,
1443                            needs_thin_lto,
1444                            import_only_modules,
1445                        ) {
1446                            let insertion_index = work_items
1447                                .binary_search_by_key(&cost, |&(_, cost)| cost)
1448                                .unwrap_or_else(|e| e);
1449                            work_items.insert(insertion_index, (work, cost));
1450                            if cgcx.parallel {
1451                                helper.request_token();
1452                            }
1453                        }
1454                    }
1455                }
1456
1457                // In this branch, we know that everything has been codegened,
1458                // so it's just a matter of determining whether the implicit
1459                // Token is free to use for LLVM work.
1460                match main_thread_state {
1461                    MainThreadState::Idle => {
1462                        if let Some((item, _)) = work_items.pop() {
1463                            main_thread_state = MainThreadState::Lending;
1464                            spawn_work(&cgcx, coordinator_send.clone(), &mut llvm_start_time, item);
1465                        } else {
1466                            // There is no unstarted work, so let the main thread
1467                            // take over for a running worker. Otherwise the
1468                            // implicit token would just go to waste.
1469                            // We reduce the `running` counter by one. The
1470                            // `tokens.truncate()` below will take care of
1471                            // giving the Token back.
1472                            assert!(running_with_own_token > 0);
1473                            running_with_own_token -= 1;
1474                            main_thread_state = MainThreadState::Lending;
1475                        }
1476                    }
1477                    MainThreadState::Codegenning => bug!(
1478                        "codegen worker should not be codegenning after \
1479                              codegen was already completed"
1480                    ),
1481                    MainThreadState::Lending => {
1482                        // Already making good use of that token
1483                    }
1484                }
1485            } else {
1486                // Don't queue up any more work if codegen was aborted, we're
1487                // just waiting for our existing children to finish.
1488                assert!(codegen_state == Aborted);
1489                if running_with_any_token(main_thread_state, running_with_own_token) == 0 {
1490                    break;
1491                }
1492            }
1493
1494            // Spin up what work we can, only doing this while we've got available
1495            // parallelism slots and work left to spawn.
1496            if codegen_state != Aborted {
1497                while running_with_own_token < tokens.len()
1498                    && let Some((item, _)) = work_items.pop()
1499                {
1500                    spawn_work(&cgcx, coordinator_send.clone(), &mut llvm_start_time, item);
1501                    running_with_own_token += 1;
1502                }
1503            }
1504
1505            // Relinquish accidentally acquired extra tokens.
1506            tokens.truncate(running_with_own_token);
1507
1508            match coordinator_receive.recv().unwrap() {
1509                // Save the token locally and the next turn of the loop will use
1510                // this to spawn a new unit of work, or it may get dropped
1511                // immediately if we have no more work to spawn.
1512                Message::Token(token) => {
1513                    match token {
1514                        Ok(token) => {
1515                            tokens.push(token);
1516
1517                            if main_thread_state == MainThreadState::Lending {
1518                                // If the main thread token is used for LLVM work
1519                                // at the moment, we turn that thread into a regular
1520                                // LLVM worker thread, so the main thread is free
1521                                // to react to codegen demand.
1522                                main_thread_state = MainThreadState::Idle;
1523                                running_with_own_token += 1;
1524                            }
1525                        }
1526                        Err(e) => {
1527                            let msg = &format!("failed to acquire jobserver token: {e}");
1528                            shared_emitter.fatal(msg);
1529                            codegen_state = Aborted;
1530                        }
1531                    }
1532                }
1533
1534                Message::CodegenDone { llvm_work_item, cost } => {
1535                    // We keep the queue sorted by estimated processing cost,
1536                    // so that more expensive items are processed earlier. This
1537                    // is good for throughput as it gives the main thread more
1538                    // time to fill up the queue and it avoids scheduling
1539                    // expensive items to the end.
1540                    // Note, however, that this is not ideal for memory
1541                    // consumption, as LLVM module sizes are not evenly
1542                    // distributed.
1543                    let insertion_index = work_items.binary_search_by_key(&cost, |&(_, cost)| cost);
1544                    let insertion_index = match insertion_index {
1545                        Ok(idx) | Err(idx) => idx,
1546                    };
1547                    work_items.insert(insertion_index, (llvm_work_item, cost));
1548
1549                    if cgcx.parallel {
1550                        helper.request_token();
1551                    }
1552                    assert_eq!(main_thread_state, MainThreadState::Codegenning);
1553                    main_thread_state = MainThreadState::Idle;
1554                }
1555
1556                Message::CodegenComplete => {
1557                    if codegen_state != Aborted {
1558                        codegen_state = Completed;
1559                    }
1560                    assert_eq!(main_thread_state, MainThreadState::Codegenning);
1561                    main_thread_state = MainThreadState::Idle;
1562                }
1563
1564                // If codegen is aborted that means translation was aborted due
1565                // to some normal-ish compiler error. In this situation we want
1566                // to exit as soon as possible, but we want to make sure all
1567                // existing work has finished. Flag codegen as being done, and
1568                // then conditions above will ensure no more work is spawned but
1569                // we'll keep executing this loop until `running_with_own_token`
1570                // hits 0.
1571                Message::CodegenAborted => {
1572                    codegen_state = Aborted;
1573                }
1574
1575                Message::WorkItem { result } => {
1576                    // If a thread exits successfully then we drop a token associated
1577                    // with that worker and update our `running_with_own_token` count.
1578                    // We may later re-acquire a token to continue running more work.
1579                    // We may also not actually drop a token here if the worker was
1580                    // running with an "ephemeral token".
1581                    if main_thread_state == MainThreadState::Lending {
1582                        main_thread_state = MainThreadState::Idle;
1583                    } else {
1584                        running_with_own_token -= 1;
1585                    }
1586
1587                    match result {
1588                        Ok(WorkItemResult::Finished(compiled_module)) => {
1589                            match compiled_module.kind {
1590                                ModuleKind::Regular => {
1591                                    compiled_modules.push(compiled_module);
1592                                }
1593                                ModuleKind::Allocator => {
1594                                    assert!(compiled_allocator_module.is_none());
1595                                    compiled_allocator_module = Some(compiled_module);
1596                                }
1597                            }
1598                        }
1599                        Ok(WorkItemResult::NeedsFatLto(fat_lto_input)) => {
1600                            assert!(!started_lto);
1601                            assert!(needs_thin_lto.is_empty());
1602                            needs_fat_lto.push(fat_lto_input);
1603                        }
1604                        Ok(WorkItemResult::NeedsThinLto(name, thin_buffer)) => {
1605                            assert!(!started_lto);
1606                            assert!(needs_fat_lto.is_empty());
1607                            needs_thin_lto.push((name, thin_buffer));
1608                        }
1609                        Err(Some(WorkerFatalError)) => {
1610                            // Like `CodegenAborted`, wait for remaining work to finish.
1611                            codegen_state = Aborted;
1612                        }
1613                        Err(None) => {
1614                            // If the thread failed that means it panicked, so
1615                            // we abort immediately.
1616                            bug!("worker thread panicked");
1617                        }
1618                    }
1619                }
1620
1621                Message::AddImportOnlyModule { module_data, work_product } => {
1622                    assert!(!started_lto);
1623                    assert_eq!(codegen_state, Ongoing);
1624                    assert_eq!(main_thread_state, MainThreadState::Codegenning);
1625                    lto_import_only_modules.push((module_data, work_product));
1626                    main_thread_state = MainThreadState::Idle;
1627                }
1628            }
1629        }
1630
1631        if codegen_state == Aborted {
1632            return Err(());
1633        }
1634
1635        // Drop to print timings
1636        drop(llvm_start_time);
1637
1638        // Regardless of what order these modules completed in, report them to
1639        // the backend in the same order every time to ensure that we're handing
1640        // out deterministic results.
1641        compiled_modules.sort_by(|a, b| a.name.cmp(&b.name));
1642
1643        Ok(CompiledModules {
1644            modules: compiled_modules,
1645            allocator_module: compiled_allocator_module,
1646        })
1647    })
1648    .expect("failed to spawn coordinator thread");
1649
1650    // A heuristic that determines if we have enough LLVM WorkItems in the
1651    // queue so that the main thread can do LLVM work instead of codegen
1652    fn queue_full_enough(items_in_queue: usize, workers_running: usize) -> bool {
1653        // This heuristic scales ahead-of-time codegen according to available
1654        // concurrency, as measured by `workers_running`. The idea is that the
1655        // more concurrency we have available, the more demand there will be for
1656        // work items, and the fuller the queue should be kept to meet demand.
1657        // An important property of this approach is that we codegen ahead of
1658        // time only as much as necessary, so as to keep fewer LLVM modules in
1659        // memory at once, thereby reducing memory consumption.
1660        //
1661        // When the number of workers running is less than the max concurrency
1662        // available to us, this heuristic can cause us to instruct the main
1663        // thread to work on an LLVM item (that is, tell it to "LLVM") instead
1664        // of codegen, even though it seems like it *should* be codegenning so
1665        // that we can create more work items and spawn more LLVM workers.
1666        //
1667        // But this is not a problem. When the main thread is told to LLVM,
1668        // according to this heuristic and how work is scheduled, there is
1669        // always at least one item in the queue, and therefore at least one
1670        // pending jobserver token request. If there *is* more concurrency
1671        // available, we will immediately receive a token, which will upgrade
1672        // the main thread's LLVM worker to a real one (conceptually), and free
1673        // up the main thread to codegen if necessary. On the other hand, if
1674        // there isn't more concurrency, then the main thread working on an LLVM
1675        // item is appropriate, as long as the queue is full enough for demand.
1676        //
1677        // Speaking of which, how full should we keep the queue? Probably less
1678        // full than you'd think. A lot has to go wrong for the queue not to be
1679        // full enough and for that to have a negative effect on compile times.
1680        //
1681        // Workers are unlikely to finish at exactly the same time, so when one
1682        // finishes and takes another work item off the queue, we often have
1683        // ample time to codegen at that point before the next worker finishes.
1684        // But suppose that codegen takes so long that the workers exhaust the
1685        // queue, and we have one or more workers that have nothing to work on.
1686        // Well, it might not be so bad. Of all the LLVM modules we create and
1687        // optimize, one has to finish last. It's not necessarily the case that
1688        // by losing some concurrency for a moment, we delay the point at which
1689        // that last LLVM module is finished and the rest of compilation can
1690        // proceed. Also, when we can't take advantage of some concurrency, we
1691        // give tokens back to the job server. That enables some other rustc to
1692        // potentially make use of the available concurrency. That could even
1693        // *decrease* overall compile time if we're lucky. But yes, if no other
1694        // rustc can make use of the concurrency, then we've squandered it.
1695        //
1696        // However, keeping the queue full is also beneficial when we have a
1697        // surge in available concurrency. Then items can be taken from the
1698        // queue immediately, without having to wait for codegen.
1699        //
1700        // So, the heuristic below tries to keep one item in the queue for every
1701        // four running workers. Based on limited benchmarking, this appears to
1702        // be more than sufficient to avoid increasing compilation times.
1703        let quarter_of_workers = workers_running - 3 * workers_running / 4;
1704        items_in_queue > 0 && items_in_queue >= quarter_of_workers
1705    }
1706}
1707
1708/// `FatalError` is explicitly not `Send`.
1709#[must_use]
1710pub(crate) struct WorkerFatalError;
1711
1712fn spawn_work<'a, B: ExtraBackendMethods>(
1713    cgcx: &'a CodegenContext<B>,
1714    coordinator_send: Sender<Message<B>>,
1715    llvm_start_time: &mut Option<VerboseTimingGuard<'a>>,
1716    work: WorkItem<B>,
1717) {
1718    if llvm_start_time.is_none() {
1719        *llvm_start_time = Some(cgcx.prof.verbose_generic_activity("LLVM_passes"));
1720    }
1721
1722    let cgcx = cgcx.clone();
1723
1724    B::spawn_named_thread(cgcx.time_trace, work.short_description(), move || {
1725        let result = std::panic::catch_unwind(AssertUnwindSafe(|| {
1726            let module_config = cgcx.config(work.module_kind());
1727
1728            match work {
1729                WorkItem::Optimize(m) => {
1730                    let _timer =
1731                        cgcx.prof.generic_activity_with_arg("codegen_module_optimize", &*m.name);
1732                    execute_optimize_work_item(&cgcx, m, module_config)
1733                }
1734                WorkItem::CopyPostLtoArtifacts(m) => {
1735                    let _timer = cgcx.prof.generic_activity_with_arg(
1736                        "codegen_copy_artifacts_from_incr_cache",
1737                        &*m.name,
1738                    );
1739                    execute_copy_from_cache_work_item(&cgcx, m, module_config)
1740                }
1741                WorkItem::FatLto {
1742                    exported_symbols_for_lto,
1743                    each_linked_rlib_for_lto,
1744                    needs_fat_lto,
1745                    import_only_modules,
1746                } => {
1747                    let _timer = cgcx
1748                        .prof
1749                        .generic_activity_with_arg("codegen_module_perform_lto", "everything");
1750                    execute_fat_lto_work_item(
1751                        &cgcx,
1752                        &exported_symbols_for_lto,
1753                        &each_linked_rlib_for_lto,
1754                        needs_fat_lto,
1755                        import_only_modules,
1756                        module_config,
1757                    )
1758                }
1759                WorkItem::ThinLto(m) => {
1760                    let _timer =
1761                        cgcx.prof.generic_activity_with_arg("codegen_module_perform_lto", m.name());
1762                    execute_thin_lto_work_item(&cgcx, m, module_config)
1763                }
1764            }
1765        }));
1766
1767        let msg = match result {
1768            Ok(result) => Message::WorkItem::<B> { result: Ok(result) },
1769
1770            // We ignore any `FatalError` coming out of `execute_work_item`, as a
1771            // diagnostic was already sent off to the main thread - just surface
1772            // that there was an error in this worker.
1773            Err(err) if err.is::<FatalErrorMarker>() => {
1774                Message::WorkItem::<B> { result: Err(Some(WorkerFatalError)) }
1775            }
1776
1777            Err(_) => Message::WorkItem::<B> { result: Err(None) },
1778        };
1779        drop(coordinator_send.send(msg));
1780    })
1781    .expect("failed to spawn work thread");
1782}
1783
1784enum SharedEmitterMessage {
1785    Diagnostic(Diagnostic),
1786    InlineAsmError(SpanData, String, Level, Option<(String, Vec<InnerSpan>)>),
1787    Fatal(String),
1788}
1789
1790#[derive(Clone)]
1791pub struct SharedEmitter {
1792    sender: Sender<SharedEmitterMessage>,
1793}
1794
1795pub struct SharedEmitterMain {
1796    receiver: Receiver<SharedEmitterMessage>,
1797}
1798
1799impl SharedEmitter {
1800    fn new() -> (SharedEmitter, SharedEmitterMain) {
1801        let (sender, receiver) = channel();
1802
1803        (SharedEmitter { sender }, SharedEmitterMain { receiver })
1804    }
1805
1806    pub fn inline_asm_error(
1807        &self,
1808        span: SpanData,
1809        msg: String,
1810        level: Level,
1811        source: Option<(String, Vec<InnerSpan>)>,
1812    ) {
1813        drop(self.sender.send(SharedEmitterMessage::InlineAsmError(span, msg, level, source)));
1814    }
1815
1816    fn fatal(&self, msg: &str) {
1817        drop(self.sender.send(SharedEmitterMessage::Fatal(msg.to_string())));
1818    }
1819}
1820
1821impl Emitter for SharedEmitter {
1822    fn emit_diagnostic(
1823        &mut self,
1824        mut diag: rustc_errors::DiagInner,
1825        _registry: &rustc_errors::registry::Registry,
1826    ) {
1827        // Check that we aren't missing anything interesting when converting to
1828        // the cut-down local `DiagInner`.
1829        assert_eq!(diag.span, MultiSpan::new());
1830        assert_eq!(diag.suggestions, Suggestions::Enabled(vec![]));
1831        assert_eq!(diag.sort_span, rustc_span::DUMMY_SP);
1832        assert_eq!(diag.is_lint, None);
1833        // No sensible check for `diag.emitted_at`.
1834
1835        let args = mem::replace(&mut diag.args, DiagArgMap::default());
1836        drop(
1837            self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
1838                level: diag.level(),
1839                messages: diag.messages,
1840                code: diag.code,
1841                children: diag
1842                    .children
1843                    .into_iter()
1844                    .map(|child| Subdiagnostic { level: child.level, messages: child.messages })
1845                    .collect(),
1846                args,
1847            })),
1848        );
1849    }
1850
1851    fn source_map(&self) -> Option<&SourceMap> {
1852        None
1853    }
1854
1855    fn translator(&self) -> &Translator {
1856        panic!("shared emitter attempted to translate a diagnostic");
1857    }
1858}
1859
1860impl SharedEmitterMain {
1861    fn check(&self, sess: &Session, blocking: bool) {
1862        loop {
1863            let message = if blocking {
1864                match self.receiver.recv() {
1865                    Ok(message) => Ok(message),
1866                    Err(_) => Err(()),
1867                }
1868            } else {
1869                match self.receiver.try_recv() {
1870                    Ok(message) => Ok(message),
1871                    Err(_) => Err(()),
1872                }
1873            };
1874
1875            match message {
1876                Ok(SharedEmitterMessage::Diagnostic(diag)) => {
1877                    // The diagnostic has been received on the main thread.
1878                    // Convert it back to a full `Diagnostic` and emit.
1879                    let dcx = sess.dcx();
1880                    let mut d =
1881                        rustc_errors::DiagInner::new_with_messages(diag.level, diag.messages);
1882                    d.code = diag.code; // may be `None`, that's ok
1883                    d.children = diag
1884                        .children
1885                        .into_iter()
1886                        .map(|sub| rustc_errors::Subdiag {
1887                            level: sub.level,
1888                            messages: sub.messages,
1889                            span: MultiSpan::new(),
1890                        })
1891                        .collect();
1892                    d.args = diag.args;
1893                    dcx.emit_diagnostic(d);
1894                    sess.dcx().abort_if_errors();
1895                }
1896                Ok(SharedEmitterMessage::InlineAsmError(span, msg, level, source)) => {
1897                    assert_matches!(level, Level::Error | Level::Warning | Level::Note);
1898                    let mut err = Diag::<()>::new(sess.dcx(), level, msg);
1899                    if !span.is_dummy() {
1900                        err.span(span.span());
1901                    }
1902
1903                    // Point to the generated assembly if it is available.
1904                    if let Some((buffer, spans)) = source {
1905                        let source = sess
1906                            .source_map()
1907                            .new_source_file(FileName::inline_asm_source_code(&buffer), buffer);
1908                        let spans: Vec<_> = spans
1909                            .iter()
1910                            .map(|sp| {
1911                                Span::with_root_ctxt(
1912                                    source.normalized_byte_pos(sp.start as u32),
1913                                    source.normalized_byte_pos(sp.end as u32),
1914                                )
1915                            })
1916                            .collect();
1917                        err.span_note(spans, "instantiated into assembly here");
1918                    }
1919
1920                    err.emit();
1921                }
1922                Ok(SharedEmitterMessage::Fatal(msg)) => {
1923                    sess.dcx().fatal(msg);
1924                }
1925                Err(_) => {
1926                    break;
1927                }
1928            }
1929        }
1930    }
1931}
1932
1933pub struct Coordinator<B: ExtraBackendMethods> {
1934    sender: Sender<Message<B>>,
1935    future: Option<thread::JoinHandle<Result<CompiledModules, ()>>>,
1936    // Only used for the Message type.
1937    phantom: PhantomData<B>,
1938}
1939
1940impl<B: ExtraBackendMethods> Coordinator<B> {
1941    fn join(mut self) -> std::thread::Result<Result<CompiledModules, ()>> {
1942        self.future.take().unwrap().join()
1943    }
1944}
1945
1946impl<B: ExtraBackendMethods> Drop for Coordinator<B> {
1947    fn drop(&mut self) {
1948        if let Some(future) = self.future.take() {
1949            // If we haven't joined yet, signal to the coordinator that it should spawn no more
1950            // work, and wait for worker threads to finish.
1951            drop(self.sender.send(Message::CodegenAborted::<B>));
1952            drop(future.join());
1953        }
1954    }
1955}
1956
1957pub struct OngoingCodegen<B: ExtraBackendMethods> {
1958    pub backend: B,
1959    pub crate_info: CrateInfo,
1960    pub codegen_worker_receive: Receiver<CguMessage>,
1961    pub shared_emitter_main: SharedEmitterMain,
1962    pub output_filenames: Arc<OutputFilenames>,
1963    pub coordinator: Coordinator<B>,
1964}
1965
1966impl<B: ExtraBackendMethods> OngoingCodegen<B> {
1967    pub fn join(self, sess: &Session) -> (CodegenResults, FxIndexMap<WorkProductId, WorkProduct>) {
1968        self.shared_emitter_main.check(sess, true);
1969        let compiled_modules = sess.time("join_worker_thread", || match self.coordinator.join() {
1970            Ok(Ok(compiled_modules)) => compiled_modules,
1971            Ok(Err(())) => {
1972                sess.dcx().abort_if_errors();
1973                panic!("expected abort due to worker thread errors")
1974            }
1975            Err(_) => {
1976                bug!("panic during codegen/LLVM phase");
1977            }
1978        });
1979
1980        sess.dcx().abort_if_errors();
1981
1982        let work_products =
1983            copy_all_cgu_workproducts_to_incr_comp_cache_dir(sess, &compiled_modules);
1984        produce_final_output_artifacts(sess, &compiled_modules, &self.output_filenames);
1985
1986        // FIXME: time_llvm_passes support - does this use a global context or
1987        // something?
1988        if sess.codegen_units().as_usize() == 1 && sess.opts.unstable_opts.time_llvm_passes {
1989            self.backend.print_pass_timings()
1990        }
1991
1992        if sess.print_llvm_stats() {
1993            self.backend.print_statistics()
1994        }
1995
1996        (
1997            CodegenResults {
1998                crate_info: self.crate_info,
1999
2000                modules: compiled_modules.modules,
2001                allocator_module: compiled_modules.allocator_module,
2002            },
2003            work_products,
2004        )
2005    }
2006
2007    pub(crate) fn codegen_finished(&self, tcx: TyCtxt<'_>) {
2008        self.wait_for_signal_to_codegen_item();
2009        self.check_for_errors(tcx.sess);
2010        drop(self.coordinator.sender.send(Message::CodegenComplete::<B>));
2011    }
2012
2013    pub(crate) fn check_for_errors(&self, sess: &Session) {
2014        self.shared_emitter_main.check(sess, false);
2015    }
2016
2017    pub(crate) fn wait_for_signal_to_codegen_item(&self) {
2018        match self.codegen_worker_receive.recv() {
2019            Ok(CguMessage) => {
2020                // Ok to proceed.
2021            }
2022            Err(_) => {
2023                // One of the LLVM threads must have panicked, fall through so
2024                // error handling can be reached.
2025            }
2026        }
2027    }
2028}
2029
2030pub(crate) fn submit_codegened_module_to_llvm<B: ExtraBackendMethods>(
2031    coordinator: &Coordinator<B>,
2032    module: ModuleCodegen<B::Module>,
2033    cost: u64,
2034) {
2035    let llvm_work_item = WorkItem::Optimize(module);
2036    drop(coordinator.sender.send(Message::CodegenDone::<B> { llvm_work_item, cost }));
2037}
2038
2039pub(crate) fn submit_post_lto_module_to_llvm<B: ExtraBackendMethods>(
2040    coordinator: &Coordinator<B>,
2041    module: CachedModuleCodegen,
2042) {
2043    let llvm_work_item = WorkItem::CopyPostLtoArtifacts(module);
2044    drop(coordinator.sender.send(Message::CodegenDone::<B> { llvm_work_item, cost: 0 }));
2045}
2046
2047pub(crate) fn submit_pre_lto_module_to_llvm<B: ExtraBackendMethods>(
2048    tcx: TyCtxt<'_>,
2049    coordinator: &Coordinator<B>,
2050    module: CachedModuleCodegen,
2051) {
2052    let filename = pre_lto_bitcode_filename(&module.name);
2053    let bc_path = in_incr_comp_dir_sess(tcx.sess, &filename);
2054    let file = fs::File::open(&bc_path)
2055        .unwrap_or_else(|e| panic!("failed to open bitcode file `{}`: {}", bc_path.display(), e));
2056
2057    let mmap = unsafe {
2058        Mmap::map(file).unwrap_or_else(|e| {
2059            panic!("failed to mmap bitcode file `{}`: {}", bc_path.display(), e)
2060        })
2061    };
2062    // Schedule the module to be loaded
2063    drop(coordinator.sender.send(Message::AddImportOnlyModule::<B> {
2064        module_data: SerializedModule::FromUncompressedFile(mmap),
2065        work_product: module.source,
2066    }));
2067}
2068
2069fn pre_lto_bitcode_filename(module_name: &str) -> String {
2070    format!("{module_name}.{PRE_LTO_BC_EXT}")
2071}
2072
2073fn msvc_imps_needed(tcx: TyCtxt<'_>) -> bool {
2074    // This should never be true (because it's not supported). If it is true,
2075    // something is wrong with commandline arg validation.
2076    assert!(
2077        !(tcx.sess.opts.cg.linker_plugin_lto.enabled()
2078            && tcx.sess.target.is_like_windows
2079            && tcx.sess.opts.cg.prefer_dynamic)
2080    );
2081
2082    // We need to generate _imp__ symbol if we are generating an rlib or we include one
2083    // indirectly from ThinLTO. In theory these are not needed as ThinLTO could resolve
2084    // these, but it currently does not do so.
2085    let can_have_static_objects =
2086        tcx.sess.lto() == Lto::Thin || tcx.crate_types().contains(&CrateType::Rlib);
2087
2088    tcx.sess.target.is_like_windows &&
2089    can_have_static_objects   &&
2090    // ThinLTO can't handle this workaround in all cases, so we don't
2091    // emit the `__imp_` symbols. Instead we make them unnecessary by disallowing
2092    // dynamic linking when linker plugin LTO is enabled.
2093    !tcx.sess.opts.cg.linker_plugin_lto.enabled()
2094}