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