Skip to main content

rustc_codegen_ssa/back/
write.rs

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