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