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, mem, str, thread};
89use 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::{
14Diag, DiagArgMap, DiagCtxt, DiagCtxtHandle, DiagMessage, ErrCode, FatalError, FatalErrorMarker,
15Level, MultiSpan, Style, Sublevel, Suggestions, catch_fatal_errors,
16};
17use rustc_fs_util::link_or_copy;
18use rustc_incremental::{
19copy_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::{
26self, Lto, OptLevel, OutFileName, OutputFilenames, OutputType, Passes, SwitchWithOptPath,
27};
28use rustc_session::{IncrCompSession, Session};
29use rustc_span::source_map::SourceMap;
30use rustc_span::{FileName, InnerSpan, Span, SpanData, bug};
31use rustc_structures::CrateType;
32use rustc_target::spec::{MergeFunctions, SanitizerSet};
33use tracing::debug;
3435use crate::back::link::ensure_removed;
36use crate::back::lto::{self, SerializedModule, check_lto_allowed};
37use crate::diagnostics::ErrorCreatingRemarkDir;
38use crate::traits::*;
39use crate::{
40CachedModuleCodegen, CompiledModule, CompiledModules, CrateInfo, ModuleCodegen, ModuleKind,
41diagnostics,
42};
4344const PRE_LTO_BC_EXT: &str = "pre-lto.bc";
4546/// 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.
50None,
5152// Just uncompressed llvm bitcode. Provides easy compatibility with
53 // emscripten's ecc compiler, when used as the linker.
54Bitcode,
5556// Object code, possibly augmented with a bitcode section.
57ObjectCode(BitcodeSection),
58}
5960/// 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.
64None,
6566// A full, uncompressed bitcode section.
67Full,
68}
6970/// 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.
74pub 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).
77pub opt_level: Option<config::OptLevel>,
7879pub pgo_gen: SwitchWithOptPath,
80pub pgo_use: Option<PathBuf>,
81pub pgo_sample_use: Option<PathBuf>,
82pub debug_info_for_profiling: bool,
83pub instrument_coverage: bool,
8485pub sanitizer: SanitizerSet,
86pub sanitizer_cfi_diag: Option<bool>,
87pub sanitizer_cfi_recover: Option<bool>,
88pub sanitizer_recover: SanitizerSet,
89pub sanitizer_dataflow_abilist: Vec<String>,
90pub sanitizer_memory_track_origins: usize,
9192// Flags indicating which outputs to produce.
93pub emit_pre_lto_bc: bool,
94pub emit_bc: bool,
95pub emit_ir: bool,
96pub emit_asm: bool,
97pub emit_obj: EmitObj,
98pub emit_thin_lto_summary: bool,
99100// Miscellaneous flags. These are mostly copied from command-line
101 // options.
102pub verify_llvm_ir: bool,
103pub lint_llvm_ir: bool,
104pub no_prepopulate_passes: bool,
105pub no_builtins: bool,
106pub vectorize_loop: bool,
107pub vectorize_slp: bool,
108pub merge_functions: bool,
109pub emit_lifetime_markers: bool,
110pub llvm_plugins: Vec<String>,
111pub autodiff: Vec<config::AutoDiff>,
112pub autodiff_post_passes: Option<String>,
113pub offload: Vec<config::Offload>,
114}
115116impl ModuleConfig {
117pub(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.
120macro_rules! if_regular {
121 ($regular: expr, $other: expr) => {
122if let ModuleKind::Regular = kind { $regular } else { $other }
123 };
124 }
125126let sess = tcx.sess;
127let opt_level_and_size = if let ModuleKind::Regular = kind { Some(sess.opts.optimize) } else { None }if_regular!(Some(sess.opts.optimize), None);
128129let save_temps = sess.opts.cg.save_temps;
130131let 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 };
136137let emit_obj = if !should_emit_obj {
138 EmitObj::None139 } 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).
166EmitObj::Bitcode167 } else if need_bitcode_in_object(tcx) || sess.target.requires_lto {
168 EmitObj::ObjectCode(BitcodeSection::Full)
169 } else {
170 EmitObj::ObjectCode(BitcodeSection::None)
171 };
172173ModuleConfig {
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![]),
175176 opt_level: opt_level_and_size,
177178 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),
186187 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,
2000
201),
202203 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),
205false
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),
213false
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),
217false
218),
219emit_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),
222false
223),
224225 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,
229230// Copy what clang does by turning on loop vectorization at O2 and
231 // slp vectorization at O3.
232vectorize_loop: !sess.opts.cg.no_vectorize_loops
233 && (sess.opts.optimize == config::OptLevel::More234 || sess.opts.optimize == config::OptLevel::Aggressive),
235 vectorize_slp: !sess.opts.cg.no_vectorize_slp
236 && sess.opts.optimize == config::OptLevel::Aggressive,
237238// 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.
247merge_functions: match sess.merge_functions() {
248 MergeFunctions::Disabled => false,
249 MergeFunctions::Trampolines | MergeFunctions::Aliases => {
250use config::OptLevel::*;
251match sess.opts.optimize {
252Aggressive | More | SizeMin | Size => true,
253Less | No => false,
254 }
255 }
256 },
257258 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(),
263None
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 }
268269pub fn bitcode_needed(&self) -> bool {
270self.emit_bc
271 || self.emit_thin_lto_summary
272 || self.emit_obj == EmitObj::Bitcode273 || self.emit_obj == EmitObj::ObjectCode(BitcodeSection::Full)
274 }
275276pub fn embed_bitcode(&self) -> bool {
277self.emit_obj == EmitObj::ObjectCode(BitcodeSection::Full)
278 }
279}
280281/// 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.
286pub split_dwarf_file: Option<PathBuf>,
287288/// 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
290pub output_obj_file: Option<PathBuf>,
291}
292293impl TargetMachineFactoryConfig {
294pub fn new(cgcx: &CodegenContext, module_name: &str) -> TargetMachineFactoryConfig {
295let split_dwarf_file = if cgcx.target_can_use_split_dwarf {
296cgcx.output_filenames.split_dwarf_path(
297cgcx.split_debuginfo,
298cgcx.split_dwarf_kind,
299module_name,
300 )
301 } else {
302None303 };
304305let output_obj_file =
306Some(cgcx.output_filenames.temp_path_for_cgu(OutputType::Object, module_name));
307TargetMachineFactoryConfig { split_dwarf_file, output_obj_file }
308 }
309}
310311pub type TargetMachineFactoryFn<B> = Arc<
312dyn Fn(
313DiagCtxtHandle<'_>,
314TargetMachineFactoryConfig,
315 ) -> <B as WriteBackendMethods>::TargetMachine316 + Send317 + Sync,
318>;
319320/// 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),
remark: ::core::clone::Clone::clone(&self.remark),
remark_dir: ::core::clone::Clone::clone(&self.remark_dir),
old_incr_comp_session_dir: ::core::clone::Clone::clone(&self.old_incr_comp_session_dir),
new_incr_comp_session_dir: ::core::clone::Clone::clone(&self.new_incr_comp_session_dir),
parallel: ::core::clone::Clone::clone(&self.parallel),
}
}
}Clone, const _: () =
{
impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
for CodegenContext {
fn encode(&self, __encoder: &mut __E) {
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,
remark: ref __binding_21,
remark_dir: ref __binding_22,
old_incr_comp_session_dir: ref __binding_23,
new_incr_comp_session_dir: ref __binding_24,
parallel: ref __binding_25 } = *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);
}
}
};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),
remark: ::rustc_serialize::Decodable::decode(__decoder),
remark_dir: ::rustc_serialize::Decodable::decode(__decoder),
old_incr_comp_session_dir: ::rustc_serialize::Decodable::decode(__decoder),
new_incr_comp_session_dir: ::rustc_serialize::Decodable::decode(__decoder),
parallel: ::rustc_serialize::Decodable::decode(__decoder),
}
}
}
};Decodable)]
322pub struct CodegenContext {
323// Resources needed when running LTO
324pub lto: Lto,
325pub use_linker_plugin_lto: bool,
326pub dylib_lto: bool,
327pub prefer_dynamic: bool,
328pub save_temps: bool,
329pub fewer_names: bool,
330pub time_trace: bool,
331pub crate_types: Vec<CrateType>,
332pub output_filenames: Arc<OutputFilenames>,
333pub module_config: Arc<ModuleConfig>,
334pub opt_level: OptLevel,
335pub msvc_imps_needed: bool,
336pub is_pe_coff: bool,
337pub target_can_use_split_dwarf: bool,
338pub target_arch: String,
339pub target_is_like_darwin: bool,
340pub target_is_like_aix: bool,
341pub target_is_like_gpu: bool,
342pub split_debuginfo: rustc_target::spec::SplitDebuginfo,
343pub split_dwarf_kind: rustc_session::config::SplitDwarfKind,
344pub pointer_size: Size,
345346/// LLVM optimizations for which we want to print remarks.
347pub remark: Passes,
348/// Directory into which should the LLVM optimization remarks be written.
349 /// If `None`, they will be written to stderr.
350pub remark_dir: Option<PathBuf>,
351/// The previous incremental compilation session directory, or None if we
352 /// are not compiling incrementally or there is no previous session.
353pub old_incr_comp_session_dir: Option<PathBuf>,
354/// The incremental compilation session directory, or None if we are not
355 /// compiling incrementally
356pub new_incr_comp_session_dir: Option<PathBuf>,
357/// `Some(limit)` if the codegen should be run in parallel.
358 ///
359 /// Depends on [`WriteBackendMethods::supports_parallel()`] and `--jobs-backend`.
360pub parallel: Option<NonZero<usize>>,
361}
362363fn generate_thin_lto_work<B: WriteBackendMethods>(
364 cgcx: &CodegenContext,
365 prof: &SelfProfilerRef,
366 dcx: DiagCtxtHandle<'_>,
367 exported_symbols_for_lto: &[String],
368 each_linked_rlib_for_lto: &[PathBuf],
369 needs_thin_lto: Vec<ThinLtoInput<B>>,
370) -> Vec<(ThinLtoWorkItem<B>, u64)> {
371let _prof_timer = prof.generic_activity("codegen_thin_generate_lto_work");
372373let (lto_modules, copy_jobs) = B::run_thin_lto(
374cgcx,
375prof,
376dcx,
377exported_symbols_for_lto,
378each_linked_rlib_for_lto,
379needs_thin_lto,
380 );
381lto_modules382 .into_iter()
383 .map(|module| {
384let cost = module.cost();
385 (ThinLtoWorkItem::ThinLto(module), cost)
386 })
387 .chain(copy_jobs.into_iter().map(|wp| {
388 (
389 ThinLtoWorkItem::CopyPostLtoArtifacts(CachedModuleCodegen {
390 name: wp.cgu_name.clone(),
391 source: wp,
392 }),
3930, // copying is very cheap
394)
395 }))
396 .collect()
397}
398399enum MaybeLtoModules<B: WriteBackendMethods> {
400 NoLto(CompiledModules),
401 FatLto { cgcx: CodegenContext, needs_fat_lto: Vec<FatLtoInput<B>> },
402 ThinLto { cgcx: CodegenContext, needs_thin_lto: Vec<ThinLtoInput<B>> },
403}
404405fn need_bitcode_in_object(tcx: TyCtxt<'_>) -> bool {
406let sess = tcx.sess;
407sess.opts.cg.embed_bitcode
408 && tcx.crate_types().contains(&CrateType::Rlib)
409 && sess.opts.output_types.contains_key(&OutputType::Exe)
410}
411412fn need_pre_lto_bitcode_for_incr_comp(sess: &Session) -> bool {
413if sess.opts.incremental.is_none() {
414return false;
415 }
416417match sess.lto() {
418 Lto::No => false,
419 Lto::Fat | Lto::Thin | Lto::ThinLocal => true,
420 }
421}
422423pub(crate) fn start_async_codegen<B: WriteBackendMethods>(
424 backend: B,
425 tcx: TyCtxt<'_>,
426 regular_config: Arc<ModuleConfig>,
427 allocator_config: Arc<ModuleConfig>,
428 allocator_module: Option<ModuleCodegen<B::Module>>,
429) -> OngoingCodegen<B> {
430let (coordinator_send, coordinator_receive) = channel();
431432let (shared_emitter, shared_emitter_main) = SharedEmitter::new();
433let (codegen_worker_send, codegen_worker_receive) = channel();
434435let coordinator_thread = start_executing_work(
436backend.clone(),
437tcx,
438shared_emitter,
439codegen_worker_send,
440coordinator_receive,
441regular_config,
442allocator_config,
443allocator_module,
444coordinator_send.clone(),
445 );
446447OngoingCodegen {
448backend,
449450codegen_worker_receive,
451shared_emitter_main,
452 coordinator: Coordinator {
453 sender: coordinator_send,
454 future: Some(coordinator_thread),
455 phantom: PhantomData,
456 },
457 output_filenames: Arc::clone(tcx.output_filenames(())),
458 }
459}
460461fn copy_all_cgu_workproducts_to_incr_comp_cache_dir(
462 sess: &Session,
463 incr_comp_session: Option<&IncrCompSession>,
464 compiled_modules: &CompiledModules,
465) -> WorkProductMap {
466let mut work_products = WorkProductMap::default();
467468if sess.opts.incremental.is_none() || sess.opts.unstable_opts.disable_incr_comp_backend_caching
469 {
470return work_products;
471 }
472473let _timer = sess.timer("copy_all_cgu_workproducts_to_incr_comp_cache_dir");
474475for module in compiled_modules.modules.iter().filter(|m| m.kind == ModuleKind::Regular) {
476let mut files = Vec::new();
477if let Some(object_file_path) = &module.object {
478 files.push((OutputType::Object.extension(), object_file_path.as_path()));
479 }
480if let Some(global_asm_object_file_path) = &module.global_asm_object {
481 files.push(("asm.o", global_asm_object_file_path.as_path()));
482 }
483if let Some(dwarf_object_file_path) = &module.dwarf_object {
484 files.push(("dwo", dwarf_object_file_path.as_path()));
485 }
486if let Some(path) = &module.assembly {
487 files.push((OutputType::Assembly.extension(), path.as_path()));
488 }
489if let Some(path) = &module.llvm_ir {
490 files.push((OutputType::LlvmAssembly.extension(), path.as_path()));
491 }
492if let Some(path) = &module.bytecode {
493 files.push((OutputType::Bitcode.extension(), path.as_path()));
494 }
495let (id, product) = copy_cgu_workproduct_to_incr_comp_cache_dir(
496 sess,
497 incr_comp_session.unwrap(),
498&module.name,
499 files.as_slice(),
500 );
501 work_products.insert(id, product);
502 }
503504work_products505}
506507pub fn produce_final_output_artifacts(
508 sess: &Session,
509 compiled_modules: &CompiledModules,
510 crate_output: &OutputFilenames,
511) {
512let mut user_wants_bitcode = false;
513let mut user_wants_objects = false;
514515// Produce final compile outputs.
516let copy_gracefully = |from: &Path, to: &OutFileName| match to {
517 OutFileName::Stdoutif let Err(e) = copy_to_stdout(from) => {
518sess.dcx().emit_err(diagnostics::CopyPath::new(from, to.as_path(), e));
519 }
520 OutFileName::Real(path) if let Err(e) = fs::copy(from, path) => {
521sess.dcx().emit_err(diagnostics::CopyPath::new(from, path, e));
522 }
523_ => {}
524 };
525526let copy_if_one_unit = |output_type: OutputType, keep_numbered: bool| {
527if let [module] = &compiled_modules.modules[..] {
528// 1) Only one codegen unit. In this case it's no difficulty
529 // to copy `foo.0.x` to `foo.x`.
530let path = crate_output.temp_path_for_cgu(output_type, &module.name);
531let output = crate_output.path(output_type);
532if !output_type.is_text_output() && output.is_tty() {
533sess.dcx().emit_err(diagnostics::BinaryOutputToTty {
534 shorthand: output_type.shorthand(),
535 });
536 } else {
537copy_gracefully(&path, &output);
538 }
539if !sess.opts.cg.save_temps && !keep_numbered {
540// The user just wants `foo.x`, not `foo.#module-name#.x`.
541ensure_removed(sess.dcx(), &path);
542 }
543 } else {
544if crate_output.outputs.contains_explicit_name(&output_type) {
545// 2) Multiple codegen units, with `--emit foo=some_name`. We have
546 // no good solution for this case, so warn the user.
547sess.dcx().emit_warn(diagnostics::IgnoringEmitPath {
548 extension: output_type.extension(),
549 });
550 } else if crate_output.single_output_file.is_some() {
551// 3) Multiple codegen units, with `-o some_name`. We have
552 // no good solution for this case, so warn the user.
553sess.dcx()
554 .emit_warn(diagnostics::IgnoringOutput { extension: output_type.extension() });
555 } else {
556// 4) Multiple codegen units, but no explicit name. We
557 // just leave the `foo.0.x` files in place.
558 // (We don't have to do any work in this case.)
559}
560 }
561 };
562563// Flag to indicate whether the user explicitly requested bitcode.
564 // Otherwise, we produced it only as a temporary output, and will need
565 // to get rid of it.
566for output_type in crate_output.outputs.keys() {
567match *output_type {
568 OutputType::Bitcode => {
569 user_wants_bitcode = true;
570// Copy to .bc, but always keep the .0.bc. There is a later
571 // check to figure out if we should delete .0.bc files, or keep
572 // them for making an rlib.
573copy_if_one_unit(OutputType::Bitcode, true);
574 }
575 OutputType::ThinLinkBitcode => {
576 copy_if_one_unit(OutputType::ThinLinkBitcode, false);
577 }
578 OutputType::LlvmAssembly => {
579 copy_if_one_unit(OutputType::LlvmAssembly, false);
580 }
581 OutputType::Assembly => {
582 copy_if_one_unit(OutputType::Assembly, false);
583 }
584 OutputType::Object => {
585 user_wants_objects = true;
586 copy_if_one_unit(OutputType::Object, true);
587 }
588 OutputType::Mir | OutputType::Metadata | OutputType::Exe | OutputType::DepInfo => {}
589 }
590 }
591592// Clean up unwanted temporary files.
593594 // We create the following files by default:
595 // - #crate#.#module-name#.rcgu.bc
596 // - #crate#.#module-name#.rcgu.o
597 // - #crate#.o (linked from crate.##.rcgu.o)
598 // - #crate#.bc (copied from crate.##.rcgu.bc)
599 // We may create additional files if requested by the user (through
600 // `-C save-temps` or `--emit=` flags).
601602if !sess.opts.cg.save_temps {
603// Remove the temporary .#module-name#.rcgu.o objects. If the user didn't
604 // explicitly request bitcode (with --emit=bc), and the bitcode is not
605 // needed for building an rlib, then we must remove .#module-name#.bc as
606 // well.
607608 // Specific rules for keeping .#module-name#.rcgu.bc:
609 // - If the user requested bitcode (`user_wants_bitcode`), and
610 // codegen_units > 1, then keep it.
611 // - If the user requested bitcode but codegen_units == 1, then we
612 // can toss .#module-name#.rcgu.bc because we copied it to .bc earlier.
613 // - If we're not building an rlib and the user didn't request
614 // bitcode, then delete .#module-name#.rcgu.bc.
615 // If you change how this works, also update back::link::link_rlib,
616 // where .#module-name#.rcgu.bc files are (maybe) deleted after making an
617 // rlib.
618let needs_crate_object = crate_output.outputs.contains_key(&OutputType::Exe);
619620let keep_numbered_bitcode = user_wants_bitcode && sess.codegen_units().as_usize() > 1;
621622let keep_numbered_objects =
623needs_crate_object || (user_wants_objects && sess.codegen_units().as_usize() > 1);
624625for module in compiled_modules.modules.iter() {
626if !keep_numbered_objects {
627if let Some(ref path) = module.object {
628 ensure_removed(sess.dcx(), path);
629 }
630631if let Some(ref path) = module.global_asm_object {
632 ensure_removed(sess.dcx(), path);
633 }
634635if let Some(ref path) = module.dwarf_object {
636 ensure_removed(sess.dcx(), path);
637 }
638 }
639640if let Some(ref path) = module.bytecode {
641if !keep_numbered_bitcode {
642 ensure_removed(sess.dcx(), path);
643 }
644 }
645 }
646647if !user_wants_bitcode648 && let Some(ref allocator_module) = compiled_modules.allocator_module
649 && let Some(ref path) = allocator_module.bytecode
650 {
651ensure_removed(sess.dcx(), path);
652 }
653 }
654655if sess.opts.json_artifact_notifications {
656if let [module] = &compiled_modules.modules[..] {
657module.for_each_output(|_path, ty| {
658if sess.opts.output_types.contains_key(&ty) {
659let descr = ty.shorthand();
660// for single cgu file is renamed to drop cgu specific suffix
661 // so we regenerate it the same way
662let path = crate_output.path(ty);
663sess.dcx().emit_artifact_notification(path.as_path(), descr);
664 }
665 });
666 } else {
667for module in &compiled_modules.modules {
668 module.for_each_output(|path, ty| {
669if sess.opts.output_types.contains_key(&ty) {
670let descr = ty.shorthand();
671 sess.dcx().emit_artifact_notification(&path, descr);
672 }
673 });
674 }
675 }
676 }
677678// We leave the following files around by default:
679 // - #crate#.o
680 // - #crate#.bc
681 // These are used in linking steps and will be cleaned up afterward.
682}
683684pub(crate) enum WorkItem<B: WriteBackendMethods> {
685/// Optimize a newly codegened, totally unoptimized module.
686Optimize(ModuleCodegen<B::Module>),
687/// Copy the post-LTO artifacts from the incremental cache to the output
688 /// directory.
689CopyPostLtoArtifacts(CachedModuleCodegen),
690}
691692enum ThinLtoWorkItem<B: WriteBackendMethods> {
693/// Copy the post-LTO artifacts from the incremental cache to the output
694 /// directory.
695CopyPostLtoArtifacts(CachedModuleCodegen),
696/// Performs thin-LTO on the given module.
697ThinLto(lto::ThinModule<B>),
698}
699700// `pthread_setname()` on *nix ignores anything beyond the first 15
701// bytes. Use short descriptions to maximize the space available for
702// the module name.
703#[cfg(not(windows))]
704fn desc(short: &str, _long: &str, name: &str) -> String {
705// The short label is three bytes, and is followed by a space. That
706 // leaves 11 bytes for the CGU name. How we obtain those 11 bytes
707 // depends on the CGU name form.
708 //
709 // - Non-incremental, e.g. `regex.f10ba03eb5ec7975-cgu.0`: the part
710 // before the `-cgu.0` is the same for every CGU, so use the
711 // `cgu.0` part. The number suffix will be different for each
712 // CGU.
713 //
714 // - Incremental (normal), e.g. `2i52vvl2hco29us0`: use the whole
715 // name because each CGU will have a unique ASCII hash, and the
716 // first 11 bytes will be enough to identify it.
717 //
718 // - Incremental (with `-Zhuman-readable-cgu-names`), e.g.
719 // `regex.f10ba03eb5ec7975-re_builder.volatile`: use the whole
720 // name. The first 11 bytes won't be enough to uniquely identify
721 // it, but no obvious substring will, and this is a rarely used
722 // option so it doesn't matter much.
723 //
724{
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);
725let name = if let Some(index) = name.find("-cgu.") {
726&name[index + 1..] // +1 skips the leading '-'.
727} else {
728name729 };
730::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} {1}", short, name))
})format!("{short} {name}")731}
732733// Windows has no thread name length limit, so use more descriptive names.
734#[cfg(windows)]
735fn desc(_short: &str, long: &str, name: &str) -> String {
736format!("{long} {name}")
737}
738739impl<B: WriteBackendMethods> WorkItem<B> {
740/// Generate a short description of this work item suitable for use as a thread name.
741fn short_description(&self) -> String {
742match self {
743 WorkItem::Optimize(m) => desc("opt", "optimize module", &m.name),
744 WorkItem::CopyPostLtoArtifacts(m) => desc("cpy", "copy LTO artifacts for", &m.name),
745 }
746 }
747}
748749impl<B: WriteBackendMethods> ThinLtoWorkItem<B> {
750/// Generate a short description of this work item suitable for use as a thread name.
751fn short_description(&self) -> String {
752match self {
753 ThinLtoWorkItem::CopyPostLtoArtifacts(m) => {
754desc("cpy", "copy LTO artifacts for", &m.name)
755 }
756 ThinLtoWorkItem::ThinLto(m) => desc("lto", "thin-LTO module", m.name()),
757 }
758 }
759}
760761/// A result produced by the backend.
762pub(crate) enum WorkItemResult<B: WriteBackendMethods> {
763/// The backend has finished compiling a CGU, nothing more required.
764Finished(CompiledModule),
765766/// The backend has finished compiling a CGU, which now needs to go through
767 /// fat LTO.
768NeedsFatLto(FatLtoInput<B>),
769770/// The backend has finished compiling a CGU, which now needs to go through
771 /// thin LTO.
772NeedsThinLto(String, B::ModuleBuffer),
773}
774775pub enum FatLtoInput<B: WriteBackendMethods> {
776 Serialized { name: String, bitcode_path: PathBuf },
777 InMemory(ModuleCodegen<B::Module>),
778}
779780pub enum ThinLtoInput<B: WriteBackendMethods> {
781 Red { name: String, buffer: SerializedModule<B::ModuleBuffer> },
782 Green { wp: WorkProduct, bitcode_path: PathBuf },
783}
784785/// Actual LTO type we end up choosing based on multiple factors.
786pub(crate) enum ComputedLtoType {
787 No,
788 Thin,
789 Fat,
790}
791792pub(crate) fn compute_per_cgu_lto_type(
793 sess_lto: &Lto,
794 linker_does_lto: bool,
795 sess_crate_types: &[CrateType],
796) -> ComputedLtoType {
797// If the linker does LTO, we don't have to do it. Note that we
798 // keep doing full LTO, if it is requested, as not to break the
799 // assumption that the output will be a single module.
800801 // We ignore a request for full crate graph LTO if the crate type
802 // is only an rlib, as there is no full crate graph to process,
803 // that'll happen later.
804 //
805 // This use case currently comes up primarily for targets that
806 // require LTO so the request for LTO is always unconditionally
807 // passed down to the backend, but we don't actually want to do
808 // anything about it yet until we've got a final product.
809let is_rlib = #[allow(non_exhaustive_omitted_patterns)] match sess_crate_types {
[CrateType::Rlib] => true,
_ => false,
}matches!(sess_crate_types, [CrateType::Rlib]);
810811match sess_lto {
812 Lto::ThinLocalif !linker_does_lto => ComputedLtoType::Thin,
813 Lto::Thinif !linker_does_lto && !is_rlib => ComputedLtoType::Thin,
814 Lto::Fatif !is_rlib => ComputedLtoType::Fat,
815_ => ComputedLtoType::No,
816 }
817}
818819fn execute_optimize_work_item<B: WriteBackendMethods>(
820 cgcx: &CodegenContext,
821 prof: &SelfProfilerRef,
822 shared_emitter: SharedEmitter,
823mut module: ModuleCodegen<B::Module>,
824) -> WorkItemResult<B> {
825let _timer = prof.generic_activity_with_arg("codegen_module_optimize", &*module.name);
826827 B::optimize(cgcx, prof, &shared_emitter, &mut module, &cgcx.module_config);
828829// After we've done the initial round of optimizations we need to
830 // decide whether to synchronously codegen this module or ship it
831 // back to the coordinator thread for further LTO processing (which
832 // has to wait for all the initial modules to be optimized).
833834let lto_type =
835compute_per_cgu_lto_type(&cgcx.lto, cgcx.use_linker_plugin_lto, &cgcx.crate_types);
836837// If we're doing some form of incremental LTO then we need to be sure to
838 // save our module to disk first.
839let bitcode = if cgcx.module_config.emit_pre_lto_bc {
840let filename = pre_lto_bitcode_filename(&module.name);
841cgcx.new_incr_comp_session_dir.as_ref().map(|path| path.join(&filename))
842 } else {
843None844 };
845846match lto_type {
847 ComputedLtoType::No => {
848let module = B::codegen(cgcx, &prof, &shared_emitter, module, &cgcx.module_config);
849 WorkItemResult::Finished(module)
850 }
851 ComputedLtoType::Thin => {
852let thin_buffer = B::serialize_module(module.module_llvm, true);
853if let Some(path) = bitcode {
854 fs::write(&path, thin_buffer.data()).unwrap_or_else(|e| {
855{
::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);
856 });
857 }
858 WorkItemResult::NeedsThinLto(module.name, thin_buffer)
859 }
860 ComputedLtoType::Fat => match bitcode {
861Some(path) => {
862let buffer = B::serialize_module(module.module_llvm, false);
863 fs::write(&path, buffer.data()).unwrap_or_else(|e| {
864{
::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);
865 });
866 WorkItemResult::NeedsFatLto(FatLtoInput::Serialized {
867 name: module.name,
868 bitcode_path: path,
869 })
870 }
871None => WorkItemResult::NeedsFatLto(FatLtoInput::InMemory(module)),
872 },
873 }
874}
875876fn execute_copy_from_cache_work_item(
877 cgcx: &CodegenContext,
878 prof: &SelfProfilerRef,
879 shared_emitter: SharedEmitter,
880 module: CachedModuleCodegen,
881) -> CompiledModule {
882let _timer =
883prof.generic_activity_with_arg("codegen_copy_artifacts_from_incr_cache", &*module.name);
884885let dcx = DiagCtxt::new(Box::new(shared_emitter));
886let dcx = dcx.handle();
887888let incr_comp_session_dir = cgcx.old_incr_comp_session_dir.as_ref().unwrap();
889890let load_from_incr_comp_dir = |output_path: PathBuf, saved_path: &str| {
891let source_file_in_incr_comp_dir = incr_comp_session_dir.join(saved_path);
892{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/8ea38001b9da1d6683ac5ebbc993cac89d3a09df/compiler/rustc_codegen_ssa/src/back/write.rs:892",
"rustc_codegen_ssa::back::write", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/8ea38001b9da1d6683ac5ebbc993cac89d3a09df/compiler/rustc_codegen_ssa/src/back/write.rs"),
::tracing_core::__macro_support::Option::Some(892u32),
::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!(
893"copying preexisting module `{}` from {:?} to {}",
894 module.name,
895 source_file_in_incr_comp_dir,
896 output_path.display()
897 );
898match link_or_copy(&source_file_in_incr_comp_dir, &output_path) {
899Ok(_) => Some(output_path),
900Err(error) => {
901dcx.emit_err(diagnostics::CopyPathBuf {
902 source_file: source_file_in_incr_comp_dir,
903output_path,
904error,
905 });
906None907 }
908 }
909 };
910911let dwarf_object =
912module.source.saved_files.get("dwo").as_ref().and_then(|saved_dwarf_object_file| {
913let dwarf_obj_out = cgcx914 .output_filenames
915 .split_dwarf_path(cgcx.split_debuginfo, cgcx.split_dwarf_kind, &module.name)
916 .expect(
917"saved dwarf object in work product but `split_dwarf_path` returned `None`",
918 );
919load_from_incr_comp_dir(dwarf_obj_out, saved_dwarf_object_file)
920 });
921922let load_from_incr_cache = |perform, output_type: OutputType| {
923if perform {
924let saved_file = module.source.saved_files.get(output_type.extension())?;
925let output_path = cgcx.output_filenames.temp_path_for_cgu(output_type, &module.name);
926load_from_incr_comp_dir(output_path, &saved_file)
927 } else {
928None929 }
930 };
931932let module_config = &cgcx.module_config;
933let should_emit_obj = module_config.emit_obj != EmitObj::None;
934let assembly = load_from_incr_cache(module_config.emit_asm, OutputType::Assembly);
935let llvm_ir = load_from_incr_cache(module_config.emit_ir, OutputType::LlvmAssembly);
936let bytecode = load_from_incr_cache(module_config.emit_bc, OutputType::Bitcode);
937let object = load_from_incr_cache(should_emit_obj, OutputType::Object);
938let global_asm_object =
939if should_emit_obj && let Some(saved_file) = module.source.saved_files.get("asm.o") {
940let output_path = cgcx.output_filenames.temp_path_ext_for_cgu("asm.o", &module.name);
941load_from_incr_comp_dir(output_path, &saved_file)
942 } else {
943None944 };
945if should_emit_obj && object.is_none() {
946dcx.emit_fatal(diagnostics::NoSavedObjectFile { cgu_name: &module.name })
947 }
948949CompiledModule {
950 kind: ModuleKind::Regular,
951 name: module.name,
952object,
953global_asm_object,
954dwarf_object,
955bytecode,
956assembly,
957llvm_ir,
958 }
959}
960961fn do_fat_lto<B: WriteBackendMethods>(
962 sess: &Session,
963 cgcx: &CodegenContext,
964 shared_emitter: SharedEmitter,
965 tm_factory: TargetMachineFactoryFn<B>,
966 exported_symbols_for_lto: &[String],
967 each_linked_rlib_for_lto: &[PathBuf],
968 needs_fat_lto: Vec<FatLtoInput<B>>,
969) -> CompiledModule {
970let _timer = sess.prof.verbose_generic_activity("LLVM_fatlto");
971972let dcx = DiagCtxt::new(Box::new(shared_emitter.clone()));
973let dcx = dcx.handle();
974975check_lto_allowed(&cgcx, dcx);
976977 B::optimize_and_codegen_fat_lto(
978sess,
979cgcx,
980&shared_emitter,
981tm_factory,
982exported_symbols_for_lto,
983each_linked_rlib_for_lto,
984needs_fat_lto,
985 )
986}
987988fn do_thin_lto<B: WriteBackendMethods>(
989 cgcx: &CodegenContext,
990 prof: &SelfProfilerRef,
991 shared_emitter: SharedEmitter,
992 tm_factory: TargetMachineFactoryFn<B>,
993 exported_symbols_for_lto: &[String],
994 each_linked_rlib_for_lto: &[PathBuf],
995 needs_thin_lto: Vec<ThinLtoInput<B>>,
996) -> Vec<CompiledModule> {
997let _timer = prof.verbose_generic_activity("LLVM_thinlto");
998999let dcx = DiagCtxt::new(Box::new(shared_emitter.clone()));
1000let dcx = dcx.handle();
10011002check_lto_allowed(&cgcx, dcx);
10031004let (coordinator_send, coordinator_receive) = channel();
10051006// First up, convert our jobserver into a helper thread so we can use normal
1007 // mpsc channels to manage our messages and such.
1008 // After we've requested tokens then we'll, when we can,
1009 // get tokens on `coordinator_receive` which will
1010 // get managed in the main loop below.
1011 // Note that using `jobserver::Proxy` is not necessary here, the code below always acquires
1012 // tokens before releasing them, so we can never accidentally release the last token
1013 // permanently held by rustc process.
1014let jobserver_helper = cgcx.parallel.map(|_| {
1015let coordinator_send2 = coordinator_send.clone();
1016 jobserver::client()
1017 .into_helper_thread(move |token| {
1018drop(coordinator_send2.send(ThinLtoMessage::Token(token)));
1019 })
1020 .expect("failed to spawn helper thread")
1021 });
10221023let mut work_items = ::alloc::vec::Vec::new()vec![];
10241025// We have LTO work to do. Perform the serial work here of
1026 // figuring out what we're going to LTO and then push a
1027 // bunch of work items onto our queue to do LTO. This all
1028 // happens on the coordinator thread but it's very quick so
1029 // we don't worry about tokens.
1030for (i, (work, cost)) in generate_thin_lto_work::<B>(
1031 cgcx,
1032 prof,
1033 dcx,
1034&exported_symbols_for_lto,
1035&each_linked_rlib_for_lto,
1036 needs_thin_lto,
1037 )
1038 .into_iter()
1039 .enumerate()
1040 {
1041let 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));
1044if let Some(helper) = &jobserver_helper
1045 && i < cgcx.parallel.unwrap().get()
1046 {
1047 helper.request_token();
1048 }
1049 }
10501051let mut codegen_aborted = None;
10521053// These are the Jobserver Tokens we currently hold. Does not include
1054 // the implicit Token the compiler process owns no matter what.
1055let mut tokens = ::alloc::vec::Vec::new()vec![];
10561057// Amount of tokens that are used (including the implicit token).
1058let mut used_token_count = 0;
10591060let mut compiled_modules = ::alloc::vec::Vec::new()vec![];
10611062// 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.
1067loop {
1068if codegen_aborted.is_none() {
1069if used_token_count == 0 && work_items.is_empty() {
1070// All codegen work is done.
1071break;
1072 }
10731074// Spin up what work we can, only doing this while we've got available
1075 // parallelism slots and work left to spawn.
1076while used_token_count < tokens.len() + 1
1077&& let Some((item, _)) = work_items.pop()
1078 {
1079 spawn_thin_lto_work(
1080&cgcx,
1081 prof,
1082 shared_emitter.clone(),
1083 Arc::clone(&tm_factory),
1084 coordinator_send.clone(),
1085 item,
1086 );
1087 used_token_count += 1;
1088 }
1089 } else {
1090// Don't queue up any more work if codegen was aborted, we're
1091 // just waiting for our existing children to finish.
1092if used_token_count == 0 {
1093break;
1094 }
1095 }
10961097// Relinquish accidentally acquired extra tokens. Subtract 1 for the implicit token.
1098tokens.truncate(used_token_count.saturating_sub(1));
10991100match coordinator_receive.recv().unwrap() {
1101// Save the token locally and the next turn of the loop will use
1102 // this to spawn a new unit of work, or it may get dropped
1103 // immediately if we have no more work to spawn.
1104ThinLtoMessage::Token(token) => match token {
1105Ok(token) => {
1106tokens.push(token);
1107 }
1108Err(e) => {
1109let msg = &::alloc::__export::must_use({
::alloc::fmt::format(format_args!("failed to acquire jobserver token: {0}",
e))
})format!("failed to acquire jobserver token: {e}");
1110shared_emitter.fatal(msg);
1111codegen_aborted = Some(FatalError);
1112 }
1113 },
11141115 ThinLtoMessage::WorkItem { result } => {
1116// If a thread exits successfully then we drop a token associated
1117 // with that worker and update our `used_token_count` count.
1118 // We may later re-acquire a token to continue running more work.
1119 // We may also not actually drop a token here if the worker was
1120 // running with an "ephemeral token".
1121used_token_count -= 1;
11221123match result {
1124Ok(compiled_module) => compiled_modules.push(compiled_module),
1125Err(Some(WorkerFatalError)) => {
1126// Like `CodegenAborted`, wait for remaining work to finish.
1127codegen_aborted = Some(FatalError);
1128 }
1129Err(None) => {
1130// If the thread failed that means it panicked, so
1131 // we abort immediately.
1132::rustc_span::macros::bug_impl(None, format_args!("worker thread panicked"),
Location::caller());bug!("worker thread panicked");
1133 }
1134 }
1135 }
1136 }
1137 }
11381139if let Some(codegen_aborted) = codegen_aborted {
1140codegen_aborted.raise();
1141 }
11421143compiled_modules1144}
11451146/// Messages sent to the coordinator.
1147pub(crate) enum Message<B: WriteBackendMethods> {
1148/// A jobserver token has become available. Sent from the jobserver helper
1149 /// thread.
1150Token(io::Result<Acquired>),
11511152/// The backend has finished processing a work item for a codegen unit.
1153 /// Sent from a backend worker thread.
1154WorkItem { result: Result<WorkItemResult<B>, Option<WorkerFatalError>> },
11551156/// The frontend has finished generating something (backend IR or a
1157 /// post-LTO artifact) for a codegen unit, and it should be passed to the
1158 /// backend. Sent from the main thread.
1159CodegenDone { llvm_work_item: WorkItem<B>, cost: u64 },
11601161/// Similar to `CodegenDone`, but for reusing a pre-LTO artifact
1162 /// Sent from the main thread.
1163AddImportOnlyModule { bitcode_path: PathBuf, work_product: WorkProduct },
11641165/// The frontend has finished generating everything for all codegen units.
1166 /// Sent from the main thread.
1167CodegenComplete,
11681169/// Some normal-ish compiler error occurred, and codegen should be wound
1170 /// down. Sent from the main thread.
1171CodegenAborted,
1172}
11731174/// Messages sent to the coordinator.
1175pub(crate) enum ThinLtoMessage {
1176/// A jobserver token has become available. Sent from the jobserver helper
1177 /// thread.
1178Token(io::Result<Acquired>),
11791180/// The backend has finished processing a work item for a codegen unit.
1181 /// Sent from a backend worker thread.
1182WorkItem { result: Result<CompiledModule, Option<WorkerFatalError>> },
1183}
11841185/// A message sent from the coordinator thread to the main thread telling it to
1186/// process another codegen unit.
1187pub struct CguMessage;
11881189// A cut-down version of `rustc_errors::DiagInner` that impls `Send`, which
1190// can be used to send diagnostics from codegen threads to the main thread.
1191// It's missing the following fields from `rustc_errors::DiagInner`.
1192// - `span`: it doesn't impl `Send`.
1193// - `suggestions`: it doesn't impl `Send`, and isn't used for codegen
1194// diagnostics.
1195// - `is_lint`: lints aren't relevant during codegen.
1196// - `emitted_at`: not used for codegen diagnostics.
1197struct Diagnostic {
1198 span: Vec<SpanData>,
1199 level: Level,
1200 messages: Vec<(DiagMessage, Style)>,
1201 code: Option<ErrCode>,
1202 children: Vec<Subdiagnostic>,
1203 args: DiagArgMap,
1204}
12051206// A cut-down version of `rustc_errors::Subdiag` that impls `Send`. It's
1207// missing the following fields from `rustc_errors::Subdiag`.
1208// - `span`: it doesn't impl `Send`.
1209struct Subdiagnostic {
1210 level: Sublevel,
1211 messages: Vec<(DiagMessage, Style)>,
1212}
12131214#[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)]
1215enum MainThreadState {
1216/// Doing nothing.
1217Idle,
12181219/// Doing codegen, i.e. MIR-to-LLVM-IR conversion.
1220Codegenning,
12211222/// Idle, but lending the compiler process's Token to an LLVM thread so it can do useful work.
1223Lending,
1224}
12251226fn start_executing_work<B: WriteBackendMethods>(
1227 backend: B,
1228 tcx: TyCtxt<'_>,
1229 shared_emitter: SharedEmitter,
1230 codegen_worker_send: Sender<CguMessage>,
1231 coordinator_receive: Receiver<Message<B>>,
1232 regular_config: Arc<ModuleConfig>,
1233 allocator_config: Arc<ModuleConfig>,
1234mut allocator_module: Option<ModuleCodegen<B::Module>>,
1235 coordinator_send: Sender<Message<B>>,
1236) -> thread::JoinHandle<Result<MaybeLtoModules<B>, ()>> {
1237let sess = tcx.sess;
1238let prof = sess.prof.clone();
12391240// Compute the set of symbols we need to retain when doing thin local LTO (if we need to)
1241let exported_symbols_for_lto =
1242if sess.lto() == Lto::ThinLocal { lto::exported_symbols_for_lto(tcx, &[]) } else { ::alloc::vec::Vec::new()vec![] };
12431244// First up, convert our jobserver into a helper thread so we can use normal
1245 // mpsc channels to manage our messages and such.
1246 // After we've requested tokens then we'll, when we can,
1247 // get tokens on `coordinator_receive` which will
1248 // get managed in the main loop below.
1249 // Note that using `jobserver::Proxy` is not necessary here, the code below always acquires
1250 // tokens before releasing them, so we can never accidentally release the last token
1251 // permanently held by rustc process.
1252let parallel = match sess.opts.jobs.backend {
1253Some(n) if backend.supports_parallel() => Some(n),
1254_ => None,
1255 };
1256let jobserver_helper = parallel.map(|_| {
1257let coordinator_send2 = coordinator_send.clone();
1258 jobserver::client()
1259 .into_helper_thread(move |token| {
1260drop(coordinator_send2.send(Message::Token::<B>(token)));
1261 })
1262 .expect("failed to spawn helper thread")
1263 });
12641265let opt_level = tcx.backend_optimization_level(());
1266let tm_factory = backend.target_machine_factory(tcx.sess, opt_level);
12671268let remark_dir = if let Some(ref dir) = sess.opts.unstable_opts.remark_dir {
1269let result = fs::create_dir_all(dir).and_then(|_| dir.canonicalize());
1270match result {
1271Ok(dir) => Some(dir),
1272Err(error) => sess.dcx().emit_fatal(ErrorCreatingRemarkDir { error }),
1273 }
1274 } else {
1275None1276 };
12771278let cgcx = CodegenContext {
1279 crate_types: tcx.crate_types().to_vec(),
1280 lto: sess.lto(),
1281 use_linker_plugin_lto: sess.opts.cg.linker_plugin_lto.enabled(),
1282 dylib_lto: sess.opts.unstable_opts.dylib_lto,
1283 prefer_dynamic: sess.opts.cg.prefer_dynamic,
1284 fewer_names: sess.fewer_names(),
1285 save_temps: sess.opts.cg.save_temps,
1286 time_trace: sess.opts.unstable_opts.llvm_time_trace,
1287 remark: sess.opts.cg.remark.clone(),
1288remark_dir,
1289 old_incr_comp_session_dir: tcx1290 .incr_comp_session
1291 .as_ref()
1292 .and_then(|incr_comp_session| incr_comp_session.old_session_directory.as_deref())
1293 .map(ToOwned::to_owned),
1294 new_incr_comp_session_dir: tcx1295 .incr_comp_session
1296 .as_ref()
1297 .map(|incr_comp_session| (&*incr_comp_session.new_session_directory).to_owned()),
1298 output_filenames: Arc::clone(tcx.output_filenames(())),
1299 module_config: regular_config,
1300opt_level,
1301 msvc_imps_needed: msvc_imps_needed(tcx),
1302 is_pe_coff: tcx.sess.target.is_like_windows,
1303 target_can_use_split_dwarf: tcx.sess.target_can_use_split_dwarf(),
1304 target_arch: tcx.sess.target.arch.to_string(),
1305 target_is_like_darwin: tcx.sess.target.is_like_darwin,
1306 target_is_like_aix: tcx.sess.target.is_like_aix,
1307 target_is_like_gpu: tcx.sess.target.is_like_gpu,
1308 split_debuginfo: tcx.sess.split_debuginfo(),
1309 split_dwarf_kind: tcx.sess.opts.unstable_opts.split_dwarf_kind,
1310parallel,
1311 pointer_size: tcx.data_layout.pointer_size(),
1312 };
13131314// This is the "main loop" of parallel work happening for parallel codegen.
1315 // It's here that we manage parallelism, schedule work, and work with
1316 // messages coming from clients.
1317 //
1318 // There are a few environmental pre-conditions that shape how the system
1319 // is set up:
1320 //
1321 // - Error reporting can only happen on the main thread because that's the
1322 // only place where we have access to the compiler `Session`.
1323 // - LLVM work can be done on any thread.
1324 // - Codegen can only happen on the main thread.
1325 // - Each thread doing substantial work must be in possession of a `Token`
1326 // from the `Jobserver`.
1327 // - The compiler process always holds one `Token`. Any additional `Tokens`
1328 // have to be requested from the `Jobserver`.
1329 //
1330 // Error Reporting
1331 // ===============
1332 // The error reporting restriction is handled separately from the rest: We
1333 // set up a `SharedEmitter` that holds an open channel to the main thread.
1334 // When an error occurs on any thread, the shared emitter will send the
1335 // error message to the receiver main thread (`SharedEmitterMain`). The
1336 // main thread will periodically query this error message queue and emit
1337 // any error messages it has received. It might even abort compilation if
1338 // it has received a fatal error. In this case we rely on all other threads
1339 // being torn down automatically with the main thread.
1340 // Since the main thread will often be busy doing codegen work, error
1341 // reporting will be somewhat delayed, since the message queue can only be
1342 // checked in between two work packages.
1343 //
1344 // Work Processing Infrastructure
1345 // ==============================
1346 // The work processing infrastructure knows three major actors:
1347 //
1348 // - the coordinator thread,
1349 // - the main thread, and
1350 // - LLVM worker threads
1351 //
1352 // The coordinator thread is running a message loop. It instructs the main
1353 // thread about what work to do when, and it will spawn off LLVM worker
1354 // threads as open LLVM WorkItems become available.
1355 //
1356 // The job of the main thread is to codegen CGUs into LLVM work packages
1357 // (since the main thread is the only thread that can do this). The main
1358 // thread will block until it receives a message from the coordinator, upon
1359 // which it will codegen one CGU, send it to the coordinator and block
1360 // again. This way the coordinator can control what the main thread is
1361 // doing.
1362 //
1363 // The coordinator keeps a queue of LLVM WorkItems, and when a `Token` is
1364 // available, it will spawn off a new LLVM worker thread and let it process
1365 // a WorkItem. When a LLVM worker thread is done with its WorkItem,
1366 // it will just shut down, which also frees all resources associated with
1367 // the given LLVM module, and sends a message to the coordinator that the
1368 // WorkItem has been completed.
1369 //
1370 // Work Scheduling
1371 // ===============
1372 // The scheduler's goal is to minimize the time it takes to complete all
1373 // work there is, however, we also want to keep memory consumption low
1374 // if possible. These two goals are at odds with each other: If memory
1375 // consumption were not an issue, we could just let the main thread produce
1376 // LLVM WorkItems at full speed, assuring maximal utilization of
1377 // Tokens/LLVM worker threads. However, since codegen is usually faster
1378 // than LLVM processing, the queue of LLVM WorkItems would fill up and each
1379 // WorkItem potentially holds on to a substantial amount of memory.
1380 //
1381 // So the actual goal is to always produce just enough LLVM WorkItems as
1382 // not to starve our LLVM worker threads. That means, once we have enough
1383 // WorkItems in our queue, we can block the main thread, so it does not
1384 // produce more until we need them.
1385 //
1386 // Doing LLVM Work on the Main Thread
1387 // ----------------------------------
1388 // Since the main thread owns the compiler process's implicit `Token`, it is
1389 // wasteful to keep it blocked without doing any work. Therefore, what we do
1390 // in this case is: We spawn off an additional LLVM worker thread that helps
1391 // reduce the queue. The work it is doing corresponds to the implicit
1392 // `Token`. The coordinator will mark the main thread as being busy with
1393 // LLVM work. (The actual work happens on another OS thread but we just care
1394 // about `Tokens`, not actual threads).
1395 //
1396 // When any LLVM worker thread finishes while the main thread is marked as
1397 // "busy with LLVM work", we can do a little switcheroo: We give the Token
1398 // of the just finished thread to the LLVM worker thread that is working on
1399 // behalf of the main thread's implicit Token, thus freeing up the main
1400 // thread again. The coordinator can then again decide what the main thread
1401 // should do. This allows the coordinator to make decisions at more points
1402 // in time.
1403 //
1404 // Striking a Balance between Throughput and Memory Consumption
1405 // ------------------------------------------------------------
1406 // Since our two goals, (1) use as many Tokens as possible and (2) keep
1407 // memory consumption as low as possible, are in conflict with each other,
1408 // we have to find a trade off between them. Right now, the goal is to keep
1409 // all workers busy, which means that no worker should find the queue empty
1410 // when it is ready to start.
1411 // How do we do achieve this? Good question :) We actually never know how
1412 // many `Tokens` are potentially available so it's hard to say how much to
1413 // fill up the queue before switching the main thread to LLVM work. Also we
1414 // currently don't have a means to estimate how long a running LLVM worker
1415 // will still be busy with it's current WorkItem. However, we know the
1416 // maximal count of available Tokens that makes sense (=the number of CPU
1417 // cores), so we can take a conservative guess. The heuristic we use here
1418 // is implemented in the `queue_full_enough()` function.
1419 //
1420 // Some Background on Jobservers
1421 // -----------------------------
1422 // It's worth also touching on the management of parallelism here. We don't
1423 // want to just spawn a thread per work item because while that's optimal
1424 // parallelism it may overload a system with too many threads or violate our
1425 // configuration for the maximum amount of cpu to use for this process. To
1426 // manage this we use the `jobserver` crate.
1427 //
1428 // Job servers are an artifact of GNU make and are used to manage
1429 // parallelism between processes. A jobserver is a glorified IPC semaphore
1430 // basically. Whenever we want to run some work we acquire the semaphore,
1431 // and whenever we're done with that work we release the semaphore. In this
1432 // manner we can ensure that the maximum number of parallel workers is
1433 // capped at any one point in time.
1434 //
1435 // LTO and the coordinator thread
1436 // ------------------------------
1437 //
1438 // The final job the coordinator thread is responsible for is managing LTO
1439 // and how that works. When LTO is requested what we'll do is collect all
1440 // optimized LLVM modules into a local vector on the coordinator. Once all
1441 // modules have been codegened and optimized we hand this to the `lto`
1442 // module for further optimization. The `lto` module will return back a list
1443 // of more modules to work on, which the coordinator will continue to spawn
1444 // work for.
1445 //
1446 // Each LLVM module is automatically sent back to the coordinator for LTO if
1447 // necessary. There's already optimizations in place to avoid sending work
1448 // back to the coordinator if LTO isn't requested.
1449let f = move || {
1450let _profiler = if cgcx.time_trace { B::thread_profiler() } else { Box::new(()) };
14511452// This is where we collect codegen units that have gone all the way
1453 // through codegen and LLVM.
1454let mut compiled_modules = ::alloc::vec::Vec::new()vec![];
1455let mut needs_fat_lto = Vec::new();
1456let mut needs_thin_lto = Vec::new();
1457let mut lto_import_only_modules = Vec::new();
14581459/// Possible state transitions:
1460 /// - Ongoing -> Completed
1461 /// - Ongoing -> Aborted
1462 /// - Completed -> Aborted
1463#[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)]
1464enum CodegenState {
1465 Ongoing,
1466 Completed,
1467 Aborted,
1468 }
1469use CodegenState::*;
1470let mut codegen_state = Ongoing;
14711472// This is the queue of LLVM work items that still need processing.
1473let mut work_items = Vec::<(WorkItem<B>, u64)>::new();
14741475// This are the Jobserver Tokens we currently hold. Does not include
1476 // the implicit Token the compiler process owns no matter what.
1477let mut tokens = Vec::new();
14781479let mut main_thread_state = MainThreadState::Idle;
14801481// How many LLVM worker threads are running while holding a Token. This
1482 // *excludes* any that the main thread is lending a Token to.
1483let mut running_with_own_token = 0;
14841485// How many LLVM worker threads are running in total. This *includes*
1486 // any that the main thread is lending a Token to.
1487let running_with_any_token = |main_thread_state, running_with_own_token| {
1488running_with_own_token1489 + if main_thread_state == MainThreadState::Lending { 1 } else { 0 }
1490 };
14911492let mut llvm_start_time: Option<VerboseTimingGuard<'_>> = None;
14931494if let Some(allocator_module) = &mut allocator_module {
1495 B::optimize(&cgcx, &prof, &shared_emitter, allocator_module, &allocator_config);
1496 }
14971498// Run the message loop while there's still anything that needs message
1499 // processing. Note that as soon as codegen is aborted we simply want to
1500 // wait for all existing work to finish, so many of the conditions here
1501 // only apply if codegen hasn't been aborted as they represent pending
1502 // work to be done.
1503loop {
1504// While there are still CGUs to be codegened, the coordinator has
1505 // to decide how to utilize the compiler processes implicit Token:
1506 // For codegenning more CGU or for running them through LLVM.
1507if codegen_state == Ongoing {
1508if main_thread_state == MainThreadState::Idle {
1509// Compute the number of workers that will be running once we've taken as many
1510 // items from the work queue as we can, plus one for the main thread. It's not
1511 // critically important that we use this instead of just
1512 // `running_with_own_token`, but it prevents the `queue_full_enough` heuristic
1513 // from fluctuating just because a worker finished up and we decreased the
1514 // `running_with_own_token` count, even though we're just going to increase it
1515 // right after this when we put a new worker to work.
1516let extra_tokens = tokens.len().checked_sub(running_with_own_token).unwrap();
1517let additional_running = std::cmp::min(extra_tokens, work_items.len());
1518let anticipated_running = running_with_own_token + additional_running + 1;
15191520if !queue_full_enough(work_items.len(), anticipated_running) {
1521// The queue is not full enough, process more codegen units:
1522if codegen_worker_send.send(CguMessage).is_err() {
1523{
::core::panicking::panic_fmt(format_args!("Could not send CguMessage to main thread"));
}panic!("Could not send CguMessage to main thread")1524 }
1525main_thread_state = MainThreadState::Codegenning;
1526 } else {
1527// The queue is full enough to not let the worker
1528 // threads starve. Use the implicit Token to do some
1529 // LLVM work too.
1530let (item, _) =
1531work_items.pop().expect("queue empty - queue_full_enough() broken?");
1532main_thread_state = MainThreadState::Lending;
1533spawn_work(
1534&cgcx,
1535&prof,
1536shared_emitter.clone(),
1537coordinator_send.clone(),
1538&mut llvm_start_time,
1539item,
1540 );
1541 }
1542 }
1543 } else if codegen_state == Completed {
1544if running_with_any_token(main_thread_state, running_with_own_token) == 0
1545&& work_items.is_empty()
1546 {
1547// All codegen work is done.
1548break;
1549 }
15501551// In this branch, we know that everything has been codegened,
1552 // so it's just a matter of determining whether the implicit
1553 // Token is free to use for LLVM work.
1554match main_thread_state {
1555 MainThreadState::Idle => {
1556if let Some((item, _)) = work_items.pop() {
1557main_thread_state = MainThreadState::Lending;
1558spawn_work(
1559&cgcx,
1560&prof,
1561shared_emitter.clone(),
1562coordinator_send.clone(),
1563&mut llvm_start_time,
1564item,
1565 );
1566 } else {
1567// There is no unstarted work, so let the main thread
1568 // take over for a running worker. Otherwise the
1569 // implicit token would just go to waste.
1570 // We reduce the `running` counter by one. The
1571 // `tokens.truncate()` below will take care of
1572 // giving the Token back.
1573if !(running_with_own_token > 0) {
::core::panicking::panic("assertion failed: running_with_own_token > 0")
};assert!(running_with_own_token > 0);
1574running_with_own_token -= 1;
1575main_thread_state = MainThreadState::Lending;
1576 }
1577 }
1578 MainThreadState::Codegenning => ::rustc_span::macros::bug_impl(None,
format_args!("codegen worker should not be codegenning after codegen was already completed"),
Location::caller())bug!(
1579"codegen worker should not be codegenning after \
1580 codegen was already completed"
1581),
1582 MainThreadState::Lending => {
1583// Already making good use of that token
1584}
1585 }
1586 } else {
1587// Don't queue up any more work if codegen was aborted, we're
1588 // just waiting for our existing children to finish.
1589if !(codegen_state == Aborted) {
::core::panicking::panic("assertion failed: codegen_state == Aborted")
};assert!(codegen_state == Aborted);
1590if running_with_any_token(main_thread_state, running_with_own_token) == 0 {
1591break;
1592 }
1593 }
15941595// Spin up what work we can, only doing this while we've got available
1596 // parallelism slots and work left to spawn.
1597if codegen_state != Aborted {
1598while running_with_own_token < tokens.len()
1599 && let Some((item, _)) = work_items.pop()
1600 {
1601 spawn_work(
1602&cgcx,
1603&prof,
1604 shared_emitter.clone(),
1605 coordinator_send.clone(),
1606&mut llvm_start_time,
1607 item,
1608 );
1609 running_with_own_token += 1;
1610 }
1611 }
16121613// Relinquish accidentally acquired extra tokens.
1614tokens.truncate(running_with_own_token);
16151616match coordinator_receive.recv().unwrap() {
1617// Save the token locally and the next turn of the loop will use
1618 // this to spawn a new unit of work, or it may get dropped
1619 // immediately if we have no more work to spawn.
1620Message::Token(token) => {
1621match token {
1622Ok(token) => {
1623tokens.push(token);
16241625if main_thread_state == MainThreadState::Lending {
1626// If the main thread token is used for LLVM work
1627 // at the moment, we turn that thread into a regular
1628 // LLVM worker thread, so the main thread is free
1629 // to react to codegen demand.
1630main_thread_state = MainThreadState::Idle;
1631running_with_own_token += 1;
1632 }
1633 }
1634Err(e) => {
1635let msg = &::alloc::__export::must_use({
::alloc::fmt::format(format_args!("failed to acquire jobserver token: {0}",
e))
})format!("failed to acquire jobserver token: {e}");
1636shared_emitter.fatal(msg);
1637codegen_state = Aborted;
1638 }
1639 }
1640 }
16411642 Message::CodegenDone { llvm_work_item, cost } => {
1643// We keep the queue sorted by estimated processing cost,
1644 // so that more expensive items are processed earlier. This
1645 // is good for throughput as it gives the main thread more
1646 // time to fill up the queue and it avoids scheduling
1647 // expensive items to the end.
1648 // Note, however, that this is not ideal for memory
1649 // consumption, as LLVM module sizes are not evenly
1650 // distributed.
1651let insertion_index = work_items.binary_search_by_key(&cost, |&(_, cost)| cost);
1652let insertion_index = match insertion_index {
1653Ok(idx) | Err(idx) => idx,
1654 };
1655work_items.insert(insertion_index, (llvm_work_item, cost));
16561657if let Some(helper) = &jobserver_helper1658 && running_with_any_token(main_thread_state, running_with_own_token)
1659 < cgcx.parallel.unwrap().get()
1660 {
1661helper.request_token();
1662 }
1663{
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);
1664main_thread_state = MainThreadState::Idle;
1665 }
16661667 Message::CodegenComplete => {
1668if codegen_state != Aborted {
1669codegen_state = Completed;
1670 }
1671{
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);
1672main_thread_state = MainThreadState::Idle;
1673 }
16741675// If codegen is aborted that means translation was aborted due
1676 // to some normal-ish compiler error. In this situation we want
1677 // to exit as soon as possible, but we want to make sure all
1678 // existing work has finished. Flag codegen as being done, and
1679 // then conditions above will ensure no more work is spawned but
1680 // we'll keep executing this loop until `running_with_own_token`
1681 // hits 0.
1682Message::CodegenAborted => {
1683codegen_state = Aborted;
1684 }
16851686 Message::WorkItem { result } => {
1687// If a thread exits successfully then we drop a token associated
1688 // with that worker and update our `running_with_own_token` count.
1689 // We may later re-acquire a token to continue running more work.
1690 // We may also not actually drop a token here if the worker was
1691 // running with an "ephemeral token".
1692if main_thread_state == MainThreadState::Lending {
1693main_thread_state = MainThreadState::Idle;
1694 } else {
1695running_with_own_token -= 1;
1696 }
16971698match result {
1699Ok(WorkItemResult::Finished(compiled_module)) => {
1700compiled_modules.push(compiled_module);
1701 }
1702Ok(WorkItemResult::NeedsFatLto(fat_lto_input)) => {
1703if !needs_thin_lto.is_empty() {
::core::panicking::panic("assertion failed: needs_thin_lto.is_empty()")
};assert!(needs_thin_lto.is_empty());
1704needs_fat_lto.push(fat_lto_input);
1705 }
1706Ok(WorkItemResult::NeedsThinLto(name, thin_buffer)) => {
1707if !needs_fat_lto.is_empty() {
::core::panicking::panic("assertion failed: needs_fat_lto.is_empty()")
};assert!(needs_fat_lto.is_empty());
1708needs_thin_lto.push(ThinLtoInput::Red {
1709name,
1710 buffer: SerializedModule::Local(thin_buffer),
1711 });
1712 }
1713Err(Some(WorkerFatalError)) => {
1714// Like `CodegenAborted`, wait for remaining work to finish.
1715codegen_state = Aborted;
1716 }
1717Err(None) => {
1718// If the thread failed that means it panicked, so
1719 // we abort immediately.
1720::rustc_span::macros::bug_impl(None, format_args!("worker thread panicked"),
Location::caller());bug!("worker thread panicked");
1721 }
1722 }
1723 }
17241725 Message::AddImportOnlyModule { bitcode_path, work_product } => {
1726{
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);
1727{
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);
1728lto_import_only_modules.push((bitcode_path, work_product));
1729main_thread_state = MainThreadState::Idle;
1730 }
1731 }
1732 }
17331734// Drop to print timings
1735drop(llvm_start_time);
17361737if codegen_state == Aborted {
1738return Err(());
1739 }
17401741drop(codegen_state);
1742drop(tokens);
1743drop(jobserver_helper);
1744if !work_items.is_empty() {
::core::panicking::panic("assertion failed: work_items.is_empty()")
};assert!(work_items.is_empty());
17451746if !needs_fat_lto.is_empty() {
1747if !compiled_modules.is_empty() {
::core::panicking::panic("assertion failed: compiled_modules.is_empty()")
};assert!(compiled_modules.is_empty());
1748if !needs_thin_lto.is_empty() {
::core::panicking::panic("assertion failed: needs_thin_lto.is_empty()")
};assert!(needs_thin_lto.is_empty());
17491750if let Some(allocator_module) = allocator_module.take() {
1751needs_fat_lto.push(FatLtoInput::InMemory(allocator_module));
1752 }
17531754for (bitcode_path, wp) in lto_import_only_modules {
1755 needs_fat_lto.push(FatLtoInput::Serialized { name: wp.cgu_name, bitcode_path })
1756 }
17571758return Ok(MaybeLtoModules::FatLto { cgcx, needs_fat_lto });
1759 } else if !needs_thin_lto.is_empty() || !lto_import_only_modules.is_empty() {
1760if !compiled_modules.is_empty() {
::core::panicking::panic("assertion failed: compiled_modules.is_empty()")
};assert!(compiled_modules.is_empty());
1761if !needs_fat_lto.is_empty() {
::core::panicking::panic("assertion failed: needs_fat_lto.is_empty()")
};assert!(needs_fat_lto.is_empty());
17621763for (bitcode_path, wp) in lto_import_only_modules {
1764 needs_thin_lto.push(ThinLtoInput::Green { wp, bitcode_path })
1765 }
17661767if cgcx.lto == Lto::ThinLocal {
1768compiled_modules.extend(do_thin_lto::<B>(
1769&cgcx,
1770&prof,
1771shared_emitter.clone(),
1772tm_factory,
1773&exported_symbols_for_lto,
1774&[],
1775needs_thin_lto,
1776 ));
1777 } else {
1778if let Some(allocator_module) = allocator_module.take() {
1779let thin_buffer = B::serialize_module(allocator_module.module_llvm, true);
1780needs_thin_lto.push(ThinLtoInput::Red {
1781 name: allocator_module.name,
1782 buffer: SerializedModule::Local(thin_buffer),
1783 });
1784 }
17851786return Ok(MaybeLtoModules::ThinLto { cgcx, needs_thin_lto });
1787 }
1788 }
17891790Ok(MaybeLtoModules::NoLto(CompiledModules {
1791 modules: compiled_modules,
1792 allocator_module: allocator_module.map(|allocator_module| {
1793 B::codegen(&cgcx, &prof, &shared_emitter, allocator_module, &allocator_config)
1794 }),
1795 }))
1796 };
1797return std::thread::Builder::new()
1798 .name("coordinator".to_owned())
1799 .spawn(f)
1800 .expect("failed to spawn coordinator thread");
18011802// A heuristic that determines if we have enough LLVM WorkItems in the
1803 // queue so that the main thread can do LLVM work instead of codegen
1804fn queue_full_enough(items_in_queue: usize, workers_running: usize) -> bool {
1805// This heuristic scales ahead-of-time codegen according to available
1806 // concurrency, as measured by `workers_running`. The idea is that the
1807 // more concurrency we have available, the more demand there will be for
1808 // work items, and the fuller the queue should be kept to meet demand.
1809 // An important property of this approach is that we codegen ahead of
1810 // time only as much as necessary, so as to keep fewer LLVM modules in
1811 // memory at once, thereby reducing memory consumption.
1812 //
1813 // When the number of workers running is less than the max concurrency
1814 // available to us, this heuristic can cause us to instruct the main
1815 // thread to work on an LLVM item (that is, tell it to "LLVM") instead
1816 // of codegen, even though it seems like it *should* be codegenning so
1817 // that we can create more work items and spawn more LLVM workers.
1818 //
1819 // But this is not a problem. When the main thread is told to LLVM,
1820 // according to this heuristic and how work is scheduled, there is
1821 // always at least one item in the queue, and therefore at least one
1822 // pending jobserver token request. If there *is* more concurrency
1823 // available, we will immediately receive a token, which will upgrade
1824 // the main thread's LLVM worker to a real one (conceptually), and free
1825 // up the main thread to codegen if necessary. On the other hand, if
1826 // there isn't more concurrency, then the main thread working on an LLVM
1827 // item is appropriate, as long as the queue is full enough for demand.
1828 //
1829 // Speaking of which, how full should we keep the queue? Probably less
1830 // full than you'd think. A lot has to go wrong for the queue not to be
1831 // full enough and for that to have a negative effect on compile times.
1832 //
1833 // Workers are unlikely to finish at exactly the same time, so when one
1834 // finishes and takes another work item off the queue, we often have
1835 // ample time to codegen at that point before the next worker finishes.
1836 // But suppose that codegen takes so long that the workers exhaust the
1837 // queue, and we have one or more workers that have nothing to work on.
1838 // Well, it might not be so bad. Of all the LLVM modules we create and
1839 // optimize, one has to finish last. It's not necessarily the case that
1840 // by losing some concurrency for a moment, we delay the point at which
1841 // that last LLVM module is finished and the rest of compilation can
1842 // proceed. Also, when we can't take advantage of some concurrency, we
1843 // give tokens back to the job server. That enables some other rustc to
1844 // potentially make use of the available concurrency. That could even
1845 // *decrease* overall compile time if we're lucky. But yes, if no other
1846 // rustc can make use of the concurrency, then we've squandered it.
1847 //
1848 // However, keeping the queue full is also beneficial when we have a
1849 // surge in available concurrency. Then items can be taken from the
1850 // queue immediately, without having to wait for codegen.
1851 //
1852 // So, the heuristic below tries to keep one item in the queue for every
1853 // four running workers. Based on limited benchmarking, this appears to
1854 // be more than sufficient to avoid increasing compilation times.
1855let quarter_of_workers = workers_running - 3 * workers_running / 4;
1856items_in_queue > 0 && items_in_queue >= quarter_of_workers1857 }
1858}
18591860/// `FatalError` is explicitly not `Send`.
1861#[must_use]
1862pub(crate) struct WorkerFatalError;
18631864fn spawn_work<'a, B: WriteBackendMethods>(
1865 cgcx: &CodegenContext,
1866 prof: &'a SelfProfilerRef,
1867 shared_emitter: SharedEmitter,
1868 coordinator_send: Sender<Message<B>>,
1869 llvm_start_time: &mut Option<VerboseTimingGuard<'a>>,
1870 work: WorkItem<B>,
1871) {
1872if llvm_start_time.is_none() {
1873*llvm_start_time = Some(prof.verbose_generic_activity("LLVM_passes"));
1874 }
18751876let cgcx = cgcx.clone();
1877let prof = prof.clone();
18781879let name = work.short_description();
1880let f = move || {
1881let _profiler = if cgcx.time_trace { B::thread_profiler() } else { Box::new(()) };
18821883let result = std::panic::catch_unwind(AssertUnwindSafe(|| match work {
1884 WorkItem::Optimize(m) => execute_optimize_work_item(&cgcx, &prof, shared_emitter, m),
1885 WorkItem::CopyPostLtoArtifacts(m) => WorkItemResult::Finished(
1886execute_copy_from_cache_work_item(&cgcx, &prof, shared_emitter, m),
1887 ),
1888 }));
18891890let msg = match result {
1891Ok(result) => Message::WorkItem::<B> { result: Ok(result) },
18921893// We ignore any `FatalError` coming out of `execute_work_item`, as a
1894 // diagnostic was already sent off to the main thread - just surface
1895 // that there was an error in this worker.
1896Err(err) if err.is::<FatalErrorMarker>() => {
1897 Message::WorkItem::<B> { result: Err(Some(WorkerFatalError)) }
1898 }
18991900Err(_) => Message::WorkItem::<B> { result: Err(None) },
1901 };
1902drop(coordinator_send.send(msg));
1903 };
1904 std::thread::Builder::new().name(name).spawn(f).expect("failed to spawn work thread");
1905}
19061907fn spawn_thin_lto_work<B: WriteBackendMethods>(
1908 cgcx: &CodegenContext,
1909 prof: &SelfProfilerRef,
1910 shared_emitter: SharedEmitter,
1911 tm_factory: TargetMachineFactoryFn<B>,
1912 coordinator_send: Sender<ThinLtoMessage>,
1913 work: ThinLtoWorkItem<B>,
1914) {
1915let cgcx = cgcx.clone();
1916let prof = prof.clone();
19171918let name = work.short_description();
1919let f = move || {
1920let _profiler = if cgcx.time_trace { B::thread_profiler() } else { Box::new(()) };
19211922let result = std::panic::catch_unwind(AssertUnwindSafe(|| match work {
1923 ThinLtoWorkItem::CopyPostLtoArtifacts(m) => {
1924execute_copy_from_cache_work_item(&cgcx, &prof, shared_emitter, m)
1925 }
1926 ThinLtoWorkItem::ThinLto(m) => {
1927let _timer = prof.generic_activity_with_arg("codegen_module_perform_lto", m.name());
1928 B::optimize_and_codegen_thin(&cgcx, &prof, &shared_emitter, tm_factory, m)
1929 }
1930 }));
19311932let msg = match result {
1933Ok(result) => ThinLtoMessage::WorkItem { result: Ok(result) },
19341935// We ignore any `FatalError` coming out of `execute_work_item`, as a
1936 // diagnostic was already sent off to the main thread - just surface
1937 // that there was an error in this worker.
1938Err(err) if err.is::<FatalErrorMarker>() => {
1939 ThinLtoMessage::WorkItem { result: Err(Some(WorkerFatalError)) }
1940 }
19411942Err(_) => ThinLtoMessage::WorkItem { result: Err(None) },
1943 };
1944drop(coordinator_send.send(msg));
1945 };
1946 std::thread::Builder::new().name(name).spawn(f).expect("failed to spawn work thread");
1947}
19481949enum SharedEmitterMessage {
1950 Diagnostic(Diagnostic),
1951 InlineAsmError(InlineAsmError),
1952 Fatal(String),
1953}
19541955pub struct InlineAsmError {
1956pub span: SpanData,
1957pub msg: String,
1958pub level: Level,
1959pub source: Option<(String, Vec<InnerSpan>)>,
1960}
19611962#[derive(#[automatically_derived]
impl ::core::clone::Clone for SharedEmitter {
#[inline]
fn clone(&self) -> Self {
SharedEmitter { sender: ::core::clone::Clone::clone(&self.sender) }
}
}Clone)]
1963pub struct SharedEmitter {
1964 sender: Sender<SharedEmitterMessage>,
1965}
19661967pub struct SharedEmitterMain {
1968 receiver: Receiver<SharedEmitterMessage>,
1969}
19701971impl SharedEmitter {
1972fn new() -> (SharedEmitter, SharedEmitterMain) {
1973let (sender, receiver) = channel();
19741975 (SharedEmitter { sender }, SharedEmitterMain { receiver })
1976 }
19771978pub fn inline_asm_error(&self, err: InlineAsmError) {
1979drop(self.sender.send(SharedEmitterMessage::InlineAsmError(err)));
1980 }
19811982fn fatal(&self, msg: &str) {
1983drop(self.sender.send(SharedEmitterMessage::Fatal(msg.to_string())));
1984 }
1985}
19861987impl Emitterfor SharedEmitter {
1988fn emit_diagnostic(&mut self, mut diag: rustc_errors::DiagInner) {
1989// Check that we aren't missing anything interesting when converting to
1990 // the cut-down local `DiagInner`.
1991if !!diag.span.has_span_labels() {
::core::panicking::panic("assertion failed: !diag.span.has_span_labels()")
};assert!(!diag.span.has_span_labels());
1992{
match (&diag.suggestions, &Suggestions::Enabled(::alloc::vec::Vec::new()))
{
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(diag.suggestions, Suggestions::Enabled(vec![]));
1993{
match (&diag.is_lint, &None) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(diag.is_lint, None);
1994// No sensible check for `diag.emitted_at`.
19951996let args = mem::take(&mut diag.args);
1997drop(
1998self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
1999 span: diag.span.primary_spans().iter().map(|span| span.data()).collect::<Vec<_>>(),
2000 level: diag.level(),
2001 messages: diag.messages,
2002 code: diag.code,
2003 children: diag2004 .children
2005 .into_iter()
2006 .map(|child| Subdiagnostic { level: child.level, messages: child.messages })
2007 .collect(),
2008args,
2009 })),
2010 );
2011 }
20122013fn source_map(&self) -> Option<&SourceMap> {
2014None2015 }
2016}
20172018impl SharedEmitterMain {
2019fn check(&self, sess: &Session, blocking: bool) {
2020loop {
2021let message = if blocking {
2022match self.receiver.recv() {
2023Ok(message) => Ok(message),
2024Err(_) => Err(()),
2025 }
2026 } else {
2027match self.receiver.try_recv() {
2028Ok(message) => Ok(message),
2029Err(_) => Err(()),
2030 }
2031 };
20322033match message {
2034Ok(SharedEmitterMessage::Diagnostic(diag)) => {
2035// The diagnostic has been received on the main thread.
2036 // Convert it back to a full `Diagnostic` and emit.
2037let dcx = sess.dcx();
2038let mut d =
2039 rustc_errors::DiagInner::new_with_messages(diag.level, diag.messages);
2040d.span = MultiSpan::from_spans(
2041diag.span.into_iter().map(|span| span.span()).collect(),
2042 );
2043d.code = diag.code; // may be `None`, that's ok
2044d.children = diag2045 .children
2046 .into_iter()
2047 .map(|sub| rustc_errors::Subdiag {
2048 level: sub.level,
2049 messages: sub.messages,
2050 span: MultiSpan::new(),
2051 })
2052 .collect();
2053d.args = diag.args;
2054dcx.emit_diagnostic(d);
2055sess.dcx().abort_if_errors();
2056 }
2057Ok(SharedEmitterMessage::InlineAsmError(inner)) => {
2058{
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);
2059let mut err = Diag::new(sess.dcx(), inner.level, inner.msg);
2060if !inner.span.is_dummy() {
2061err.span(inner.span.span());
2062 }
20632064// Point to the generated assembly if it is available.
2065if let Some((buffer, spans)) = inner.source {
2066let source = sess2067 .source_map()
2068 .new_source_file(FileName::inline_asm_source_code(&buffer), buffer);
2069let spans: Vec<_> = spans2070 .iter()
2071 .map(|sp| {
2072Span::with_root_ctxt(
2073source.normalized_byte_pos(sp.start as u32),
2074source.normalized_byte_pos(sp.end as u32),
2075 )
2076 })
2077 .collect();
2078err.span_note(spans, "instantiated into assembly here");
2079 }
20802081err.emit();
2082 }
2083Ok(SharedEmitterMessage::Fatal(msg)) => {
2084sess.dcx().fatal(msg);
2085 }
2086Err(_) => {
2087break;
2088 }
2089 }
2090 }
2091 }
2092}
20932094pub struct Coordinator<B: WriteBackendMethods> {
2095 sender: Sender<Message<B>>,
2096 future: Option<thread::JoinHandle<Result<MaybeLtoModules<B>, ()>>>,
2097// Only used for the Message type.
2098phantom: PhantomData<B>,
2099}
21002101impl<B: WriteBackendMethods> Coordinator<B> {
2102fn join(mut self) -> std::thread::Result<Result<MaybeLtoModules<B>, ()>> {
2103self.future.take().unwrap().join()
2104 }
2105}
21062107impl<B: WriteBackendMethods> Dropfor Coordinator<B> {
2108fn drop(&mut self) {
2109if let Some(future) = self.future.take() {
2110// If we haven't joined yet, signal to the coordinator that it should spawn no more
2111 // work, and wait for worker threads to finish.
2112drop(self.sender.send(Message::CodegenAborted::<B>));
2113drop(future.join());
2114 }
2115 }
2116}
21172118pub struct OngoingCodegen<B: WriteBackendMethods> {
2119 backend: B,
2120 output_filenames: Arc<OutputFilenames>,
2121// Field order below is intended to terminate the coordinator thread before two fields below
2122 // drop and prematurely close channels used by coordinator thread. See `Coordinator`'s
2123 // `Drop` implementation for more info.
2124pub(crate) coordinator: Coordinator<B>,
2125 codegen_worker_receive: Receiver<CguMessage>,
2126 shared_emitter_main: SharedEmitterMain,
2127}
21282129impl<B: WriteBackendMethods> OngoingCodegen<B> {
2130pub fn join(
2131self,
2132 sess: &Session,
2133 incr_comp_session: Option<&IncrCompSession>,
2134 crate_info: &CrateInfo,
2135 ) -> (CompiledModules, WorkProductMap) {
2136self.shared_emitter_main.check(sess, true);
21372138let maybe_lto_modules = sess.time("join_worker_thread", || match self.coordinator.join() {
2139Ok(Ok(maybe_lto_modules)) => maybe_lto_modules,
2140Ok(Err(())) => {
2141sess.dcx().abort_if_errors();
2142{
::core::panicking::panic_fmt(format_args!("expected abort due to worker thread errors"));
}panic!("expected abort due to worker thread errors")2143 }
2144Err(_) => {
2145::rustc_span::macros::bug_impl(None,
format_args!("panic during codegen/LLVM phase"), Location::caller());bug!("panic during codegen/LLVM phase");
2146 }
2147 });
21482149sess.dcx().abort_if_errors();
21502151let (shared_emitter, shared_emitter_main) = SharedEmitter::new();
21522153// Catch fatal errors to ensure shared_emitter_main.check() can emit the actual diagnostics
2154let compiled_modules = catch_fatal_errors(|| match maybe_lto_modules {
2155 MaybeLtoModules::NoLto(compiled_modules) => {
2156drop(shared_emitter);
2157compiled_modules2158 }
2159 MaybeLtoModules::FatLto { cgcx, needs_fat_lto } => {
2160let tm_factory = self.backend.target_machine_factory(sess, cgcx.opt_level);
21612162CompiledModules {
2163 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(
2164 sess,
2165&cgcx,
2166 shared_emitter,
2167 tm_factory,
2168&crate_info.exported_symbols_for_lto,
2169&crate_info.each_linked_rlib_file_for_lto,
2170 needs_fat_lto,
2171 )],
2172 allocator_module: None,
2173 }
2174 }
2175 MaybeLtoModules::ThinLto { cgcx, needs_thin_lto } => {
2176let tm_factory = self.backend.target_machine_factory(sess, cgcx.opt_level);
21772178CompiledModules {
2179 modules: do_thin_lto::<B>(
2180&cgcx,
2181&sess.prof,
2182shared_emitter,
2183tm_factory,
2184&crate_info.exported_symbols_for_lto,
2185&crate_info.each_linked_rlib_file_for_lto,
2186needs_thin_lto,
2187 ),
2188 allocator_module: None,
2189 }
2190 }
2191 });
21922193shared_emitter_main.check(sess, true);
21942195sess.dcx().abort_if_errors();
21962197let mut compiled_modules =
2198compiled_modules.expect("fatal error emitted but not sent to SharedEmitter");
21992200// Regardless of what order these modules completed in, report them to
2201 // the backend in the same order every time to ensure that we're handing
2202 // out deterministic results.
2203compiled_modules.modules.sort_by(|a, b| a.name.cmp(&b.name));
22042205let work_products = copy_all_cgu_workproducts_to_incr_comp_cache_dir(
2206sess,
2207incr_comp_session,
2208&compiled_modules,
2209 );
2210produce_final_output_artifacts(sess, &compiled_modules, &self.output_filenames);
22112212 (compiled_modules, work_products)
2213 }
22142215pub(crate) fn codegen_finished(&self, tcx: TyCtxt<'_>) {
2216self.wait_for_signal_to_codegen_item();
2217self.check_for_errors(tcx.sess);
2218drop(self.coordinator.sender.send(Message::CodegenComplete::<B>));
2219 }
22202221pub(crate) fn check_for_errors(&self, sess: &Session) {
2222self.shared_emitter_main.check(sess, false);
2223 }
22242225pub(crate) fn wait_for_signal_to_codegen_item(&self) {
2226match self.codegen_worker_receive.recv() {
2227Ok(CguMessage) => {
2228// Ok to proceed.
2229}
2230Err(_) => {
2231// One of the LLVM threads must have panicked, fall through so
2232 // error handling can be reached.
2233}
2234 }
2235 }
2236}
22372238pub(crate) fn submit_codegened_module_to_llvm<B: WriteBackendMethods>(
2239 coordinator: &Coordinator<B>,
2240 module: ModuleCodegen<B::Module>,
2241 cost: u64,
2242) {
2243let llvm_work_item = WorkItem::Optimize(module);
2244drop(coordinator.sender.send(Message::CodegenDone::<B> { llvm_work_item, cost }));
2245}
22462247pub(crate) fn submit_post_lto_module_to_llvm<B: WriteBackendMethods>(
2248 coordinator: &Coordinator<B>,
2249 module: CachedModuleCodegen,
2250) {
2251let llvm_work_item = WorkItem::CopyPostLtoArtifacts(module);
2252drop(coordinator.sender.send(Message::CodegenDone::<B> { llvm_work_item, cost: 0 }));
2253}
22542255pub(crate) fn submit_pre_lto_module_to_llvm<B: WriteBackendMethods>(
2256 tcx: TyCtxt<'_>,
2257 coordinator: &Coordinator<B>,
2258 module: CachedModuleCodegen,
2259) {
2260let filename = pre_lto_bitcode_filename(&module.name);
2261let old_bitcode_path =
2262in_old_incr_comp_dir_sess(tcx.incr_comp_session.unwrap(), &filename).unwrap();
2263let bitcode_path = in_incr_comp_dir_sess(tcx.incr_comp_session.unwrap(), &filename);
22642265match link_or_copy(&old_bitcode_path, &bitcode_path) {
2266Ok(_) => {}
2267Err(error) => {
2268tcx.sess.dcx().emit_err(diagnostics::CopyPathBuf {
2269 source_file: old_bitcode_path,
2270 output_path: bitcode_path,
2271error,
2272 });
2273return;
2274 }
2275 }
22762277// Schedule the module to be loaded
2278drop(
2279coordinator2280 .sender
2281 .send(Message::AddImportOnlyModule::<B> { bitcode_path, work_product: module.source }),
2282 );
2283}
22842285fn pre_lto_bitcode_filename(module_name: &str) -> String {
2286::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}.{1}", module_name,
PRE_LTO_BC_EXT))
})format!("{module_name}.{PRE_LTO_BC_EXT}")2287}
22882289fn msvc_imps_needed(tcx: TyCtxt<'_>) -> bool {
2290// This should never be true (because it's not supported). If it is true,
2291 // something is wrong with commandline arg validation.
2292if !!(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!(
2293 !(tcx.sess.opts.cg.linker_plugin_lto.enabled()
2294 && tcx.sess.target.is_like_windows
2295 && tcx.sess.opts.cg.prefer_dynamic)
2296 );
22972298// We need to generate _imp__ symbol if we are generating an rlib or we include one
2299 // indirectly from ThinLTO. In theory these are not needed as ThinLTO could resolve
2300 // these, but it currently does not do so.
2301let can_have_static_objects =
2302tcx.sess.lto() == Lto::Thin || tcx.crate_types().contains(&CrateType::Rlib);
23032304tcx.sess.target.is_like_windows &&
2305can_have_static_objects &&
2306// ThinLTO can't handle this workaround in all cases, so we don't
2307 // emit the `__imp_` symbols. Instead we make them unnecessary by disallowing
2308 // dynamic linking when linker plugin LTO is enabled.
2309!tcx.sess.opts.cg.linker_plugin_lto.enabled()
2310}