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