1use std::marker::PhantomData;
2use std::num::NonZero;
3use std::panic::AssertUnwindSafe;
4use std::path::{Path, PathBuf};
5use std::sync::Arc;
6use std::sync::mpsc::{Receiver, Sender, channel};
7use std::{assert_matches, fs, io, str, thread};
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, DiagCtxt, DiagCtxtHandle, DiagInner, FatalError, FatalErrorMarker, Level,
15catch_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, JobsMode, Lto, OptLevel, OutFileName, OutputFilenames, OutputType, Passes,
27SwitchWithOptPath,
28};
29use rustc_session::{BorrowedIncrCompSession, IncrCompSession, Session};
30use rustc_span::source_map::SourceMap;
31use rustc_span::{BytePos, FileName, InnerSpan, Span, SyntaxContext, bug};
32use rustc_structures::CrateType;
33use rustc_target::spec::{MergeFunctions, SanitizerSet};
34use tracing::debug;
3536use crate::back::link::ensure_removed;
37use crate::back::lto::{self, SerializedModule, check_lto_allowed};
38use crate::diagnostics::ErrorCreatingRemarkDir;
39use crate::traits::*;
40use crate::{
41CachedModuleCodegen, CompiledModule, CompiledModules, CrateInfo, ModuleCodegen, ModuleKind,
42diagnostics,
43};
4445const PRE_LTO_BC_EXT: &str = "pre-lto.bc";
4647/// What kind of object file to emit.
48#[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)]
49pub enum EmitObj {
50// No object file.
51None,
5253// Just uncompressed llvm bitcode. Provides easy compatibility with
54 // emscripten's ecc compiler, when used as the linker.
55Bitcode,
5657// Object code, possibly augmented with a bitcode section.
58ObjectCode(BitcodeSection),
59}
6061/// What kind of llvm bitcode section to embed in an object file.
62#[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)]
63pub enum BitcodeSection {
64// No bitcode section.
65None,
6667// A full, uncompressed bitcode section.
68Full,
69}
7071/// Module-specific configuration for `optimize_and_codegen`.
72#[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)]
73pub struct ModuleConfig {
74/// Names of additional optimization passes to run.
75pub passes: Vec<String>,
76/// Some(level) to optimize at a certain level, or None to run
77 /// absolutely no optimizations (used for the allocator module).
78pub opt_level: Option<config::OptLevel>,
7980pub pgo_gen: SwitchWithOptPath,
81pub pgo_use: Option<PathBuf>,
82pub pgo_sample_use: Option<PathBuf>,
83pub debug_info_for_profiling: bool,
84pub instrument_coverage: bool,
8586pub sanitizer: SanitizerSet,
87pub sanitizer_cfi_diag: Option<bool>,
88pub sanitizer_cfi_recover: Option<bool>,
89pub sanitizer_recover: SanitizerSet,
90pub sanitizer_dataflow_abilist: Vec<String>,
91pub sanitizer_memory_track_origins: usize,
9293// Flags indicating which outputs to produce.
94pub emit_pre_lto_bc: bool,
95pub emit_bc: bool,
96pub emit_ir: bool,
97pub emit_asm: bool,
98pub emit_obj: EmitObj,
99pub emit_thin_lto_summary: bool,
100101// Miscellaneous flags. These are mostly copied from command-line
102 // options.
103pub verify_llvm_ir: bool,
104pub lint_llvm_ir: bool,
105pub no_prepopulate_passes: bool,
106pub no_builtins: bool,
107pub vectorize_loop: bool,
108pub vectorize_slp: bool,
109pub merge_functions: bool,
110pub emit_lifetime_markers: bool,
111pub llvm_plugins: Vec<String>,
112pub autodiff: Vec<config::AutoDiff>,
113pub autodiff_post_passes: Option<String>,
114pub offload: Vec<config::Offload>,
115}
116117impl ModuleConfig {
118pub(crate) fn new(kind: ModuleKind, tcx: TyCtxt<'_>, no_builtins: bool) -> ModuleConfig {
119// If it's a regular module, use `$regular`, otherwise use `$other`.
120 // `$regular` and `$other` are evaluated lazily.
121macro_rules! if_regular {
122 ($regular: expr, $other: expr) => {
123if let ModuleKind::Regular = kind { $regular } else { $other }
124 };
125 }
126127let sess = tcx.sess;
128let opt_level_and_size = if let ModuleKind::Regular = kind { Some(sess.opts.optimize) } else { None }if_regular!(Some(sess.opts.optimize), None);
129130let save_temps = sess.opts.cg.save_temps;
131132let should_emit_obj = sess.opts.output_types.contains_key(&OutputType::Exe)
133 || match kind {
134 ModuleKind::Regular => sess.opts.output_types.contains_key(&OutputType::Object),
135 ModuleKind::Allocator => false,
136 };
137138let emit_obj = if !should_emit_obj {
139 EmitObj::None140 } else if sess.target.obj_is_bitcode
141 || (sess.opts.cg.linker_plugin_lto.enabled()
142 && (!no_builtins || tcx.sess.is_sanitizer_cfi_enabled()))
143 {
144// This case is selected if the target uses objects as bitcode, or
145 // if linker plugin LTO is enabled. In the linker plugin LTO case
146 // the assumption is that the final link-step will read the bitcode
147 // and convert it to object code. This may be done by either the
148 // native linker or rustc itself.
149 //
150 // By default this branch is skipped for `#![no_builtins]` crates so
151 // they emit native object files (machine code), not LLVM bitcode
152 // objects for the linker (see rust-lang/rust#146133).
153 //
154 // However, when LLVM CFI is enabled (`-Zsanitizer=cfi`), this
155 // breaks LLVM's expected pipeline: LLVM emits `llvm.type.test`
156 // intrinsics and related metadata that must be lowered by LLVM's
157 // `LowerTypeTests` pass before instruction selection during
158 // link-time LTO. Otherwise, `llvm.type.test` intrinsics and related
159 // metadata are not lowered by LLVM's `LowerTypeTests` pass before
160 // reaching the target backend, and LLVM may abort during codegen
161 // (for example in SelectionDAG type legalization) (see
162 // rust-lang/rust#142284).
163 //
164 // Therefore, with `-Clinker-plugin-lto` and `-Zsanitizer=cfi`, a
165 // `#![no_builtins]` crate must still use rustc's `EmitObj::Bitcode`
166 // path (and emit LLVM bitcode in the `.o` for linker-based LTO).
167EmitObj::Bitcode168 } else if need_bitcode_in_object(tcx) || sess.target.requires_lto {
169 EmitObj::ObjectCode(BitcodeSection::Full)
170 } else {
171 EmitObj::ObjectCode(BitcodeSection::None)
172 };
173174ModuleConfig {
175 passes: if let ModuleKind::Regular = kind {
sess.opts.cg.passes.clone()
} else { ::alloc::vec::Vec::new() }if_regular!(sess.opts.cg.passes.clone(), vec![]),
176177 opt_level: opt_level_and_size,
178179 pgo_gen: if let ModuleKind::Regular = kind {
sess.opts.cg.profile_generate.clone()
} else { SwitchWithOptPath::Disabled }if_regular!(
180 sess.opts.cg.profile_generate.clone(),
181 SwitchWithOptPath::Disabled
182 ),
183 pgo_use: if let ModuleKind::Regular = kind {
sess.opts.cg.profile_use.clone()
} else { None }if_regular!(sess.opts.cg.profile_use.clone(), None),
184 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),
185 debug_info_for_profiling: sess.opts.unstable_opts.debuginfo_for_profiling,
186 instrument_coverage: if let ModuleKind::Regular = kind {
sess.instrument_coverage()
} else { false }if_regular!(sess.instrument_coverage(), false),
187188 sanitizer: if let ModuleKind::Regular = kind {
sess.sanitizers()
} else { SanitizerSet::empty() }if_regular!(sess.sanitizers(), SanitizerSet::empty()),
189 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),
190 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),
191 sanitizer_dataflow_abilist: if let ModuleKind::Regular = kind {
sess.opts.unstable_opts.sanitizer_dataflow_abilist.clone()
} else { Vec::new() }if_regular!(
192 sess.opts.unstable_opts.sanitizer_dataflow_abilist.clone(),
193 Vec::new()
194 ),
195 sanitizer_recover: if let ModuleKind::Regular = kind {
sess.opts.unstable_opts.sanitizer_recover
} else { SanitizerSet::empty() }if_regular!(
196 sess.opts.unstable_opts.sanitizer_recover,
197 SanitizerSet::empty()
198 ),
199 sanitizer_memory_track_origins: if let ModuleKind::Regular = kind {
sess.opts.unstable_opts.sanitizer_memory_track_origins
} else { 0 }if_regular!(
200 sess.opts.unstable_opts.sanitizer_memory_track_origins,
2010
202),
203204 emit_pre_lto_bc: if let ModuleKind::Regular = kind {
save_temps || need_pre_lto_bitcode_for_incr_comp(sess)
} else { false }if_regular!(
205 save_temps || need_pre_lto_bitcode_for_incr_comp(sess),
206false
207),
208 emit_bc: if let ModuleKind::Regular = kind {
save_temps || sess.opts.output_types.contains_key(&OutputType::Bitcode)
} else { save_temps }if_regular!(
209 save_temps || sess.opts.output_types.contains_key(&OutputType::Bitcode),
210 save_temps
211 ),
212 emit_ir: if let ModuleKind::Regular = kind {
sess.opts.output_types.contains_key(&OutputType::LlvmAssembly)
} else { false }if_regular!(
213 sess.opts.output_types.contains_key(&OutputType::LlvmAssembly),
214false
215),
216 emit_asm: if let ModuleKind::Regular = kind {
sess.opts.output_types.contains_key(&OutputType::Assembly)
} else { false }if_regular!(
217 sess.opts.output_types.contains_key(&OutputType::Assembly),
218false
219),
220emit_obj,
221 emit_thin_lto_summary: if let ModuleKind::Regular = kind {
sess.opts.output_types.contains_key(&OutputType::ThinLinkBitcode)
} else { false }if_regular!(
222 sess.opts.output_types.contains_key(&OutputType::ThinLinkBitcode),
223false
224),
225226 verify_llvm_ir: sess.verify_llvm_ir(),
227 lint_llvm_ir: sess.opts.unstable_opts.lint_llvm_ir,
228 no_prepopulate_passes: sess.opts.cg.no_prepopulate_passes,
229 no_builtins: no_builtins || sess.target.no_builtins,
230231// Copy what clang does by turning on loop vectorization at O2 and
232 // slp vectorization at O3.
233vectorize_loop: !sess.opts.cg.no_vectorize_loops
234 && (sess.opts.optimize == config::OptLevel::More235 || sess.opts.optimize == config::OptLevel::Aggressive),
236 vectorize_slp: !sess.opts.cg.no_vectorize_slp
237 && sess.opts.optimize == config::OptLevel::Aggressive,
238239// Some targets (namely, NVPTX) interact badly with the
240 // MergeFunctions pass. This is because MergeFunctions can generate
241 // new function calls which may interfere with the target calling
242 // convention; e.g. for the NVPTX target, PTX kernels should not
243 // call other PTX kernels. MergeFunctions can also be configured to
244 // generate aliases instead, but aliases are not supported by some
245 // backends (again, NVPTX). Therefore, allow targets to opt out of
246 // the MergeFunctions pass, but otherwise keep the pass enabled (at
247 // O2 and O3) since it can be useful for reducing code size.
248merge_functions: match sess.merge_functions() {
249 MergeFunctions::Disabled => false,
250 MergeFunctions::Trampolines | MergeFunctions::Aliases => {
251use config::OptLevel::*;
252match sess.opts.optimize {
253Aggressive | More | SizeMin | Size => true,
254Less | No => false,
255 }
256 }
257 },
258259 emit_lifetime_markers: sess.emit_lifetime_markers(),
260 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![]),
261 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![]),
262 autodiff_post_passes: if let ModuleKind::Regular = kind {
sess.opts.unstable_opts.autodiff_post_passes.clone()
} else { None }if_regular!(
263 sess.opts.unstable_opts.autodiff_post_passes.clone(),
264None
265),
266 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![]),
267 }
268 }
269270pub fn bitcode_needed(&self) -> bool {
271self.emit_bc
272 || self.emit_thin_lto_summary
273 || self.emit_obj == EmitObj::Bitcode274 || self.emit_obj == EmitObj::ObjectCode(BitcodeSection::Full)
275 }
276277pub fn embed_bitcode(&self) -> bool {
278self.emit_obj == EmitObj::ObjectCode(BitcodeSection::Full)
279 }
280}
281282/// Configuration passed to the function returned by the `target_machine_factory`.
283pub struct TargetMachineFactoryConfig {
284/// Split DWARF is enabled in LLVM by checking that `TM.MCOptions.SplitDwarfFile` isn't empty,
285 /// so the path to the dwarf object has to be provided when we create the target machine.
286 /// This can be ignored by backends which do not need it for their Split DWARF support.
287pub split_dwarf_file: Option<PathBuf>,
288289/// The name of the output object file. Used for setting OutputFilenames in target options
290 /// so that LLVM can emit the CodeView S_OBJNAME record in pdb files
291pub output_obj_file: Option<PathBuf>,
292}
293294impl TargetMachineFactoryConfig {
295pub fn new(cgcx: &CodegenContext, module_name: &str) -> TargetMachineFactoryConfig {
296let split_dwarf_file = if cgcx.target_can_use_split_dwarf {
297cgcx.output_filenames.split_dwarf_path(
298cgcx.split_debuginfo,
299cgcx.split_dwarf_kind,
300module_name,
301 )
302 } else {
303None304 };
305306let output_obj_file =
307Some(cgcx.output_filenames.temp_path_for_cgu(OutputType::Object, module_name));
308TargetMachineFactoryConfig { split_dwarf_file, output_obj_file }
309 }
310}
311312pub type TargetMachineFactoryFn<B> = Arc<
313dyn Fn(
314DiagCtxtHandle<'_>,
315TargetMachineFactoryConfig,
316 ) -> <B as WriteBackendMethods>::TargetMachine317 + Send318 + Sync,
319>;
320321/// Additional resources used by optimize_and_codegen (not module specific)
322#[derive(#[automatically_derived]impl ::core::clone::Clone for CodegenContext {
#[inline]
fn clone(&self) -> Self {
CodegenContext {
lto: ::core::clone::Clone::clone(&self.lto),
use_linker_plugin_lto: ::core::clone::Clone::clone(&self.use_linker_plugin_lto),
dylib_lto: ::core::clone::Clone::clone(&self.dylib_lto),
prefer_dynamic: ::core::clone::Clone::clone(&self.prefer_dynamic),
save_temps: ::core::clone::Clone::clone(&self.save_temps),
fewer_names: ::core::clone::Clone::clone(&self.fewer_names),
time_trace: ::core::clone::Clone::clone(&self.time_trace),
crate_types: ::core::clone::Clone::clone(&self.crate_types),
output_filenames: ::core::clone::Clone::clone(&self.output_filenames),
module_config: ::core::clone::Clone::clone(&self.module_config),
opt_level: ::core::clone::Clone::clone(&self.opt_level),
msvc_imps_needed: ::core::clone::Clone::clone(&self.msvc_imps_needed),
is_pe_coff: ::core::clone::Clone::clone(&self.is_pe_coff),
target_can_use_split_dwarf: ::core::clone::Clone::clone(&self.target_can_use_split_dwarf),
target_arch: ::core::clone::Clone::clone(&self.target_arch),
target_is_like_darwin: ::core::clone::Clone::clone(&self.target_is_like_darwin),
target_is_like_aix: ::core::clone::Clone::clone(&self.target_is_like_aix),
target_is_like_gpu: ::core::clone::Clone::clone(&self.target_is_like_gpu),
split_debuginfo: ::core::clone::Clone::clone(&self.split_debuginfo),
split_dwarf_kind: ::core::clone::Clone::clone(&self.split_dwarf_kind),
pointer_size: ::core::clone::Clone::clone(&self.pointer_size),
rust_eh_personality_symbol: ::core::clone::Clone::clone(&self.rust_eh_personality_symbol),
remark: ::core::clone::Clone::clone(&self.remark),
remark_dir: ::core::clone::Clone::clone(&self.remark_dir),
parallel: ::core::clone::Clone::clone(&self.parallel),
}
}
}Clone, const _: () =
{
impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
for CodegenContext {
fn encode(&self, __encoder: &mut __E) {
let CodegenContext {
lto: ref __binding_0,
use_linker_plugin_lto: ref __binding_1,
dylib_lto: ref __binding_2,
prefer_dynamic: ref __binding_3,
save_temps: ref __binding_4,
fewer_names: ref __binding_5,
time_trace: ref __binding_6,
crate_types: ref __binding_7,
output_filenames: ref __binding_8,
module_config: ref __binding_9,
opt_level: ref __binding_10,
msvc_imps_needed: ref __binding_11,
is_pe_coff: ref __binding_12,
target_can_use_split_dwarf: ref __binding_13,
target_arch: ref __binding_14,
target_is_like_darwin: ref __binding_15,
target_is_like_aix: ref __binding_16,
target_is_like_gpu: ref __binding_17,
split_debuginfo: ref __binding_18,
split_dwarf_kind: ref __binding_19,
pointer_size: ref __binding_20,
rust_eh_personality_symbol: ref __binding_21,
remark: ref __binding_22,
remark_dir: ref __binding_23,
parallel: ref __binding_24 } = *self;
::rustc_serialize::Encodable::<__E>::encode(__binding_0,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_1,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_2,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_3,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_4,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_5,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_6,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_7,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_8,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_9,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_10,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_11,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_12,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_13,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_14,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_15,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_16,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_17,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_18,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_19,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_20,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_21,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_22,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_23,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_24,
__encoder);
}
}
};Encodable, const _: () =
{
impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
for CodegenContext {
fn decode(__decoder: &mut __D) -> Self {
CodegenContext {
lto: ::rustc_serialize::Decodable::decode(__decoder),
use_linker_plugin_lto: ::rustc_serialize::Decodable::decode(__decoder),
dylib_lto: ::rustc_serialize::Decodable::decode(__decoder),
prefer_dynamic: ::rustc_serialize::Decodable::decode(__decoder),
save_temps: ::rustc_serialize::Decodable::decode(__decoder),
fewer_names: ::rustc_serialize::Decodable::decode(__decoder),
time_trace: ::rustc_serialize::Decodable::decode(__decoder),
crate_types: ::rustc_serialize::Decodable::decode(__decoder),
output_filenames: ::rustc_serialize::Decodable::decode(__decoder),
module_config: ::rustc_serialize::Decodable::decode(__decoder),
opt_level: ::rustc_serialize::Decodable::decode(__decoder),
msvc_imps_needed: ::rustc_serialize::Decodable::decode(__decoder),
is_pe_coff: ::rustc_serialize::Decodable::decode(__decoder),
target_can_use_split_dwarf: ::rustc_serialize::Decodable::decode(__decoder),
target_arch: ::rustc_serialize::Decodable::decode(__decoder),
target_is_like_darwin: ::rustc_serialize::Decodable::decode(__decoder),
target_is_like_aix: ::rustc_serialize::Decodable::decode(__decoder),
target_is_like_gpu: ::rustc_serialize::Decodable::decode(__decoder),
split_debuginfo: ::rustc_serialize::Decodable::decode(__decoder),
split_dwarf_kind: ::rustc_serialize::Decodable::decode(__decoder),
pointer_size: ::rustc_serialize::Decodable::decode(__decoder),
rust_eh_personality_symbol: ::rustc_serialize::Decodable::decode(__decoder),
remark: ::rustc_serialize::Decodable::decode(__decoder),
remark_dir: ::rustc_serialize::Decodable::decode(__decoder),
parallel: ::rustc_serialize::Decodable::decode(__decoder),
}
}
}
};Decodable)]
323pub struct CodegenContext {
324// Resources needed when running LTO
325pub lto: Lto,
326pub use_linker_plugin_lto: bool,
327pub dylib_lto: bool,
328pub prefer_dynamic: bool,
329pub save_temps: bool,
330pub fewer_names: bool,
331pub time_trace: bool,
332pub crate_types: Vec<CrateType>,
333pub output_filenames: Arc<OutputFilenames>,
334pub module_config: Arc<ModuleConfig>,
335pub opt_level: OptLevel,
336pub msvc_imps_needed: bool,
337pub is_pe_coff: bool,
338pub target_can_use_split_dwarf: bool,
339pub target_arch: String,
340pub target_is_like_darwin: bool,
341pub target_is_like_aix: bool,
342pub target_is_like_gpu: bool,
343pub split_debuginfo: rustc_target::spec::SplitDebuginfo,
344pub split_dwarf_kind: rustc_session::config::SplitDwarfKind,
345pub pointer_size: Size,
346pub rust_eh_personality_symbol: String,
347348/// LLVM optimizations for which we want to print remarks.
349pub remark: Passes,
350/// Directory into which should the LLVM optimization remarks be written.
351 /// If `None`, they will be written to stderr.
352pub remark_dir: Option<PathBuf>,
353/// `Some(limit)` if the codegen should be run in parallel.
354 ///
355 /// Depends on [`WriteBackendMethods::supports_parallel()`] and `--jobs-backend`.
356pub parallel: Option<NonZero<usize>>,
357}
358359fn generate_thin_lto_work<B: WriteBackendMethods>(
360 cgcx: &CodegenContext,
361 prof: &SelfProfilerRef,
362 incr_comp_session: Option<&BorrowedIncrCompSession>,
363 dcx: DiagCtxtHandle<'_>,
364 exported_symbols_for_lto: &[String],
365 each_linked_rlib_for_lto: &[PathBuf],
366 needs_thin_lto: Vec<ThinLtoInput<B>>,
367) -> Vec<(ThinLtoWorkItem<B>, u64)> {
368let _prof_timer = prof.generic_activity("codegen_thin_generate_lto_work");
369370let (lto_modules, copy_jobs) = B::run_thin_lto(
371cgcx,
372prof,
373incr_comp_session,
374dcx,
375exported_symbols_for_lto,
376each_linked_rlib_for_lto,
377needs_thin_lto,
378 );
379lto_modules380 .into_iter()
381 .map(|module| {
382let cost = module.cost();
383 (ThinLtoWorkItem::ThinLto(module), cost)
384 })
385 .chain(copy_jobs.into_iter().map(|wp| {
386 (
387 ThinLtoWorkItem::CopyPostLtoArtifacts(CachedModuleCodegen {
388 name: wp.cgu_name.clone(),
389 source: wp,
390 }),
3910, // copying is very cheap
392)
393 }))
394 .collect()
395}
396397enum MaybeLtoModules<B: WriteBackendMethods> {
398 NoLto(CompiledModules),
399 FatLto { cgcx: CodegenContext, needs_fat_lto: Vec<FatLtoInput<B>> },
400 ThinLto { cgcx: CodegenContext, needs_thin_lto: Vec<ThinLtoInput<B>> },
401}
402403fn need_bitcode_in_object(tcx: TyCtxt<'_>) -> bool {
404let sess = tcx.sess;
405sess.opts.cg.embed_bitcode
406 && tcx.crate_types().contains(&CrateType::Rlib)
407 && sess.opts.output_types.contains_key(&OutputType::Exe)
408}
409410fn need_pre_lto_bitcode_for_incr_comp(sess: &Session) -> bool {
411if sess.opts.incremental.is_none() {
412return false;
413 }
414415match sess.lto() {
416 Lto::No => false,
417 Lto::Fat | Lto::Thin | Lto::ThinLocal => true,
418 }
419}
420421pub(crate) fn start_async_codegen<B: WriteBackendMethods>(
422 backend: B,
423 tcx: TyCtxt<'_>,
424 regular_config: Arc<ModuleConfig>,
425 allocator_config: Arc<ModuleConfig>,
426 allocator_module: Option<ModuleCodegen<B::Module>>,
427) -> OngoingCodegen<B> {
428let (coordinator_send, coordinator_receive) = channel();
429430let (shared_emitter, shared_emitter_main) = SharedEmitter::new();
431let (codegen_worker_send, codegen_worker_receive) = channel();
432433let coordinator_thread = start_executing_work(
434backend.clone(),
435tcx,
436shared_emitter,
437codegen_worker_send,
438coordinator_receive,
439regular_config,
440allocator_config,
441allocator_module,
442coordinator_send.clone(),
443 );
444445OngoingCodegen {
446backend,
447448codegen_worker_receive,
449shared_emitter_main,
450 coordinator: Coordinator {
451 sender: coordinator_send,
452 future: Some(coordinator_thread),
453 phantom: PhantomData,
454 },
455 output_filenames: Arc::clone(tcx.output_filenames(())),
456 }
457}
458459fn copy_all_cgu_workproducts_to_incr_comp_cache_dir(
460 sess: &Session,
461 incr_comp_session: Option<&IncrCompSession>,
462 compiled_modules: &CompiledModules,
463) -> WorkProductMap {
464let mut work_products = WorkProductMap::default();
465466if sess.opts.incremental.is_none() || sess.opts.unstable_opts.disable_incr_comp_backend_caching
467 {
468return work_products;
469 }
470471let _timer = sess.timer("copy_all_cgu_workproducts_to_incr_comp_cache_dir");
472473for module in compiled_modules.modules.iter().filter(|m| m.kind == ModuleKind::Regular) {
474let mut files = Vec::new();
475if let Some(object_file_path) = &module.object {
476 files.push((OutputType::Object.extension(), object_file_path.as_path()));
477 }
478if let Some(global_asm_object_file_path) = &module.global_asm_object {
479 files.push(("asm.o", global_asm_object_file_path.as_path()));
480 }
481if let Some(dwarf_object_file_path) = &module.dwarf_object {
482 files.push(("dwo", dwarf_object_file_path.as_path()));
483 }
484if let Some(path) = &module.assembly {
485 files.push((OutputType::Assembly.extension(), path.as_path()));
486 }
487if let Some(path) = &module.llvm_ir {
488 files.push((OutputType::LlvmAssembly.extension(), path.as_path()));
489 }
490if let Some(path) = &module.bytecode {
491 files.push((OutputType::Bitcode.extension(), path.as_path()));
492 }
493let (id, product) = copy_cgu_workproduct_to_incr_comp_cache_dir(
494 sess,
495 incr_comp_session.unwrap(),
496&module.name,
497 files.as_slice(),
498 );
499 work_products.insert(id, product);
500 }
501502work_products503}
504505pub fn produce_final_output_artifacts(
506 sess: &Session,
507 compiled_modules: &CompiledModules,
508 crate_output: &OutputFilenames,
509) {
510let mut user_wants_bitcode = false;
511let mut user_wants_objects = false;
512513// Produce final compile outputs.
514let copy_gracefully = |from: &Path, to: &OutFileName| match to {
515 OutFileName::Stdoutif let Err(e) = copy_to_stdout(from) => {
516sess.dcx().emit_err(diagnostics::CopyPath::new(from, to.as_path(), e));
517 }
518 OutFileName::Real(path) if let Err(e) = fs::copy(from, path) => {
519sess.dcx().emit_err(diagnostics::CopyPath::new(from, path, e));
520 }
521_ => {}
522 };
523524let copy_if_one_unit = |output_type: OutputType, keep_numbered: bool| {
525if let [module] = &compiled_modules.modules[..] {
526// 1) Only one codegen unit. In this case it's no difficulty
527 // to copy `foo.0.x` to `foo.x`.
528let path = crate_output.temp_path_for_cgu(output_type, &module.name);
529let output = crate_output.path(output_type);
530if !output_type.is_text_output() && output.is_tty() {
531sess.dcx().emit_err(diagnostics::BinaryOutputToTty {
532 shorthand: output_type.shorthand(),
533 });
534 } else {
535copy_gracefully(&path, &output);
536 }
537if !sess.opts.cg.save_temps && !keep_numbered {
538// The user just wants `foo.x`, not `foo.#module-name#.x`.
539ensure_removed(sess.dcx(), &path);
540 }
541 } else {
542if crate_output.outputs.contains_explicit_name(&output_type) {
543// 2) Multiple codegen units, with `--emit foo=some_name`. We have
544 // no good solution for this case, so warn the user.
545sess.dcx().emit_warn(diagnostics::IgnoringEmitPath {
546 extension: output_type.extension(),
547 });
548 } else if crate_output.single_output_file.is_some() {
549// 3) Multiple codegen units, with `-o some_name`. We have
550 // no good solution for this case, so warn the user.
551sess.dcx()
552 .emit_warn(diagnostics::IgnoringOutput { extension: output_type.extension() });
553 } else {
554// 4) Multiple codegen units, but no explicit name. We
555 // just leave the `foo.0.x` files in place.
556 // (We don't have to do any work in this case.)
557}
558 }
559 };
560561// Flag to indicate whether the user explicitly requested bitcode.
562 // Otherwise, we produced it only as a temporary output, and will need
563 // to get rid of it.
564for output_type in crate_output.outputs.keys() {
565match *output_type {
566 OutputType::Bitcode => {
567 user_wants_bitcode = true;
568// Copy to .bc, but always keep the .0.bc. There is a later
569 // check to figure out if we should delete .0.bc files, or keep
570 // them for making an rlib.
571copy_if_one_unit(OutputType::Bitcode, true);
572 }
573 OutputType::ThinLinkBitcode => {
574 copy_if_one_unit(OutputType::ThinLinkBitcode, false);
575 }
576 OutputType::LlvmAssembly => {
577 copy_if_one_unit(OutputType::LlvmAssembly, false);
578 }
579 OutputType::Assembly => {
580 copy_if_one_unit(OutputType::Assembly, false);
581 }
582 OutputType::Object => {
583 user_wants_objects = true;
584 copy_if_one_unit(OutputType::Object, true);
585 }
586 OutputType::Mir | OutputType::Metadata | OutputType::Exe | OutputType::DepInfo => {}
587 }
588 }
589590// Clean up unwanted temporary files.
591592 // We create the following files by default:
593 // - #crate#.#module-name#.rcgu.bc
594 // - #crate#.#module-name#.rcgu.o
595 // - #crate#.o (linked from crate.##.rcgu.o)
596 // - #crate#.bc (copied from crate.##.rcgu.bc)
597 // We may create additional files if requested by the user (through
598 // `-C save-temps` or `--emit=` flags).
599600if !sess.opts.cg.save_temps {
601// Remove the temporary .#module-name#.rcgu.o objects. If the user didn't
602 // explicitly request bitcode (with --emit=bc), and the bitcode is not
603 // needed for building an rlib, then we must remove .#module-name#.bc as
604 // well.
605606 // Specific rules for keeping .#module-name#.rcgu.bc:
607 // - If the user requested bitcode (`user_wants_bitcode`), and
608 // codegen_units > 1, then keep it.
609 // - If the user requested bitcode but codegen_units == 1, then we
610 // can toss .#module-name#.rcgu.bc because we copied it to .bc earlier.
611 // - If we're not building an rlib and the user didn't request
612 // bitcode, then delete .#module-name#.rcgu.bc.
613 // If you change how this works, also update back::link::link_rlib,
614 // where .#module-name#.rcgu.bc files are (maybe) deleted after making an
615 // rlib.
616let needs_crate_object = crate_output.outputs.contains_key(&OutputType::Exe);
617618let keep_numbered_bitcode = user_wants_bitcode && sess.codegen_units().as_usize() > 1;
619620let keep_numbered_objects =
621needs_crate_object || (user_wants_objects && sess.codegen_units().as_usize() > 1);
622623for module in compiled_modules.modules.iter() {
624if !keep_numbered_objects {
625if let Some(ref path) = module.object {
626 ensure_removed(sess.dcx(), path);
627 }
628629if let Some(ref path) = module.global_asm_object {
630 ensure_removed(sess.dcx(), path);
631 }
632633if let Some(ref path) = module.dwarf_object {
634 ensure_removed(sess.dcx(), path);
635 }
636 }
637638if let Some(ref path) = module.bytecode {
639if !keep_numbered_bitcode {
640 ensure_removed(sess.dcx(), path);
641 }
642 }
643 }
644645if !user_wants_bitcode646 && let Some(ref allocator_module) = compiled_modules.allocator_module
647 && let Some(ref path) = allocator_module.bytecode
648 {
649ensure_removed(sess.dcx(), path);
650 }
651 }
652653if sess.opts.json_artifact_notifications {
654if let [module] = &compiled_modules.modules[..] {
655module.for_each_output(|_path, ty| {
656if sess.opts.output_types.contains_key(&ty) {
657let descr = ty.shorthand();
658// for single cgu file is renamed to drop cgu specific suffix
659 // so we regenerate it the same way
660let path = crate_output.path(ty);
661sess.dcx().emit_artifact_notification(path.as_path(), descr);
662 }
663 });
664 } else {
665for module in &compiled_modules.modules {
666 module.for_each_output(|path, ty| {
667if sess.opts.output_types.contains_key(&ty) {
668let descr = ty.shorthand();
669 sess.dcx().emit_artifact_notification(&path, descr);
670 }
671 });
672 }
673 }
674 }
675676// We leave the following files around by default:
677 // - #crate#.o
678 // - #crate#.bc
679 // These are used in linking steps and will be cleaned up afterward.
680}
681682pub(crate) enum WorkItem<B: WriteBackendMethods> {
683/// Optimize a newly codegened, totally unoptimized module.
684Optimize(ModuleCodegen<B::Module>),
685/// Copy the post-LTO artifacts from the incremental cache to the output
686 /// directory.
687CopyPostLtoArtifacts(CachedModuleCodegen),
688}
689690enum ThinLtoWorkItem<B: WriteBackendMethods> {
691/// Copy the post-LTO artifacts from the incremental cache to the output
692 /// directory.
693CopyPostLtoArtifacts(CachedModuleCodegen),
694/// Performs thin-LTO on the given module.
695ThinLto(lto::ThinModule<B>),
696}
697698// `pthread_setname()` on *nix ignores anything beyond the first 15
699// bytes. Use short descriptions to maximize the space available for
700// the module name.
701#[cfg(not(windows))]
702fn desc(short: &str, _long: &str, name: &str) -> String {
703// The short label is three bytes, and is followed by a space. That
704 // leaves 11 bytes for the CGU name. How we obtain those 11 bytes
705 // depends on the CGU name form.
706 //
707 // - Non-incremental, e.g. `regex.f10ba03eb5ec7975-cgu.0`: the part
708 // before the `-cgu.0` is the same for every CGU, so use the
709 // `cgu.0` part. The number suffix will be different for each
710 // CGU.
711 //
712 // - Incremental (normal), e.g. `2i52vvl2hco29us0`: use the whole
713 // name because each CGU will have a unique ASCII hash, and the
714 // first 11 bytes will be enough to identify it.
715 //
716 // - Incremental (with `-Zhuman-readable-cgu-names`), e.g.
717 // `regex.f10ba03eb5ec7975-re_builder.volatile`: use the whole
718 // name. The first 11 bytes won't be enough to uniquely identify
719 // it, but no obvious substring will, and this is a rarely used
720 // option so it doesn't matter much.
721 //
722{
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);
723let name = if let Some(index) = name.find("-cgu.") {
724&name[index + 1..] // +1 skips the leading '-'.
725} else {
726name727 };
728::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} {1}", short, name))
})format!("{short} {name}")729}
730731// Windows has no thread name length limit, so use more descriptive names.
732#[cfg(windows)]
733fn desc(_short: &str, long: &str, name: &str) -> String {
734format!("{long} {name}")
735}
736737impl<B: WriteBackendMethods> WorkItem<B> {
738/// Generate a short description of this work item suitable for use as a thread name.
739fn short_description(&self) -> String {
740match self {
741 WorkItem::Optimize(m) => desc("opt", "optimize module", &m.name),
742 WorkItem::CopyPostLtoArtifacts(m) => desc("cpy", "copy LTO artifacts for", &m.name),
743 }
744 }
745}
746747impl<B: WriteBackendMethods> ThinLtoWorkItem<B> {
748/// Generate a short description of this work item suitable for use as a thread name.
749fn short_description(&self) -> String {
750match self {
751 ThinLtoWorkItem::CopyPostLtoArtifacts(m) => {
752desc("cpy", "copy LTO artifacts for", &m.name)
753 }
754 ThinLtoWorkItem::ThinLto(m) => desc("lto", "thin-LTO module", m.name()),
755 }
756 }
757}
758759/// A result produced by the backend.
760pub(crate) enum WorkItemResult<B: WriteBackendMethods> {
761/// The backend has finished compiling a CGU, nothing more required.
762Finished(CompiledModule),
763764/// The backend has finished compiling a CGU, which now needs to go through
765 /// fat LTO.
766NeedsFatLto(FatLtoInput<B>),
767768/// The backend has finished compiling a CGU, which now needs to go through
769 /// thin LTO.
770NeedsThinLto(String, B::ModuleBuffer),
771}
772773pub enum FatLtoInput<B: WriteBackendMethods> {
774 Serialized { name: String, bitcode_path: PathBuf },
775 InMemory(ModuleCodegen<B::Module>),
776}
777778pub enum ThinLtoInput<B: WriteBackendMethods> {
779 Red { name: String, buffer: SerializedModule<B::ModuleBuffer> },
780 Green { wp: WorkProduct, bitcode_path: PathBuf },
781}
782783/// Actual LTO type we end up choosing based on multiple factors.
784pub(crate) enum ComputedLtoType {
785 No,
786 Thin,
787 Fat,
788}
789790pub(crate) fn compute_per_cgu_lto_type(
791 sess_lto: &Lto,
792 linker_does_lto: bool,
793 sess_crate_types: &[CrateType],
794) -> ComputedLtoType {
795// If the linker does LTO, we don't have to do it. Note that we
796 // keep doing full LTO, if it is requested, as not to break the
797 // assumption that the output will be a single module.
798799 // We ignore a request for full crate graph LTO if the crate type
800 // is only an rlib, as there is no full crate graph to process,
801 // that'll happen later.
802 //
803 // This use case currently comes up primarily for targets that
804 // require LTO so the request for LTO is always unconditionally
805 // passed down to the backend, but we don't actually want to do
806 // anything about it yet until we've got a final product.
807let is_rlib = #[allow(non_exhaustive_omitted_patterns)] match sess_crate_types {
[CrateType::Rlib] => true,
_ => false,
}matches!(sess_crate_types, [CrateType::Rlib]);
808809match sess_lto {
810 Lto::ThinLocalif !linker_does_lto => ComputedLtoType::Thin,
811 Lto::Thinif !linker_does_lto && !is_rlib => ComputedLtoType::Thin,
812 Lto::Fatif !is_rlib => ComputedLtoType::Fat,
813_ => ComputedLtoType::No,
814 }
815}
816817fn execute_optimize_work_item<B: WriteBackendMethods>(
818 cgcx: &CodegenContext,
819 prof: &SelfProfilerRef,
820 new_incr_comp_session_dir: Option<&Path>,
821 shared_emitter: SharedEmitter,
822mut module: ModuleCodegen<B::Module>,
823) -> WorkItemResult<B> {
824let _timer = prof.generic_activity_with_arg("codegen_module_optimize", &*module.name);
825826 B::optimize(cgcx, prof, &shared_emitter, &mut module, &cgcx.module_config);
827828// After we've done the initial round of optimizations we need to
829 // decide whether to synchronously codegen this module or ship it
830 // back to the coordinator thread for further LTO processing (which
831 // has to wait for all the initial modules to be optimized).
832833let lto_type =
834compute_per_cgu_lto_type(&cgcx.lto, cgcx.use_linker_plugin_lto, &cgcx.crate_types);
835836// If we're doing some form of incremental LTO then we need to be sure to
837 // save our module to disk first.
838let bitcode = if cgcx.module_config.emit_pre_lto_bc {
839let filename = pre_lto_bitcode_filename(&module.name);
840new_incr_comp_session_dir.map(|path| path.join(&filename))
841 } else {
842None843 };
844845match lto_type {
846 ComputedLtoType::No => {
847let module = B::codegen(cgcx, &prof, &shared_emitter, module, &cgcx.module_config);
848 WorkItemResult::Finished(module)
849 }
850 ComputedLtoType::Thin => {
851let thin_buffer = B::serialize_module(module.module_llvm, true);
852if let Some(path) = bitcode {
853 fs::write(&path, thin_buffer.data()).unwrap_or_else(|e| {
854{
::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);
855 });
856 }
857 WorkItemResult::NeedsThinLto(module.name, thin_buffer)
858 }
859 ComputedLtoType::Fat => match bitcode {
860Some(path) => {
861let buffer = B::serialize_module(module.module_llvm, false);
862 fs::write(&path, buffer.data()).unwrap_or_else(|e| {
863{
::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);
864 });
865 WorkItemResult::NeedsFatLto(FatLtoInput::Serialized {
866 name: module.name,
867 bitcode_path: path,
868 })
869 }
870None => WorkItemResult::NeedsFatLto(FatLtoInput::InMemory(module)),
871 },
872 }
873}
874875fn execute_copy_from_cache_work_item(
876 cgcx: &CodegenContext,
877 prof: &SelfProfilerRef,
878 old_incr_comp_session_dir: &Path,
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 load_from_incr_comp_dir = |output_path: PathBuf, saved_path: &str| {
889let source_file_in_incr_comp_dir = old_incr_comp_session_dir.join(saved_path);
890{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/0377038f98d734a74468b6b0f48dd1a9351ed328/compiler/rustc_codegen_ssa/src/back/write.rs:890",
"rustc_codegen_ssa::back::write", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/0377038f98d734a74468b6b0f48dd1a9351ed328/compiler/rustc_codegen_ssa/src/back/write.rs"),
::tracing_core::__macro_support::Option::Some(890u32),
::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!(
891"copying preexisting module `{}` from {:?} to {}",
892 module.name,
893 source_file_in_incr_comp_dir,
894 output_path.display()
895 );
896match link_or_copy(&source_file_in_incr_comp_dir, &output_path) {
897Ok(_) => Some(output_path),
898Err(error) => {
899dcx.emit_err(diagnostics::CopyPathBuf {
900 source_file: source_file_in_incr_comp_dir,
901output_path,
902error,
903 });
904None905 }
906 }
907 };
908909let dwarf_object =
910module.source.saved_files.get("dwo").as_ref().and_then(|saved_dwarf_object_file| {
911let dwarf_obj_out = cgcx912 .output_filenames
913 .split_dwarf_path(cgcx.split_debuginfo, cgcx.split_dwarf_kind, &module.name)
914 .expect(
915"saved dwarf object in work product but `split_dwarf_path` returned `None`",
916 );
917load_from_incr_comp_dir(dwarf_obj_out, saved_dwarf_object_file)
918 });
919920let load_from_incr_cache = |perform, output_type: OutputType| {
921if perform {
922let saved_file = module.source.saved_files.get(output_type.extension())?;
923let output_path = cgcx.output_filenames.temp_path_for_cgu(output_type, &module.name);
924load_from_incr_comp_dir(output_path, &saved_file)
925 } else {
926None927 }
928 };
929930let module_config = &cgcx.module_config;
931let should_emit_obj = module_config.emit_obj != EmitObj::None;
932let assembly = load_from_incr_cache(module_config.emit_asm, OutputType::Assembly);
933let llvm_ir = load_from_incr_cache(module_config.emit_ir, OutputType::LlvmAssembly);
934let bytecode = load_from_incr_cache(module_config.emit_bc, OutputType::Bitcode);
935let object = load_from_incr_cache(should_emit_obj, OutputType::Object);
936let global_asm_object =
937if should_emit_obj && let Some(saved_file) = module.source.saved_files.get("asm.o") {
938let output_path = cgcx.output_filenames.temp_path_ext_for_cgu("asm.o", &module.name);
939load_from_incr_comp_dir(output_path, &saved_file)
940 } else {
941None942 };
943if should_emit_obj && object.is_none() {
944dcx.emit_fatal(diagnostics::NoSavedObjectFile { cgu_name: &module.name })
945 }
946947CompiledModule {
948 kind: ModuleKind::Regular,
949 name: module.name,
950object,
951global_asm_object,
952dwarf_object,
953bytecode,
954assembly,
955llvm_ir,
956 }
957}
958959fn do_fat_lto<B: WriteBackendMethods>(
960 sess: &Session,
961 cgcx: &CodegenContext,
962 shared_emitter: SharedEmitter,
963 tm_factory: TargetMachineFactoryFn<B>,
964 exported_symbols_for_lto: &[String],
965 each_linked_rlib_for_lto: &[PathBuf],
966 needs_fat_lto: Vec<FatLtoInput<B>>,
967) -> CompiledModule {
968let _timer = sess.prof.verbose_generic_activity("LLVM_fatlto");
969970let dcx = DiagCtxt::new(Box::new(shared_emitter.clone()));
971let dcx = dcx.handle();
972973check_lto_allowed(&cgcx, dcx);
974975 B::optimize_and_codegen_fat_lto(
976sess,
977cgcx,
978&shared_emitter,
979tm_factory,
980exported_symbols_for_lto,
981each_linked_rlib_for_lto,
982needs_fat_lto,
983 )
984}
985986fn do_thin_lto<B: WriteBackendMethods>(
987 cgcx: &CodegenContext,
988 prof: &SelfProfilerRef,
989 incr_comp_session: Option<BorrowedIncrCompSession>,
990 shared_emitter: SharedEmitter,
991 tm_factory: TargetMachineFactoryFn<B>,
992 exported_symbols_for_lto: &[String],
993 each_linked_rlib_for_lto: &[PathBuf],
994 needs_thin_lto: Vec<ThinLtoInput<B>>,
995 stack_size: usize,
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 incr_comp_session.as_ref(),
1034 dcx,
1035&exported_symbols_for_lto,
1036&each_linked_rlib_for_lto,
1037 needs_thin_lto,
1038 )
1039 .into_iter()
1040 .enumerate()
1041 {
1042let insertion_index =
1043 work_items.binary_search_by_key(&cost, |&(_, cost)| cost).unwrap_or_else(|e| e);
1044 work_items.insert(insertion_index, (work, cost));
1045if let Some(helper) = &jobserver_helper
1046 && i < cgcx.parallel.unwrap().get()
1047 {
1048 helper.request_token();
1049 }
1050 }
10511052let mut codegen_aborted = None;
10531054// These are the Jobserver Tokens we currently hold. Does not include
1055 // the implicit Token the compiler process owns no matter what.
1056let mut tokens = ::alloc::vec::Vec::new()vec![];
10571058// Amount of tokens that are used (including the implicit token).
1059let mut used_token_count = 0;
10601061let mut compiled_modules = ::alloc::vec::Vec::new()vec![];
10621063// Run the message loop while there's still anything that needs message
1064 // processing. Note that as soon as codegen is aborted we simply want to
1065 // wait for all existing work to finish, so many of the conditions here
1066 // only apply if codegen hasn't been aborted as they represent pending
1067 // work to be done.
1068loop {
1069if codegen_aborted.is_none() {
1070if used_token_count == 0 && work_items.is_empty() {
1071// All codegen work is done.
1072break;
1073 }
10741075// Spin up what work we can, only doing this while we've got available
1076 // parallelism slots and work left to spawn.
1077while used_token_count < tokens.len() + 1
1078&& let Some((item, _)) = work_items.pop()
1079 {
1080 spawn_thin_lto_work(
1081&cgcx,
1082 prof,
1083 incr_comp_session
1084 .as_ref()
1085 .and_then(|incr_comp_session| {
1086 incr_comp_session.old_session_directory.as_deref()
1087 })
1088 .map(ToOwned::to_owned),
1089 shared_emitter.clone(),
1090 Arc::clone(&tm_factory),
1091 coordinator_send.clone(),
1092 item,
1093 stack_size,
1094 );
1095 used_token_count += 1;
1096 }
1097 } else {
1098// Don't queue up any more work if codegen was aborted, we're
1099 // just waiting for our existing children to finish.
1100if used_token_count == 0 {
1101break;
1102 }
1103 }
11041105// Relinquish accidentally acquired extra tokens. Subtract 1 for the implicit token.
1106tokens.truncate(used_token_count.saturating_sub(1));
11071108match coordinator_receive.recv().unwrap() {
1109// Save the token locally and the next turn of the loop will use
1110 // this to spawn a new unit of work, or it may get dropped
1111 // immediately if we have no more work to spawn.
1112ThinLtoMessage::Token(token) => match token {
1113Ok(token) => {
1114tokens.push(token);
1115 }
1116Err(e) => {
1117let msg = &::alloc::__export::must_use({
::alloc::fmt::format(format_args!("failed to acquire jobserver token: {0}",
e))
})format!("failed to acquire jobserver token: {e}");
1118shared_emitter.fatal(msg);
1119codegen_aborted = Some(FatalError);
1120 }
1121 },
11221123 ThinLtoMessage::WorkItem { result } => {
1124// If a thread exits successfully then we drop a token associated
1125 // with that worker and update our `used_token_count` count.
1126 // We may later re-acquire a token to continue running more work.
1127 // We may also not actually drop a token here if the worker was
1128 // running with an "ephemeral token".
1129used_token_count -= 1;
11301131match result {
1132Ok(compiled_module) => compiled_modules.push(compiled_module),
1133Err(Some(WorkerFatalError)) => {
1134// Like `CodegenAborted`, wait for remaining work to finish.
1135codegen_aborted = Some(FatalError);
1136 }
1137Err(None) => {
1138// If the thread failed that means it panicked, so
1139 // we abort immediately.
1140::rustc_span::macros::bug_impl(None, format_args!("worker thread panicked"),
Location::caller());bug!("worker thread panicked");
1141 }
1142 }
1143 }
1144 }
1145 }
11461147if let Some(codegen_aborted) = codegen_aborted {
1148codegen_aborted.raise();
1149 }
11501151compiled_modules1152}
11531154/// Messages sent to the coordinator.
1155pub(crate) enum Message<B: WriteBackendMethods> {
1156/// A jobserver token has become available. Sent from the jobserver helper
1157 /// thread.
1158Token(io::Result<Acquired>),
11591160/// The backend has finished processing a work item for a codegen unit.
1161 /// Sent from a backend worker thread.
1162WorkItem { result: Result<WorkItemResult<B>, Option<WorkerFatalError>> },
11631164/// The frontend has finished generating something (backend IR or a
1165 /// post-LTO artifact) for a codegen unit, and it should be passed to the
1166 /// backend. Sent from the main thread.
1167CodegenDone { llvm_work_item: WorkItem<B>, cost: u64 },
11681169/// Similar to `CodegenDone`, but for reusing a pre-LTO artifact
1170 /// Sent from the main thread.
1171AddImportOnlyModule { bitcode_path: PathBuf, work_product: WorkProduct },
11721173/// The frontend has finished generating everything for all codegen units.
1174 /// Sent from the main thread.
1175CodegenComplete,
11761177/// Some normal-ish compiler error occurred, and codegen should be wound
1178 /// down. Sent from the main thread.
1179CodegenAborted,
1180}
11811182/// Messages sent to the coordinator.
1183pub(crate) enum ThinLtoMessage {
1184/// A jobserver token has become available. Sent from the jobserver helper
1185 /// thread.
1186Token(io::Result<Acquired>),
11871188/// The backend has finished processing a work item for a codegen unit.
1189 /// Sent from a backend worker thread.
1190WorkItem { result: Result<CompiledModule, Option<WorkerFatalError>> },
1191}
11921193/// A message sent from the coordinator thread to the main thread telling it to
1194/// process another codegen unit.
1195pub struct CguMessage;
11961197#[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)]
1198enum MainThreadState {
1199/// Doing nothing.
1200Idle,
12011202/// Doing codegen, i.e. MIR-to-LLVM-IR conversion.
1203Codegenning,
12041205/// Idle, but lending the compiler process's Token to an LLVM thread so it can do useful work.
1206Lending,
1207}
12081209fn start_executing_work<B: WriteBackendMethods>(
1210 backend: B,
1211 tcx: TyCtxt<'_>,
1212 shared_emitter: SharedEmitter,
1213 codegen_worker_send: Sender<CguMessage>,
1214 coordinator_receive: Receiver<Message<B>>,
1215 regular_config: Arc<ModuleConfig>,
1216 allocator_config: Arc<ModuleConfig>,
1217mut allocator_module: Option<ModuleCodegen<B::Module>>,
1218 coordinator_send: Sender<Message<B>>,
1219) -> thread::JoinHandle<Result<MaybeLtoModules<B>, ()>> {
1220let sess = tcx.sess;
1221let prof = sess.prof.clone();
1222let incr_comp_session =
1223tcx.incr_comp_session.map(|incr_comp_session| incr_comp_session.borrow());
12241225// Compute the set of symbols we need to retain when doing thin local LTO (if we need to)
1226let exported_symbols_for_lto =
1227if sess.lto() == Lto::ThinLocal { lto::exported_symbols_for_lto(tcx, &[]) } else { ::alloc::vec::Vec::new()vec![] };
12281229// First up, convert our jobserver into a helper thread so we can use normal
1230 // mpsc channels to manage our messages and such.
1231 // After we've requested tokens then we'll, when we can,
1232 // get tokens on `coordinator_receive` which will
1233 // get managed in the main loop below.
1234 // Note that using `jobserver::Proxy` is not necessary here, the code below always acquires
1235 // tokens before releasing them, so we can never accidentally release the last token
1236 // permanently held by rustc process.
1237let parallel = match sess.opts.jobs.backend {
1238 JobsMode::Parallel(n) if backend.supports_parallel() => Some(n),
1239_ => None,
1240 };
1241let jobserver_helper = parallel.map(|_| {
1242let coordinator_send2 = coordinator_send.clone();
1243 jobserver::client()
1244 .into_helper_thread(move |token| {
1245drop(coordinator_send2.send(Message::Token::<B>(token)));
1246 })
1247 .expect("failed to spawn helper thread")
1248 });
12491250let opt_level = tcx.backend_optimization_level(());
1251let tm_factory = backend.target_machine_factory(tcx.sess, opt_level);
12521253let remark_dir = if let Some(ref dir) = sess.opts.unstable_opts.remark_dir {
1254let result = fs::create_dir_all(dir).and_then(|_| dir.canonicalize());
1255match result {
1256Ok(dir) => Some(dir),
1257Err(error) => sess.dcx().emit_fatal(ErrorCreatingRemarkDir { error }),
1258 }
1259 } else {
1260None1261 };
12621263let stack_size = sess.opts.recommended_stack_size;
12641265let cgcx = CodegenContext {
1266 crate_types: tcx.crate_types().to_vec(),
1267 lto: sess.lto(),
1268 use_linker_plugin_lto: sess.opts.cg.linker_plugin_lto.enabled(),
1269 dylib_lto: sess.opts.unstable_opts.dylib_lto,
1270 prefer_dynamic: sess.opts.cg.prefer_dynamic,
1271 fewer_names: sess.fewer_names(),
1272 save_temps: sess.opts.cg.save_temps,
1273 time_trace: sess.opts.unstable_opts.llvm_time_trace,
1274 remark: sess.opts.cg.remark.clone(),
1275remark_dir,
1276 output_filenames: Arc::clone(tcx.output_filenames(())),
1277 module_config: regular_config,
1278opt_level,
1279 msvc_imps_needed: msvc_imps_needed(tcx),
1280 is_pe_coff: tcx.sess.target.is_like_windows,
1281 target_can_use_split_dwarf: tcx.sess.target_can_use_split_dwarf(),
1282 target_arch: tcx.sess.target.arch.to_string(),
1283 target_is_like_darwin: tcx.sess.target.is_like_darwin,
1284 target_is_like_aix: tcx.sess.target.is_like_aix,
1285 target_is_like_gpu: tcx.sess.target.is_like_gpu,
1286 rust_eh_personality_symbol: rustc_symbol_mangling::eh_personality_symbol(tcx),
1287 split_debuginfo: tcx.sess.split_debuginfo(),
1288 split_dwarf_kind: tcx.sess.opts.unstable_opts.split_dwarf_kind,
1289parallel,
1290 pointer_size: tcx.data_layout.pointer_size(),
1291 };
12921293// This is the "main loop" of parallel work happening for parallel codegen.
1294 // It's here that we manage parallelism, schedule work, and work with
1295 // messages coming from clients.
1296 //
1297 // There are a few environmental pre-conditions that shape how the system
1298 // is set up:
1299 //
1300 // - Error reporting can only happen on the main thread because that's the
1301 // only place where we have access to the compiler `Session`.
1302 // - LLVM work can be done on any thread.
1303 // - Codegen can only happen on the main thread.
1304 // - Each thread doing substantial work must be in possession of a `Token`
1305 // from the `Jobserver`.
1306 // - The compiler process always holds one `Token`. Any additional `Tokens`
1307 // have to be requested from the `Jobserver`.
1308 //
1309 // Error Reporting
1310 // ===============
1311 // The error reporting restriction is handled separately from the rest: We
1312 // set up a `SharedEmitter` that holds an open channel to the main thread.
1313 // When an error occurs on any thread, the shared emitter will send the
1314 // error message to the receiver main thread (`SharedEmitterMain`). The
1315 // main thread will periodically query this error message queue and emit
1316 // any error messages it has received. It might even abort compilation if
1317 // it has received a fatal error. In this case we rely on all other threads
1318 // being torn down automatically with the main thread.
1319 // Since the main thread will often be busy doing codegen work, error
1320 // reporting will be somewhat delayed, since the message queue can only be
1321 // checked in between two work packages.
1322 //
1323 // Work Processing Infrastructure
1324 // ==============================
1325 // The work processing infrastructure knows three major actors:
1326 //
1327 // - the coordinator thread,
1328 // - the main thread, and
1329 // - LLVM worker threads
1330 //
1331 // The coordinator thread is running a message loop. It instructs the main
1332 // thread about what work to do when, and it will spawn off LLVM worker
1333 // threads as open LLVM WorkItems become available.
1334 //
1335 // The job of the main thread is to codegen CGUs into LLVM work packages
1336 // (since the main thread is the only thread that can do this). The main
1337 // thread will block until it receives a message from the coordinator, upon
1338 // which it will codegen one CGU, send it to the coordinator and block
1339 // again. This way the coordinator can control what the main thread is
1340 // doing.
1341 //
1342 // The coordinator keeps a queue of LLVM WorkItems, and when a `Token` is
1343 // available, it will spawn off a new LLVM worker thread and let it process
1344 // a WorkItem. When a LLVM worker thread is done with its WorkItem,
1345 // it will just shut down, which also frees all resources associated with
1346 // the given LLVM module, and sends a message to the coordinator that the
1347 // WorkItem has been completed.
1348 //
1349 // Work Scheduling
1350 // ===============
1351 // The scheduler's goal is to minimize the time it takes to complete all
1352 // work there is, however, we also want to keep memory consumption low
1353 // if possible. These two goals are at odds with each other: If memory
1354 // consumption were not an issue, we could just let the main thread produce
1355 // LLVM WorkItems at full speed, assuring maximal utilization of
1356 // Tokens/LLVM worker threads. However, since codegen is usually faster
1357 // than LLVM processing, the queue of LLVM WorkItems would fill up and each
1358 // WorkItem potentially holds on to a substantial amount of memory.
1359 //
1360 // So the actual goal is to always produce just enough LLVM WorkItems as
1361 // not to starve our LLVM worker threads. That means, once we have enough
1362 // WorkItems in our queue, we can block the main thread, so it does not
1363 // produce more until we need them.
1364 //
1365 // Doing LLVM Work on the Main Thread
1366 // ----------------------------------
1367 // Since the main thread owns the compiler process's implicit `Token`, it is
1368 // wasteful to keep it blocked without doing any work. Therefore, what we do
1369 // in this case is: We spawn off an additional LLVM worker thread that helps
1370 // reduce the queue. The work it is doing corresponds to the implicit
1371 // `Token`. The coordinator will mark the main thread as being busy with
1372 // LLVM work. (The actual work happens on another OS thread but we just care
1373 // about `Tokens`, not actual threads).
1374 //
1375 // When any LLVM worker thread finishes while the main thread is marked as
1376 // "busy with LLVM work", we can do a little switcheroo: We give the Token
1377 // of the just finished thread to the LLVM worker thread that is working on
1378 // behalf of the main thread's implicit Token, thus freeing up the main
1379 // thread again. The coordinator can then again decide what the main thread
1380 // should do. This allows the coordinator to make decisions at more points
1381 // in time.
1382 //
1383 // Striking a Balance between Throughput and Memory Consumption
1384 // ------------------------------------------------------------
1385 // Since our two goals, (1) use as many Tokens as possible and (2) keep
1386 // memory consumption as low as possible, are in conflict with each other,
1387 // we have to find a trade off between them. Right now, the goal is to keep
1388 // all workers busy, which means that no worker should find the queue empty
1389 // when it is ready to start.
1390 // How do we do achieve this? Good question :) We actually never know how
1391 // many `Tokens` are potentially available so it's hard to say how much to
1392 // fill up the queue before switching the main thread to LLVM work. Also we
1393 // currently don't have a means to estimate how long a running LLVM worker
1394 // will still be busy with it's current WorkItem. However, we know the
1395 // maximal count of available Tokens that makes sense (=the number of CPU
1396 // cores), so we can take a conservative guess. The heuristic we use here
1397 // is implemented in the `queue_full_enough()` function.
1398 //
1399 // Some Background on Jobservers
1400 // -----------------------------
1401 // It's worth also touching on the management of parallelism here. We don't
1402 // want to just spawn a thread per work item because while that's optimal
1403 // parallelism it may overload a system with too many threads or violate our
1404 // configuration for the maximum amount of cpu to use for this process. To
1405 // manage this we use the `jobserver` crate.
1406 //
1407 // Job servers are an artifact of GNU make and are used to manage
1408 // parallelism between processes. A jobserver is a glorified IPC semaphore
1409 // basically. Whenever we want to run some work we acquire the semaphore,
1410 // and whenever we're done with that work we release the semaphore. In this
1411 // manner we can ensure that the maximum number of parallel workers is
1412 // capped at any one point in time.
1413 //
1414 // LTO and the coordinator thread
1415 // ------------------------------
1416 //
1417 // The final job the coordinator thread is responsible for is managing LTO
1418 // and how that works. When LTO is requested what we'll do is collect all
1419 // optimized LLVM modules into a local vector on the coordinator. Once all
1420 // modules have been codegened and optimized we hand this to the `lto`
1421 // module for further optimization. The `lto` module will return back a list
1422 // of more modules to work on, which the coordinator will continue to spawn
1423 // work for.
1424 //
1425 // Each LLVM module is automatically sent back to the coordinator for LTO if
1426 // necessary. There's already optimizations in place to avoid sending work
1427 // back to the coordinator if LTO isn't requested.
1428let f = move || {
1429let _profiler = if cgcx.time_trace { B::thread_profiler() } else { Box::new(()) };
14301431// This is where we collect codegen units that have gone all the way
1432 // through codegen and LLVM.
1433let mut compiled_modules = ::alloc::vec::Vec::new()vec![];
1434let mut needs_fat_lto = Vec::new();
1435let mut needs_thin_lto = Vec::new();
1436let mut lto_import_only_modules = Vec::new();
14371438/// Possible state transitions:
1439 /// - Ongoing -> Completed
1440 /// - Ongoing -> Aborted
1441 /// - Completed -> Aborted
1442#[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)]
1443enum CodegenState {
1444 Ongoing,
1445 Completed,
1446 Aborted,
1447 }
1448use CodegenState::*;
1449let mut codegen_state = Ongoing;
14501451// This is the queue of LLVM work items that still need processing.
1452let mut work_items = Vec::<(WorkItem<B>, u64)>::new();
14531454// This are the Jobserver Tokens we currently hold. Does not include
1455 // the implicit Token the compiler process owns no matter what.
1456let mut tokens = Vec::new();
14571458let mut main_thread_state = MainThreadState::Idle;
14591460// How many LLVM worker threads are running while holding a Token. This
1461 // *excludes* any that the main thread is lending a Token to.
1462let mut running_with_own_token = 0;
14631464// How many LLVM worker threads are running in total. This *includes*
1465 // any that the main thread is lending a Token to.
1466let running_with_any_token = |main_thread_state, running_with_own_token| {
1467running_with_own_token1468 + if main_thread_state == MainThreadState::Lending { 1 } else { 0 }
1469 };
14701471let mut llvm_start_time: Option<VerboseTimingGuard<'_>> = None;
14721473if let Some(allocator_module) = &mut allocator_module {
1474 B::optimize(&cgcx, &prof, &shared_emitter, allocator_module, &allocator_config);
1475 }
14761477// Run the message loop while there's still anything that needs message
1478 // processing. Note that as soon as codegen is aborted we simply want to
1479 // wait for all existing work to finish, so many of the conditions here
1480 // only apply if codegen hasn't been aborted as they represent pending
1481 // work to be done.
1482loop {
1483// While there are still CGUs to be codegened, the coordinator has
1484 // to decide how to utilize the compiler processes implicit Token:
1485 // For codegenning more CGU or for running them through LLVM.
1486if codegen_state == Ongoing {
1487if main_thread_state == MainThreadState::Idle {
1488// Compute the number of workers that will be running once we've taken as many
1489 // items from the work queue as we can, plus one for the main thread. It's not
1490 // critically important that we use this instead of just
1491 // `running_with_own_token`, but it prevents the `queue_full_enough` heuristic
1492 // from fluctuating just because a worker finished up and we decreased the
1493 // `running_with_own_token` count, even though we're just going to increase it
1494 // right after this when we put a new worker to work.
1495let extra_tokens = tokens.len().checked_sub(running_with_own_token).unwrap();
1496let additional_running = std::cmp::min(extra_tokens, work_items.len());
1497let anticipated_running = running_with_own_token + additional_running + 1;
14981499if !queue_full_enough(work_items.len(), anticipated_running) {
1500// The queue is not full enough, process more codegen units:
1501if codegen_worker_send.send(CguMessage).is_err() {
1502{
::core::panicking::panic_fmt(format_args!("Could not send CguMessage to main thread"));
}panic!("Could not send CguMessage to main thread")1503 }
1504main_thread_state = MainThreadState::Codegenning;
1505 } else {
1506// The queue is full enough to not let the worker
1507 // threads starve. Use the implicit Token to do some
1508 // LLVM work too.
1509let (item, _) =
1510work_items.pop().expect("queue empty - queue_full_enough() broken?");
1511main_thread_state = MainThreadState::Lending;
1512spawn_work(
1513&cgcx,
1514&prof,
1515incr_comp_session.as_ref(),
1516shared_emitter.clone(),
1517coordinator_send.clone(),
1518&mut llvm_start_time,
1519item,
1520stack_size,
1521 );
1522 }
1523 }
1524 } else if codegen_state == Completed {
1525if running_with_any_token(main_thread_state, running_with_own_token) == 0
1526&& work_items.is_empty()
1527 {
1528// All codegen work is done.
1529break;
1530 }
15311532// In this branch, we know that everything has been codegened,
1533 // so it's just a matter of determining whether the implicit
1534 // Token is free to use for LLVM work.
1535match main_thread_state {
1536 MainThreadState::Idle => {
1537if let Some((item, _)) = work_items.pop() {
1538main_thread_state = MainThreadState::Lending;
1539spawn_work(
1540&cgcx,
1541&prof,
1542incr_comp_session.as_ref(),
1543shared_emitter.clone(),
1544coordinator_send.clone(),
1545&mut llvm_start_time,
1546item,
1547stack_size,
1548 );
1549 } else {
1550// There is no unstarted work, so let the main thread
1551 // take over for a running worker. Otherwise the
1552 // implicit token would just go to waste.
1553 // We reduce the `running` counter by one. The
1554 // `tokens.truncate()` below will take care of
1555 // giving the Token back.
1556if !(running_with_own_token > 0) {
::core::panicking::panic("assertion failed: running_with_own_token > 0")
};assert!(running_with_own_token > 0);
1557running_with_own_token -= 1;
1558main_thread_state = MainThreadState::Lending;
1559 }
1560 }
1561 MainThreadState::Codegenning => ::rustc_span::macros::bug_impl(None,
format_args!("codegen worker should not be codegenning after codegen was already completed"),
Location::caller())bug!(
1562"codegen worker should not be codegenning after \
1563 codegen was already completed"
1564),
1565 MainThreadState::Lending => {
1566// Already making good use of that token
1567}
1568 }
1569 } else {
1570// Don't queue up any more work if codegen was aborted, we're
1571 // just waiting for our existing children to finish.
1572if !(codegen_state == Aborted) {
::core::panicking::panic("assertion failed: codegen_state == Aborted")
};assert!(codegen_state == Aborted);
1573if running_with_any_token(main_thread_state, running_with_own_token) == 0 {
1574break;
1575 }
1576 }
15771578// Spin up what work we can, only doing this while we've got available
1579 // parallelism slots and work left to spawn.
1580if codegen_state != Aborted {
1581while running_with_own_token < tokens.len()
1582 && let Some((item, _)) = work_items.pop()
1583 {
1584 spawn_work(
1585&cgcx,
1586&prof,
1587 incr_comp_session.as_ref(),
1588 shared_emitter.clone(),
1589 coordinator_send.clone(),
1590&mut llvm_start_time,
1591 item,
1592 stack_size,
1593 );
1594 running_with_own_token += 1;
1595 }
1596 }
15971598// Relinquish accidentally acquired extra tokens.
1599tokens.truncate(running_with_own_token);
16001601match coordinator_receive.recv().unwrap() {
1602// Save the token locally and the next turn of the loop will use
1603 // this to spawn a new unit of work, or it may get dropped
1604 // immediately if we have no more work to spawn.
1605Message::Token(token) => {
1606match token {
1607Ok(token) => {
1608tokens.push(token);
16091610if main_thread_state == MainThreadState::Lending {
1611// If the main thread token is used for LLVM work
1612 // at the moment, we turn that thread into a regular
1613 // LLVM worker thread, so the main thread is free
1614 // to react to codegen demand.
1615main_thread_state = MainThreadState::Idle;
1616running_with_own_token += 1;
1617 }
1618 }
1619Err(e) => {
1620let msg = &::alloc::__export::must_use({
::alloc::fmt::format(format_args!("failed to acquire jobserver token: {0}",
e))
})format!("failed to acquire jobserver token: {e}");
1621shared_emitter.fatal(msg);
1622codegen_state = Aborted;
1623 }
1624 }
1625 }
16261627 Message::CodegenDone { llvm_work_item, cost } => {
1628// We keep the queue sorted by estimated processing cost,
1629 // so that more expensive items are processed earlier. This
1630 // is good for throughput as it gives the main thread more
1631 // time to fill up the queue and it avoids scheduling
1632 // expensive items to the end.
1633 // Note, however, that this is not ideal for memory
1634 // consumption, as LLVM module sizes are not evenly
1635 // distributed.
1636let insertion_index = work_items.binary_search_by_key(&cost, |&(_, cost)| cost);
1637let insertion_index = match insertion_index {
1638Ok(idx) | Err(idx) => idx,
1639 };
1640work_items.insert(insertion_index, (llvm_work_item, cost));
16411642if let Some(helper) = &jobserver_helper1643 && running_with_any_token(main_thread_state, running_with_own_token)
1644 < cgcx.parallel.unwrap().get()
1645 {
1646helper.request_token();
1647 }
1648{
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);
1649main_thread_state = MainThreadState::Idle;
1650 }
16511652 Message::CodegenComplete => {
1653if codegen_state != Aborted {
1654codegen_state = Completed;
1655 }
1656{
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);
1657main_thread_state = MainThreadState::Idle;
1658 }
16591660// If codegen is aborted that means translation was aborted due
1661 // to some normal-ish compiler error. In this situation we want
1662 // to exit as soon as possible, but we want to make sure all
1663 // existing work has finished. Flag codegen as being done, and
1664 // then conditions above will ensure no more work is spawned but
1665 // we'll keep executing this loop until `running_with_own_token`
1666 // hits 0.
1667Message::CodegenAborted => {
1668codegen_state = Aborted;
1669 }
16701671 Message::WorkItem { result } => {
1672// If a thread exits successfully then we drop a token associated
1673 // with that worker and update our `running_with_own_token` count.
1674 // We may later re-acquire a token to continue running more work.
1675 // We may also not actually drop a token here if the worker was
1676 // running with an "ephemeral token".
1677if main_thread_state == MainThreadState::Lending {
1678main_thread_state = MainThreadState::Idle;
1679 } else {
1680running_with_own_token -= 1;
1681 }
16821683match result {
1684Ok(WorkItemResult::Finished(compiled_module)) => {
1685compiled_modules.push(compiled_module);
1686 }
1687Ok(WorkItemResult::NeedsFatLto(fat_lto_input)) => {
1688if !needs_thin_lto.is_empty() {
::core::panicking::panic("assertion failed: needs_thin_lto.is_empty()")
};assert!(needs_thin_lto.is_empty());
1689needs_fat_lto.push(fat_lto_input);
1690 }
1691Ok(WorkItemResult::NeedsThinLto(name, thin_buffer)) => {
1692if !needs_fat_lto.is_empty() {
::core::panicking::panic("assertion failed: needs_fat_lto.is_empty()")
};assert!(needs_fat_lto.is_empty());
1693needs_thin_lto.push(ThinLtoInput::Red {
1694name,
1695 buffer: SerializedModule::Local(thin_buffer),
1696 });
1697 }
1698Err(Some(WorkerFatalError)) => {
1699// Like `CodegenAborted`, wait for remaining work to finish.
1700codegen_state = Aborted;
1701 }
1702Err(None) => {
1703// If the thread failed that means it panicked, so
1704 // we abort immediately.
1705::rustc_span::macros::bug_impl(None, format_args!("worker thread panicked"),
Location::caller());bug!("worker thread panicked");
1706 }
1707 }
1708 }
17091710 Message::AddImportOnlyModule { bitcode_path, work_product } => {
1711{
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);
1712{
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);
1713lto_import_only_modules.push((bitcode_path, work_product));
1714main_thread_state = MainThreadState::Idle;
1715 }
1716 }
1717 }
17181719// Drop to print timings
1720drop(llvm_start_time);
17211722if codegen_state == Aborted {
1723return Err(());
1724 }
17251726drop(codegen_state);
1727drop(tokens);
1728drop(jobserver_helper);
1729if !work_items.is_empty() {
::core::panicking::panic("assertion failed: work_items.is_empty()")
};assert!(work_items.is_empty());
17301731if !needs_fat_lto.is_empty() {
1732if !compiled_modules.is_empty() {
::core::panicking::panic("assertion failed: compiled_modules.is_empty()")
};assert!(compiled_modules.is_empty());
1733if !needs_thin_lto.is_empty() {
::core::panicking::panic("assertion failed: needs_thin_lto.is_empty()")
};assert!(needs_thin_lto.is_empty());
17341735if let Some(allocator_module) = allocator_module.take() {
1736needs_fat_lto.push(FatLtoInput::InMemory(allocator_module));
1737 }
17381739for (bitcode_path, wp) in lto_import_only_modules {
1740 needs_fat_lto.push(FatLtoInput::Serialized { name: wp.cgu_name, bitcode_path })
1741 }
17421743return Ok(MaybeLtoModules::FatLto { cgcx, needs_fat_lto });
1744 } else if !needs_thin_lto.is_empty() || !lto_import_only_modules.is_empty() {
1745if !compiled_modules.is_empty() {
::core::panicking::panic("assertion failed: compiled_modules.is_empty()")
};assert!(compiled_modules.is_empty());
1746if !needs_fat_lto.is_empty() {
::core::panicking::panic("assertion failed: needs_fat_lto.is_empty()")
};assert!(needs_fat_lto.is_empty());
17471748for (bitcode_path, wp) in lto_import_only_modules {
1749 needs_thin_lto.push(ThinLtoInput::Green { wp, bitcode_path })
1750 }
17511752if cgcx.lto == Lto::ThinLocal {
1753compiled_modules.extend(do_thin_lto::<B>(
1754&cgcx,
1755&prof,
1756incr_comp_session,
1757shared_emitter.clone(),
1758tm_factory,
1759&exported_symbols_for_lto,
1760&[],
1761needs_thin_lto,
1762stack_size,
1763 ));
1764 } else {
1765if let Some(allocator_module) = allocator_module.take() {
1766let thin_buffer = B::serialize_module(allocator_module.module_llvm, true);
1767needs_thin_lto.push(ThinLtoInput::Red {
1768 name: allocator_module.name,
1769 buffer: SerializedModule::Local(thin_buffer),
1770 });
1771 }
17721773return Ok(MaybeLtoModules::ThinLto { cgcx, needs_thin_lto });
1774 }
1775 }
17761777Ok(MaybeLtoModules::NoLto(CompiledModules {
1778 modules: compiled_modules,
1779 allocator_module: allocator_module.map(|allocator_module| {
1780 B::codegen(&cgcx, &prof, &shared_emitter, allocator_module, &allocator_config)
1781 }),
1782 }))
1783 };
1784return std::thread::Builder::new()
1785 .name("coordinator".to_owned())
1786 .spawn(f)
1787 .expect("failed to spawn coordinator thread");
17881789// A heuristic that determines if we have enough LLVM WorkItems in the
1790 // queue so that the main thread can do LLVM work instead of codegen
1791fn queue_full_enough(items_in_queue: usize, workers_running: usize) -> bool {
1792// This heuristic scales ahead-of-time codegen according to available
1793 // concurrency, as measured by `workers_running`. The idea is that the
1794 // more concurrency we have available, the more demand there will be for
1795 // work items, and the fuller the queue should be kept to meet demand.
1796 // An important property of this approach is that we codegen ahead of
1797 // time only as much as necessary, so as to keep fewer LLVM modules in
1798 // memory at once, thereby reducing memory consumption.
1799 //
1800 // When the number of workers running is less than the max concurrency
1801 // available to us, this heuristic can cause us to instruct the main
1802 // thread to work on an LLVM item (that is, tell it to "LLVM") instead
1803 // of codegen, even though it seems like it *should* be codegenning so
1804 // that we can create more work items and spawn more LLVM workers.
1805 //
1806 // But this is not a problem. When the main thread is told to LLVM,
1807 // according to this heuristic and how work is scheduled, there is
1808 // always at least one item in the queue, and therefore at least one
1809 // pending jobserver token request. If there *is* more concurrency
1810 // available, we will immediately receive a token, which will upgrade
1811 // the main thread's LLVM worker to a real one (conceptually), and free
1812 // up the main thread to codegen if necessary. On the other hand, if
1813 // there isn't more concurrency, then the main thread working on an LLVM
1814 // item is appropriate, as long as the queue is full enough for demand.
1815 //
1816 // Speaking of which, how full should we keep the queue? Probably less
1817 // full than you'd think. A lot has to go wrong for the queue not to be
1818 // full enough and for that to have a negative effect on compile times.
1819 //
1820 // Workers are unlikely to finish at exactly the same time, so when one
1821 // finishes and takes another work item off the queue, we often have
1822 // ample time to codegen at that point before the next worker finishes.
1823 // But suppose that codegen takes so long that the workers exhaust the
1824 // queue, and we have one or more workers that have nothing to work on.
1825 // Well, it might not be so bad. Of all the LLVM modules we create and
1826 // optimize, one has to finish last. It's not necessarily the case that
1827 // by losing some concurrency for a moment, we delay the point at which
1828 // that last LLVM module is finished and the rest of compilation can
1829 // proceed. Also, when we can't take advantage of some concurrency, we
1830 // give tokens back to the job server. That enables some other rustc to
1831 // potentially make use of the available concurrency. That could even
1832 // *decrease* overall compile time if we're lucky. But yes, if no other
1833 // rustc can make use of the concurrency, then we've squandered it.
1834 //
1835 // However, keeping the queue full is also beneficial when we have a
1836 // surge in available concurrency. Then items can be taken from the
1837 // queue immediately, without having to wait for codegen.
1838 //
1839 // So, the heuristic below tries to keep one item in the queue for every
1840 // four running workers. Based on limited benchmarking, this appears to
1841 // be more than sufficient to avoid increasing compilation times.
1842let quarter_of_workers = workers_running - 3 * workers_running / 4;
1843items_in_queue > 0 && items_in_queue >= quarter_of_workers1844 }
1845}
18461847/// `FatalError` is explicitly not `Send`.
1848#[must_use]
1849pub(crate) struct WorkerFatalError;
18501851fn spawn_work<'a, B: WriteBackendMethods>(
1852 cgcx: &CodegenContext,
1853 prof: &'a SelfProfilerRef,
1854 incr_comp_session: Option<&BorrowedIncrCompSession>,
1855 shared_emitter: SharedEmitter,
1856 coordinator_send: Sender<Message<B>>,
1857 llvm_start_time: &mut Option<VerboseTimingGuard<'a>>,
1858 work: WorkItem<B>,
1859 stack_size: usize,
1860) {
1861if llvm_start_time.is_none() {
1862*llvm_start_time = Some(prof.verbose_generic_activity("LLVM_passes"));
1863 }
18641865let old_incr_comp_session_dir = incr_comp_session1866 .and_then(|incr_comp_session| incr_comp_session.old_session_directory.clone());
1867let new_incr_comp_session_dir =
1868incr_comp_session.map(|incr_comp_session| incr_comp_session.new_session_directory.clone());
18691870let cgcx = cgcx.clone();
1871let prof = prof.clone();
18721873let name = work.short_description();
1874let f = move || {
1875let _profiler = if cgcx.time_trace { B::thread_profiler() } else { Box::new(()) };
18761877let result = std::panic::catch_unwind(AssertUnwindSafe(|| match work {
1878 WorkItem::Optimize(m) => execute_optimize_work_item(
1879&cgcx,
1880&prof,
1881new_incr_comp_session_dir.as_deref(),
1882shared_emitter,
1883m,
1884 ),
1885 WorkItem::CopyPostLtoArtifacts(m) => {
1886 WorkItemResult::Finished(execute_copy_from_cache_work_item(
1887&cgcx,
1888&prof,
1889old_incr_comp_session_dir.as_deref().unwrap(),
1890shared_emitter,
1891m,
1892 ))
1893 }
1894 }));
18951896let msg = match result {
1897Ok(result) => Message::WorkItem::<B> { result: Ok(result) },
18981899// We ignore any `FatalError` coming out of `execute_work_item`, as a
1900 // diagnostic was already sent off to the main thread - just surface
1901 // that there was an error in this worker.
1902Err(err) if err.is::<FatalErrorMarker>() => {
1903 Message::WorkItem::<B> { result: Err(Some(WorkerFatalError)) }
1904 }
19051906Err(_) => Message::WorkItem::<B> { result: Err(None) },
1907 };
1908drop(coordinator_send.send(msg));
1909 };
1910 std::thread::Builder::new()
1911 .name(name)
1912 .stack_size(stack_size)
1913 .spawn(f)
1914 .expect("failed to spawn work thread");
1915}
19161917fn spawn_thin_lto_work<B: WriteBackendMethods>(
1918 cgcx: &CodegenContext,
1919 prof: &SelfProfilerRef,
1920 old_incr_comp_session_dir: Option<PathBuf>,
1921 shared_emitter: SharedEmitter,
1922 tm_factory: TargetMachineFactoryFn<B>,
1923 coordinator_send: Sender<ThinLtoMessage>,
1924 work: ThinLtoWorkItem<B>,
1925 stack_size: usize,
1926) {
1927let cgcx = cgcx.clone();
1928let prof = prof.clone();
19291930let name = work.short_description();
1931let f = move || {
1932let _profiler = if cgcx.time_trace { B::thread_profiler() } else { Box::new(()) };
19331934let result = std::panic::catch_unwind(AssertUnwindSafe(|| match work {
1935 ThinLtoWorkItem::CopyPostLtoArtifacts(m) => execute_copy_from_cache_work_item(
1936&cgcx,
1937&prof,
1938old_incr_comp_session_dir.as_deref().unwrap(),
1939shared_emitter,
1940m,
1941 ),
1942 ThinLtoWorkItem::ThinLto(m) => {
1943let _timer = prof.generic_activity_with_arg("codegen_module_perform_lto", m.name());
1944 B::optimize_and_codegen_thin(&cgcx, &prof, &shared_emitter, tm_factory, m)
1945 }
1946 }));
19471948let msg = match result {
1949Ok(result) => ThinLtoMessage::WorkItem { result: Ok(result) },
19501951// We ignore any `FatalError` coming out of `execute_work_item`, as a
1952 // diagnostic was already sent off to the main thread - just surface
1953 // that there was an error in this worker.
1954Err(err) if err.is::<FatalErrorMarker>() => {
1955 ThinLtoMessage::WorkItem { result: Err(Some(WorkerFatalError)) }
1956 }
19571958Err(_) => ThinLtoMessage::WorkItem { result: Err(None) },
1959 };
1960drop(coordinator_send.send(msg));
1961 };
1962 std::thread::Builder::new()
1963 .name(name)
1964 .stack_size(stack_size)
1965 .spawn(f)
1966 .expect("failed to spawn work thread");
1967}
19681969enum SharedEmitterMessage {
1970 Diagnostic(DiagInner),
1971 InlineAsmError(InlineAsmError),
1972 Fatal(String),
1973}
19741975pub struct InlineAsmError {
1976// We store byte positions rather than a `Span` because this error is created on a codegen
1977 // thread which doesn't have access to the span interner within the session globals. The byte
1978 // positions are converted to a `Span` once they reach a thread with access to the span
1979 // interner.
1980pub lo: BytePos,
1981pub hi: BytePos,
1982pub msg: String,
1983pub level: Level,
1984pub source: Option<(String, Vec<InnerSpan>)>,
1985}
19861987#[derive(#[automatically_derived]impl ::core::clone::Clone for SharedEmitter {
#[inline]
fn clone(&self) -> Self {
SharedEmitter { sender: ::core::clone::Clone::clone(&self.sender) }
}
}Clone)]
1988pub struct SharedEmitter {
1989 sender: Sender<SharedEmitterMessage>,
1990}
19911992pub struct SharedEmitterMain {
1993 receiver: Receiver<SharedEmitterMessage>,
1994}
19951996impl SharedEmitter {
1997fn new() -> (SharedEmitter, SharedEmitterMain) {
1998let (sender, receiver) = channel();
19992000 (SharedEmitter { sender }, SharedEmitterMain { receiver })
2001 }
20022003pub fn inline_asm_error(&self, err: InlineAsmError) {
2004drop(self.sender.send(SharedEmitterMessage::InlineAsmError(err)));
2005 }
20062007fn fatal(&self, msg: &str) {
2008drop(self.sender.send(SharedEmitterMessage::Fatal(msg.to_string())));
2009 }
2010}
20112012impl Emitterfor SharedEmitter {
2013fn emit_diagnostic(&mut self, diag: DiagInner) {
2014drop(self.sender.send(SharedEmitterMessage::Diagnostic(diag)));
2015 }
20162017fn source_map(&self) -> Option<&SourceMap> {
2018None2019 }
2020}
20212022impl SharedEmitterMain {
2023fn check(&self, sess: &Session, blocking: bool) {
2024loop {
2025let message = if blocking {
2026match self.receiver.recv() {
2027Ok(message) => Ok(message),
2028Err(_) => Err(()),
2029 }
2030 } else {
2031match self.receiver.try_recv() {
2032Ok(message) => Ok(message),
2033Err(_) => Err(()),
2034 }
2035 };
20362037match message {
2038Ok(SharedEmitterMessage::Diagnostic(diag)) => {
2039let dcx = sess.dcx();
2040dcx.emit_diagnostic(diag);
2041sess.dcx().abort_if_errors();
2042 }
2043Ok(SharedEmitterMessage::InlineAsmError(inner)) => {
2044{
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);
2045let mut err = Diag::new(sess.dcx(), inner.level, inner.msg);
2046let span = Span::new(inner.lo, inner.hi, SyntaxContext::root(), None);
2047if !span.is_dummy() {
2048err.span(span);
2049 }
20502051// Point to the generated assembly if it is available.
2052if let Some((buffer, spans)) = inner.source {
2053let source = sess2054 .source_map()
2055 .new_source_file(FileName::inline_asm_source_code(&buffer), buffer);
2056let spans: Vec<_> = spans2057 .iter()
2058 .map(|sp| {
2059Span::with_root_ctxt(
2060source.normalized_byte_pos(sp.start as u32),
2061source.normalized_byte_pos(sp.end as u32),
2062 )
2063 })
2064 .collect();
2065err.span_note(spans, "instantiated into assembly here");
2066 }
20672068err.emit();
2069 }
2070Ok(SharedEmitterMessage::Fatal(msg)) => {
2071sess.dcx().fatal(msg);
2072 }
2073Err(_) => {
2074break;
2075 }
2076 }
2077 }
2078 }
2079}
20802081pub struct Coordinator<B: WriteBackendMethods> {
2082 sender: Sender<Message<B>>,
2083 future: Option<thread::JoinHandle<Result<MaybeLtoModules<B>, ()>>>,
2084// Only used for the Message type.
2085phantom: PhantomData<B>,
2086}
20872088impl<B: WriteBackendMethods> Coordinator<B> {
2089fn join(mut self) -> std::thread::Result<Result<MaybeLtoModules<B>, ()>> {
2090self.future.take().unwrap().join()
2091 }
2092}
20932094impl<B: WriteBackendMethods> Dropfor Coordinator<B> {
2095fn drop(&mut self) {
2096if let Some(future) = self.future.take() {
2097// If we haven't joined yet, signal to the coordinator that it should spawn no more
2098 // work, and wait for worker threads to finish.
2099drop(self.sender.send(Message::CodegenAborted::<B>));
2100drop(future.join());
2101 }
2102 }
2103}
21042105pub struct OngoingCodegen<B: WriteBackendMethods> {
2106 backend: B,
2107 output_filenames: Arc<OutputFilenames>,
2108// Field order below is intended to terminate the coordinator thread before two fields below
2109 // drop and prematurely close channels used by coordinator thread. See `Coordinator`'s
2110 // `Drop` implementation for more info.
2111pub(crate) coordinator: Coordinator<B>,
2112 codegen_worker_receive: Receiver<CguMessage>,
2113 shared_emitter_main: SharedEmitterMain,
2114}
21152116impl<B: WriteBackendMethods> OngoingCodegen<B> {
2117pub fn join(
2118self,
2119 sess: &Session,
2120 incr_comp_session: Option<&IncrCompSession>,
2121 crate_info: &CrateInfo,
2122 ) -> (CompiledModules, WorkProductMap) {
2123self.shared_emitter_main.check(sess, true);
21242125let maybe_lto_modules = sess.time("join_worker_thread", || match self.coordinator.join() {
2126Ok(Ok(maybe_lto_modules)) => maybe_lto_modules,
2127Ok(Err(())) => {
2128sess.dcx().abort_if_errors();
2129{
::core::panicking::panic_fmt(format_args!("expected abort due to worker thread errors"));
}panic!("expected abort due to worker thread errors")2130 }
2131Err(_) => {
2132::rustc_span::macros::bug_impl(None,
format_args!("panic during codegen/LLVM phase"), Location::caller());bug!("panic during codegen/LLVM phase");
2133 }
2134 });
21352136sess.dcx().abort_if_errors();
21372138let (shared_emitter, shared_emitter_main) = SharedEmitter::new();
21392140// Catch fatal errors to ensure shared_emitter_main.check() can emit the actual diagnostics
2141let compilation_output = catch_fatal_errors(|| match maybe_lto_modules {
2142 MaybeLtoModules::NoLto(compiled_modules) => {
2143drop(shared_emitter);
21442145let work_products = copy_all_cgu_workproducts_to_incr_comp_cache_dir(
2146sess,
2147incr_comp_session,
2148&compiled_modules,
2149 );
21502151 (compiled_modules, work_products)
2152 }
2153 MaybeLtoModules::FatLto { cgcx, needs_fat_lto } => {
2154let tm_factory = self.backend.target_machine_factory(sess, cgcx.opt_level);
21552156// FIXME cache local pre-LTO bitcode
2157let work_products = WorkProductMap::default();
21582159let compiled_modules = CompiledModules {
2160 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(
2161 sess,
2162&cgcx,
2163 shared_emitter,
2164 tm_factory,
2165&crate_info.exported_symbols_for_lto,
2166&crate_info.each_linked_rlib_file_for_lto,
2167 needs_fat_lto,
2168 )],
2169 allocator_module: None,
2170 };
21712172 (compiled_modules, work_products)
2173 }
2174 MaybeLtoModules::ThinLto { cgcx, needs_thin_lto } => {
2175let tm_factory = self.backend.target_machine_factory(sess, cgcx.opt_level);
21762177let compiled_modules = CompiledModules {
2178 modules: do_thin_lto::<B>(
2179&cgcx,
2180&sess.prof,
2181incr_comp_session.map(|incr_comp_session| incr_comp_session.borrow()),
2182shared_emitter,
2183tm_factory,
2184&crate_info.exported_symbols_for_lto,
2185&crate_info.each_linked_rlib_file_for_lto,
2186needs_thin_lto,
2187sess.opts.recommended_stack_size,
2188 ),
2189 allocator_module: None,
2190 };
21912192// FIXME include pre-LTO bitcode in workproduct tracking
2193 // FIXME add separate incr comp session for post-LTO outputs to use during link step
2194let work_products = copy_all_cgu_workproducts_to_incr_comp_cache_dir(
2195sess,
2196incr_comp_session,
2197&compiled_modules,
2198 );
21992200 (compiled_modules, work_products)
2201 }
2202 });
22032204shared_emitter_main.check(sess, true);
22052206sess.dcx().abort_if_errors();
22072208let (mut compiled_modules, work_products) =
2209compilation_output.expect("fatal error emitted but not sent to SharedEmitter");
22102211// Regardless of what order these modules completed in, report them to
2212 // the backend in the same order every time to ensure that we're handing
2213 // out deterministic results.
2214compiled_modules.modules.sort_by(|a, b| a.name.cmp(&b.name));
22152216produce_final_output_artifacts(sess, &compiled_modules, &self.output_filenames);
22172218 (compiled_modules, work_products)
2219 }
22202221pub(crate) fn codegen_finished(&self, tcx: TyCtxt<'_>) {
2222self.wait_for_signal_to_codegen_item();
2223self.check_for_errors(tcx.sess);
2224drop(self.coordinator.sender.send(Message::CodegenComplete::<B>));
2225 }
22262227pub(crate) fn check_for_errors(&self, sess: &Session) {
2228self.shared_emitter_main.check(sess, false);
2229 }
22302231pub(crate) fn wait_for_signal_to_codegen_item(&self) {
2232match self.codegen_worker_receive.recv() {
2233Ok(CguMessage) => {
2234// Ok to proceed.
2235}
2236Err(_) => {
2237// One of the LLVM threads must have panicked, fall through so
2238 // error handling can be reached.
2239}
2240 }
2241 }
2242}
22432244pub(crate) fn submit_codegened_module_to_llvm<B: WriteBackendMethods>(
2245 coordinator: &Coordinator<B>,
2246 module: ModuleCodegen<B::Module>,
2247 cost: u64,
2248) {
2249let llvm_work_item = WorkItem::Optimize(module);
2250drop(coordinator.sender.send(Message::CodegenDone::<B> { llvm_work_item, cost }));
2251}
22522253pub(crate) fn submit_post_lto_module_to_llvm<B: WriteBackendMethods>(
2254 coordinator: &Coordinator<B>,
2255 module: CachedModuleCodegen,
2256) {
2257let llvm_work_item = WorkItem::CopyPostLtoArtifacts(module);
2258drop(coordinator.sender.send(Message::CodegenDone::<B> { llvm_work_item, cost: 0 }));
2259}
22602261pub(crate) fn submit_pre_lto_module_to_llvm<B: WriteBackendMethods>(
2262 tcx: TyCtxt<'_>,
2263 coordinator: &Coordinator<B>,
2264 module: CachedModuleCodegen,
2265) {
2266let filename = pre_lto_bitcode_filename(&module.name);
2267let old_bitcode_path =
2268in_old_incr_comp_dir_sess(tcx.incr_comp_session.unwrap(), &filename).unwrap();
2269let bitcode_path = in_incr_comp_dir_sess(tcx.incr_comp_session.unwrap(), &filename);
22702271match link_or_copy(&old_bitcode_path, &bitcode_path) {
2272Ok(_) => {}
2273Err(error) => {
2274tcx.sess.dcx().emit_err(diagnostics::CopyPathBuf {
2275 source_file: old_bitcode_path,
2276 output_path: bitcode_path,
2277error,
2278 });
2279return;
2280 }
2281 }
22822283// Schedule the module to be loaded
2284drop(
2285coordinator2286 .sender
2287 .send(Message::AddImportOnlyModule::<B> { bitcode_path, work_product: module.source }),
2288 );
2289}
22902291fn pre_lto_bitcode_filename(module_name: &str) -> String {
2292::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}.{1}", module_name,
PRE_LTO_BC_EXT))
})format!("{module_name}.{PRE_LTO_BC_EXT}")2293}
22942295fn msvc_imps_needed(tcx: TyCtxt<'_>) -> bool {
2296// This should never be true (because it's not supported). If it is true,
2297 // something is wrong with commandline arg validation.
2298if !!(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!(
2299 !(tcx.sess.opts.cg.linker_plugin_lto.enabled()
2300 && tcx.sess.target.is_like_windows
2301 && tcx.sess.opts.cg.prefer_dynamic)
2302 );
23032304// We need to generate _imp__ symbol if we are generating an rlib or we include one
2305 // indirectly from ThinLTO. In theory these are not needed as ThinLTO could resolve
2306 // these, but it currently does not do so.
2307let can_have_static_objects =
2308tcx.sess.lto() == Lto::Thin || tcx.crate_types().contains(&CrateType::Rlib);
23092310tcx.sess.target.is_like_windows &&
2311can_have_static_objects &&
2312// ThinLTO can't handle this workaround in all cases, so we don't
2313 // emit the `__imp_` symbols. Instead we make them unnecessary by disallowing
2314 // dynamic linking when linker plugin LTO is enabled.
2315!tcx.sess.opts.cg.linker_plugin_lto.enabled()
2316}