Skip to main content

rustc_codegen_ssa/back/
write.rs

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