Skip to main content

rustc_codegen_ssa/back/
write.rs

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