1use std::marker::PhantomData;
2use std::panic::AssertUnwindSafe;
3use std::path::{Path, PathBuf};
4use std::sync::Arc;
5use std::sync::mpsc::{Receiver, Sender, channel};
6use std::{assert_matches, fs, io, mem, str, thread};
78use rustc_abi::Size;
9use rustc_data_structures::fx::FxIndexMap;
10use rustc_data_structures::jobserver::{self, Acquired};
11use rustc_data_structures::profiling::{SelfProfilerRef, VerboseTimingGuard};
12use rustc_errors::emitter::Emitter;
13use rustc_errors::{
14Diag, DiagArgMap, DiagCtxt, DiagCtxtHandle, DiagMessage, ErrCode, FatalError, FatalErrorMarker,
15Level, MultiSpan, Style, Suggestions, catch_fatal_errors,
16};
17use rustc_fs_util::link_or_copy;
18use rustc_hir::find_attr;
19use rustc_incremental::{
20copy_cgu_workproduct_to_incr_comp_cache_dir, in_incr_comp_dir, in_incr_comp_dir_sess,
21};
22use rustc_macros::{Decodable, Encodable};
23use rustc_metadata::fs::copy_to_stdout;
24use rustc_middle::bug;
25use rustc_middle::dep_graph::{WorkProduct, WorkProductId};
26use rustc_middle::ty::TyCtxt;
27use rustc_session::Session;
28use rustc_session::config::{
29self, CrateType, Lto, OptLevel, OutFileName, OutputFilenames, OutputType, Passes,
30SwitchWithOptPath,
31};
32use rustc_span::source_map::SourceMap;
33use rustc_span::{FileName, InnerSpan, Span, SpanData};
34use rustc_target::spec::{MergeFunctions, SanitizerSet};
35use tracing::debug;
3637use crate::back::link::ensure_removed;
38use crate::back::lto::{self, SerializedModule, check_lto_allowed};
39use crate::errors::ErrorCreatingRemarkDir;
40use crate::traits::*;
41use crate::{
42CachedModuleCodegen, CompiledModule, CompiledModules, CrateInfo, ModuleCodegen, ModuleKind,
43errors,
44};
4546const PRE_LTO_BC_EXT: &str = "pre-lto.bc";
4748/// What kind of object file to emit.
49#[derive(#[automatically_derived]
impl ::core::clone::Clone for EmitObj {
#[inline]
fn clone(&self) -> EmitObj {
let _: ::core::clone::AssertParamIsClone<BitcodeSection>;
*self
}
}Clone, #[automatically_derived]
impl ::core::marker::Copy for EmitObj { }Copy, #[automatically_derived]
impl ::core::cmp::PartialEq for EmitObj {
#[inline]
fn eq(&self, other: &EmitObj) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr &&
match (self, other) {
(EmitObj::ObjectCode(__self_0), EmitObj::ObjectCode(__arg1_0))
=> __self_0 == __arg1_0,
_ => true,
}
}
}PartialEq, const _: () =
{
impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
for EmitObj {
fn encode(&self, __encoder: &mut __E) {
let disc =
match *self {
EmitObj::None => { 0usize }
EmitObj::Bitcode => { 1usize }
EmitObj::ObjectCode(ref __binding_0) => { 2usize }
};
::rustc_serialize::Encoder::emit_u8(__encoder, disc as u8);
match *self {
EmitObj::None => {}
EmitObj::Bitcode => {}
EmitObj::ObjectCode(ref __binding_0) => {
::rustc_serialize::Encodable::<__E>::encode(__binding_0,
__encoder);
}
}
}
}
};Encodable, const _: () =
{
impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
for EmitObj {
fn decode(__decoder: &mut __D) -> Self {
match ::rustc_serialize::Decoder::read_u8(__decoder) as usize
{
0usize => { EmitObj::None }
1usize => { EmitObj::Bitcode }
2usize => {
EmitObj::ObjectCode(::rustc_serialize::Decodable::decode(__decoder))
}
n => {
::core::panicking::panic_fmt(format_args!("invalid enum variant tag while decoding `EmitObj`, expected 0..3, actual {0}",
n));
}
}
}
}
};Decodable)]
50pub enum EmitObj {
51// No object file.
52None,
5354// Just uncompressed llvm bitcode. Provides easy compatibility with
55 // emscripten's ecc compiler, when used as the linker.
56Bitcode,
5758// Object code, possibly augmented with a bitcode section.
59ObjectCode(BitcodeSection),
60}
6162/// What kind of llvm bitcode section to embed in an object file.
63#[derive(#[automatically_derived]
impl ::core::clone::Clone for BitcodeSection {
#[inline]
fn clone(&self) -> BitcodeSection { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for BitcodeSection { }Copy, #[automatically_derived]
impl ::core::cmp::PartialEq for BitcodeSection {
#[inline]
fn eq(&self, other: &BitcodeSection) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq, const _: () =
{
impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
for BitcodeSection {
fn encode(&self, __encoder: &mut __E) {
let disc =
match *self {
BitcodeSection::None => { 0usize }
BitcodeSection::Full => { 1usize }
};
::rustc_serialize::Encoder::emit_u8(__encoder, disc as u8);
match *self {
BitcodeSection::None => {}
BitcodeSection::Full => {}
}
}
}
};Encodable, const _: () =
{
impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
for BitcodeSection {
fn decode(__decoder: &mut __D) -> Self {
match ::rustc_serialize::Decoder::read_u8(__decoder) as usize
{
0usize => { BitcodeSection::None }
1usize => { BitcodeSection::Full }
n => {
::core::panicking::panic_fmt(format_args!("invalid enum variant tag while decoding `BitcodeSection`, expected 0..2, actual {0}",
n));
}
}
}
}
};Decodable)]
64pub enum BitcodeSection {
65// No bitcode section.
66None,
6768// A full, uncompressed bitcode section.
69Full,
70}
7172/// Module-specific configuration for `optimize_and_codegen`.
73#[derive(const _: () =
{
impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
for ModuleConfig {
fn encode(&self, __encoder: &mut __E) {
match *self {
ModuleConfig {
passes: ref __binding_0,
opt_level: ref __binding_1,
pgo_gen: ref __binding_2,
pgo_use: ref __binding_3,
pgo_sample_use: ref __binding_4,
debug_info_for_profiling: ref __binding_5,
instrument_coverage: ref __binding_6,
sanitizer: ref __binding_7,
sanitizer_recover: ref __binding_8,
sanitizer_dataflow_abilist: ref __binding_9,
sanitizer_memory_track_origins: ref __binding_10,
emit_pre_lto_bc: ref __binding_11,
emit_bc: ref __binding_12,
emit_ir: ref __binding_13,
emit_asm: ref __binding_14,
emit_obj: ref __binding_15,
emit_thin_lto_summary: ref __binding_16,
verify_llvm_ir: ref __binding_17,
lint_llvm_ir: ref __binding_18,
no_prepopulate_passes: ref __binding_19,
no_builtins: ref __binding_20,
vectorize_loop: ref __binding_21,
vectorize_slp: ref __binding_22,
merge_functions: ref __binding_23,
emit_lifetime_markers: ref __binding_24,
llvm_plugins: ref __binding_25,
autodiff: ref __binding_26,
offload: ref __binding_27 } => {
::rustc_serialize::Encodable::<__E>::encode(__binding_0,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_1,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_2,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_3,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_4,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_5,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_6,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_7,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_8,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_9,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_10,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_11,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_12,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_13,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_14,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_15,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_16,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_17,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_18,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_19,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_20,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_21,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_22,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_23,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_24,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_25,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_26,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_27,
__encoder);
}
}
}
}
};Encodable, const _: () =
{
impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
for ModuleConfig {
fn decode(__decoder: &mut __D) -> Self {
ModuleConfig {
passes: ::rustc_serialize::Decodable::decode(__decoder),
opt_level: ::rustc_serialize::Decodable::decode(__decoder),
pgo_gen: ::rustc_serialize::Decodable::decode(__decoder),
pgo_use: ::rustc_serialize::Decodable::decode(__decoder),
pgo_sample_use: ::rustc_serialize::Decodable::decode(__decoder),
debug_info_for_profiling: ::rustc_serialize::Decodable::decode(__decoder),
instrument_coverage: ::rustc_serialize::Decodable::decode(__decoder),
sanitizer: ::rustc_serialize::Decodable::decode(__decoder),
sanitizer_recover: ::rustc_serialize::Decodable::decode(__decoder),
sanitizer_dataflow_abilist: ::rustc_serialize::Decodable::decode(__decoder),
sanitizer_memory_track_origins: ::rustc_serialize::Decodable::decode(__decoder),
emit_pre_lto_bc: ::rustc_serialize::Decodable::decode(__decoder),
emit_bc: ::rustc_serialize::Decodable::decode(__decoder),
emit_ir: ::rustc_serialize::Decodable::decode(__decoder),
emit_asm: ::rustc_serialize::Decodable::decode(__decoder),
emit_obj: ::rustc_serialize::Decodable::decode(__decoder),
emit_thin_lto_summary: ::rustc_serialize::Decodable::decode(__decoder),
verify_llvm_ir: ::rustc_serialize::Decodable::decode(__decoder),
lint_llvm_ir: ::rustc_serialize::Decodable::decode(__decoder),
no_prepopulate_passes: ::rustc_serialize::Decodable::decode(__decoder),
no_builtins: ::rustc_serialize::Decodable::decode(__decoder),
vectorize_loop: ::rustc_serialize::Decodable::decode(__decoder),
vectorize_slp: ::rustc_serialize::Decodable::decode(__decoder),
merge_functions: ::rustc_serialize::Decodable::decode(__decoder),
emit_lifetime_markers: ::rustc_serialize::Decodable::decode(__decoder),
llvm_plugins: ::rustc_serialize::Decodable::decode(__decoder),
autodiff: ::rustc_serialize::Decodable::decode(__decoder),
offload: ::rustc_serialize::Decodable::decode(__decoder),
}
}
}
};Decodable)]
74pub struct ModuleConfig {
75/// Names of additional optimization passes to run.
76pub passes: Vec<String>,
77/// Some(level) to optimize at a certain level, or None to run
78 /// absolutely no optimizations (used for the allocator module).
79pub opt_level: Option<config::OptLevel>,
8081pub pgo_gen: SwitchWithOptPath,
82pub pgo_use: Option<PathBuf>,
83pub pgo_sample_use: Option<PathBuf>,
84pub debug_info_for_profiling: bool,
85pub instrument_coverage: bool,
8687pub sanitizer: SanitizerSet,
88pub sanitizer_recover: SanitizerSet,
89pub sanitizer_dataflow_abilist: Vec<String>,
90pub sanitizer_memory_track_origins: usize,
9192// Flags indicating which outputs to produce.
93pub emit_pre_lto_bc: bool,
94pub emit_bc: bool,
95pub emit_ir: bool,
96pub emit_asm: bool,
97pub emit_obj: EmitObj,
98pub emit_thin_lto_summary: bool,
99100// Miscellaneous flags. These are mostly copied from command-line
101 // options.
102pub verify_llvm_ir: bool,
103pub lint_llvm_ir: bool,
104pub no_prepopulate_passes: bool,
105pub no_builtins: bool,
106pub vectorize_loop: bool,
107pub vectorize_slp: bool,
108pub merge_functions: bool,
109pub emit_lifetime_markers: bool,
110pub llvm_plugins: Vec<String>,
111pub autodiff: Vec<config::AutoDiff>,
112pub offload: Vec<config::Offload>,
113}
114115impl ModuleConfig {
116fn new(kind: ModuleKind, tcx: TyCtxt<'_>, no_builtins: bool) -> ModuleConfig {
117// If it's a regular module, use `$regular`, otherwise use `$other`.
118 // `$regular` and `$other` are evaluated lazily.
119macro_rules! if_regular {
120 ($regular: expr, $other: expr) => {
121if let ModuleKind::Regular = kind { $regular } else { $other }
122 };
123 }
124125let sess = tcx.sess;
126let opt_level_and_size = if let ModuleKind::Regular = kind { Some(sess.opts.optimize) } else { None }if_regular!(Some(sess.opts.optimize), None);
127128let save_temps = sess.opts.cg.save_temps;
129130let should_emit_obj = sess.opts.output_types.contains_key(&OutputType::Exe)
131 || match kind {
132 ModuleKind::Regular => sess.opts.output_types.contains_key(&OutputType::Object),
133 ModuleKind::Allocator => false,
134 };
135136let emit_obj = if !should_emit_obj {
137 EmitObj::None138 } else if sess.target.obj_is_bitcode
139 || (sess.opts.cg.linker_plugin_lto.enabled()
140 && (!no_builtins || tcx.sess.is_sanitizer_cfi_enabled()))
141 {
142// This case is selected if the target uses objects as bitcode, or
143 // if linker plugin LTO is enabled. In the linker plugin LTO case
144 // the assumption is that the final link-step will read the bitcode
145 // and convert it to object code. This may be done by either the
146 // native linker or rustc itself.
147 //
148 // By default this branch is skipped for `#![no_builtins]` crates so
149 // they emit native object files (machine code), not LLVM bitcode
150 // objects for the linker (see rust-lang/rust#146133).
151 //
152 // However, when LLVM CFI is enabled (`-Zsanitizer=cfi`), this
153 // breaks LLVM's expected pipeline: LLVM emits `llvm.type.test`
154 // intrinsics and related metadata that must be lowered by LLVM's
155 // `LowerTypeTests` pass before instruction selection during
156 // link-time LTO. Otherwise, `llvm.type.test` intrinsics and related
157 // metadata are not lowered by LLVM's `LowerTypeTests` pass before
158 // reaching the target backend, and LLVM may abort during codegen
159 // (for example in SelectionDAG type legalization) (see
160 // rust-lang/rust#142284).
161 //
162 // Therefore, with `-Clinker-plugin-lto` and `-Zsanitizer=cfi`, a
163 // `#![no_builtins]` crate must still use rustc's `EmitObj::Bitcode`
164 // path (and emit LLVM bitcode in the `.o` for linker-based LTO).
165EmitObj::Bitcode166 } else if need_bitcode_in_object(tcx) || sess.target.requires_lto {
167 EmitObj::ObjectCode(BitcodeSection::Full)
168 } else {
169 EmitObj::ObjectCode(BitcodeSection::None)
170 };
171172ModuleConfig {
173 passes: if let ModuleKind::Regular = kind {
sess.opts.cg.passes.clone()
} else { ::alloc::vec::Vec::new() }if_regular!(sess.opts.cg.passes.clone(), vec![]),
174175 opt_level: opt_level_and_size,
176177 pgo_gen: if let ModuleKind::Regular = kind {
sess.opts.cg.profile_generate.clone()
} else { SwitchWithOptPath::Disabled }if_regular!(
178 sess.opts.cg.profile_generate.clone(),
179 SwitchWithOptPath::Disabled
180 ),
181 pgo_use: if let ModuleKind::Regular = kind {
sess.opts.cg.profile_use.clone()
} else { None }if_regular!(sess.opts.cg.profile_use.clone(), None),
182 pgo_sample_use: if let ModuleKind::Regular = kind {
sess.opts.unstable_opts.profile_sample_use.clone()
} else { None }if_regular!(sess.opts.unstable_opts.profile_sample_use.clone(), None),
183 debug_info_for_profiling: sess.opts.unstable_opts.debug_info_for_profiling,
184 instrument_coverage: if let ModuleKind::Regular = kind {
sess.instrument_coverage()
} else { false }if_regular!(sess.instrument_coverage(), false),
185186 sanitizer: if let ModuleKind::Regular = kind {
sess.sanitizers()
} else { SanitizerSet::empty() }if_regular!(sess.sanitizers(), SanitizerSet::empty()),
187 sanitizer_dataflow_abilist: if let ModuleKind::Regular = kind {
sess.opts.unstable_opts.sanitizer_dataflow_abilist.clone()
} else { Vec::new() }if_regular!(
188 sess.opts.unstable_opts.sanitizer_dataflow_abilist.clone(),
189 Vec::new()
190 ),
191 sanitizer_recover: if let ModuleKind::Regular = kind {
sess.opts.unstable_opts.sanitizer_recover
} else { SanitizerSet::empty() }if_regular!(
192 sess.opts.unstable_opts.sanitizer_recover,
193 SanitizerSet::empty()
194 ),
195 sanitizer_memory_track_origins: if let ModuleKind::Regular = kind {
sess.opts.unstable_opts.sanitizer_memory_track_origins
} else { 0 }if_regular!(
196 sess.opts.unstable_opts.sanitizer_memory_track_origins,
1970
198),
199200 emit_pre_lto_bc: if let ModuleKind::Regular = kind {
save_temps || need_pre_lto_bitcode_for_incr_comp(sess)
} else { false }if_regular!(
201 save_temps || need_pre_lto_bitcode_for_incr_comp(sess),
202false
203),
204 emit_bc: if let ModuleKind::Regular = kind {
save_temps || sess.opts.output_types.contains_key(&OutputType::Bitcode)
} else { save_temps }if_regular!(
205 save_temps || sess.opts.output_types.contains_key(&OutputType::Bitcode),
206 save_temps
207 ),
208 emit_ir: if let ModuleKind::Regular = kind {
sess.opts.output_types.contains_key(&OutputType::LlvmAssembly)
} else { false }if_regular!(
209 sess.opts.output_types.contains_key(&OutputType::LlvmAssembly),
210false
211),
212 emit_asm: if let ModuleKind::Regular = kind {
sess.opts.output_types.contains_key(&OutputType::Assembly)
} else { false }if_regular!(
213 sess.opts.output_types.contains_key(&OutputType::Assembly),
214false
215),
216emit_obj,
217 emit_thin_lto_summary: if let ModuleKind::Regular = kind {
sess.opts.output_types.contains_key(&OutputType::ThinLinkBitcode)
} else { false }if_regular!(
218 sess.opts.output_types.contains_key(&OutputType::ThinLinkBitcode),
219false
220),
221222 verify_llvm_ir: sess.verify_llvm_ir(),
223 lint_llvm_ir: sess.opts.unstable_opts.lint_llvm_ir,
224 no_prepopulate_passes: sess.opts.cg.no_prepopulate_passes,
225 no_builtins: no_builtins || sess.target.no_builtins,
226227// Copy what clang does by turning on loop vectorization at O2 and
228 // slp vectorization at O3.
229vectorize_loop: !sess.opts.cg.no_vectorize_loops
230 && (sess.opts.optimize == config::OptLevel::More231 || sess.opts.optimize == config::OptLevel::Aggressive),
232 vectorize_slp: !sess.opts.cg.no_vectorize_slp
233 && sess.opts.optimize == config::OptLevel::Aggressive,
234235// Some targets (namely, NVPTX) interact badly with the
236 // MergeFunctions pass. This is because MergeFunctions can generate
237 // new function calls which may interfere with the target calling
238 // convention; e.g. for the NVPTX target, PTX kernels should not
239 // call other PTX kernels. MergeFunctions can also be configured to
240 // generate aliases instead, but aliases are not supported by some
241 // backends (again, NVPTX). Therefore, allow targets to opt out of
242 // the MergeFunctions pass, but otherwise keep the pass enabled (at
243 // O2 and O3) since it can be useful for reducing code size.
244merge_functions: match sess245 .opts
246 .unstable_opts
247 .merge_functions
248 .unwrap_or(sess.target.merge_functions)
249 {
250 MergeFunctions::Disabled => false,
251 MergeFunctions::Trampolines | MergeFunctions::Aliases => {
252use config::OptLevel::*;
253match sess.opts.optimize {
254Aggressive | More | SizeMin | Size => true,
255Less | No => false,
256 }
257 }
258 },
259260 emit_lifetime_markers: sess.emit_lifetime_markers(),
261 llvm_plugins: if let ModuleKind::Regular = kind {
sess.opts.unstable_opts.llvm_plugins.clone()
} else { ::alloc::vec::Vec::new() }if_regular!(sess.opts.unstable_opts.llvm_plugins.clone(), vec![]),
262 autodiff: if let ModuleKind::Regular = kind {
sess.opts.unstable_opts.autodiff.clone()
} else { ::alloc::vec::Vec::new() }if_regular!(sess.opts.unstable_opts.autodiff.clone(), vec![]),
263 offload: if let ModuleKind::Regular = kind {
sess.opts.unstable_opts.offload.clone()
} else { ::alloc::vec::Vec::new() }if_regular!(sess.opts.unstable_opts.offload.clone(), vec![]),
264 }
265 }
266267pub fn bitcode_needed(&self) -> bool {
268self.emit_bc
269 || self.emit_thin_lto_summary
270 || self.emit_obj == EmitObj::Bitcode271 || self.emit_obj == EmitObj::ObjectCode(BitcodeSection::Full)
272 }
273274pub fn embed_bitcode(&self) -> bool {
275self.emit_obj == EmitObj::ObjectCode(BitcodeSection::Full)
276 }
277}
278279/// Configuration passed to the function returned by the `target_machine_factory`.
280pub struct TargetMachineFactoryConfig {
281/// Split DWARF is enabled in LLVM by checking that `TM.MCOptions.SplitDwarfFile` isn't empty,
282 /// so the path to the dwarf object has to be provided when we create the target machine.
283 /// This can be ignored by backends which do not need it for their Split DWARF support.
284pub split_dwarf_file: Option<PathBuf>,
285286/// The name of the output object file. Used for setting OutputFilenames in target options
287 /// so that LLVM can emit the CodeView S_OBJNAME record in pdb files
288pub output_obj_file: Option<PathBuf>,
289}
290291impl TargetMachineFactoryConfig {
292pub fn new(cgcx: &CodegenContext, module_name: &str) -> TargetMachineFactoryConfig {
293let split_dwarf_file = if cgcx.target_can_use_split_dwarf {
294cgcx.output_filenames.split_dwarf_path(
295cgcx.split_debuginfo,
296cgcx.split_dwarf_kind,
297module_name,
298 )
299 } else {
300None301 };
302303let output_obj_file =
304Some(cgcx.output_filenames.temp_path_for_cgu(OutputType::Object, module_name));
305TargetMachineFactoryConfig { split_dwarf_file, output_obj_file }
306 }
307}
308309pub type TargetMachineFactoryFn<B> = Arc<
310dyn Fn(
311DiagCtxtHandle<'_>,
312TargetMachineFactoryConfig,
313 ) -> <B as WriteBackendMethods>::TargetMachine314 + Send315 + Sync,
316>;
317318/// Additional resources used by optimize_and_codegen (not module specific)
319#[derive(#[automatically_derived]
impl ::core::clone::Clone for CodegenContext {
#[inline]
fn clone(&self) -> CodegenContext {
CodegenContext {
lto: ::core::clone::Clone::clone(&self.lto),
use_linker_plugin_lto: ::core::clone::Clone::clone(&self.use_linker_plugin_lto),
dylib_lto: ::core::clone::Clone::clone(&self.dylib_lto),
prefer_dynamic: ::core::clone::Clone::clone(&self.prefer_dynamic),
save_temps: ::core::clone::Clone::clone(&self.save_temps),
fewer_names: ::core::clone::Clone::clone(&self.fewer_names),
time_trace: ::core::clone::Clone::clone(&self.time_trace),
crate_types: ::core::clone::Clone::clone(&self.crate_types),
output_filenames: ::core::clone::Clone::clone(&self.output_filenames),
module_config: ::core::clone::Clone::clone(&self.module_config),
opt_level: ::core::clone::Clone::clone(&self.opt_level),
backend_features: ::core::clone::Clone::clone(&self.backend_features),
msvc_imps_needed: ::core::clone::Clone::clone(&self.msvc_imps_needed),
is_pe_coff: ::core::clone::Clone::clone(&self.is_pe_coff),
target_can_use_split_dwarf: ::core::clone::Clone::clone(&self.target_can_use_split_dwarf),
target_arch: ::core::clone::Clone::clone(&self.target_arch),
target_is_like_darwin: ::core::clone::Clone::clone(&self.target_is_like_darwin),
target_is_like_aix: ::core::clone::Clone::clone(&self.target_is_like_aix),
target_is_like_gpu: ::core::clone::Clone::clone(&self.target_is_like_gpu),
split_debuginfo: ::core::clone::Clone::clone(&self.split_debuginfo),
split_dwarf_kind: ::core::clone::Clone::clone(&self.split_dwarf_kind),
pointer_size: ::core::clone::Clone::clone(&self.pointer_size),
remark: ::core::clone::Clone::clone(&self.remark),
remark_dir: ::core::clone::Clone::clone(&self.remark_dir),
incr_comp_session_dir: ::core::clone::Clone::clone(&self.incr_comp_session_dir),
parallel: ::core::clone::Clone::clone(&self.parallel),
}
}
}Clone, const _: () =
{
impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
for CodegenContext {
fn encode(&self, __encoder: &mut __E) {
match *self {
CodegenContext {
lto: ref __binding_0,
use_linker_plugin_lto: ref __binding_1,
dylib_lto: ref __binding_2,
prefer_dynamic: ref __binding_3,
save_temps: ref __binding_4,
fewer_names: ref __binding_5,
time_trace: ref __binding_6,
crate_types: ref __binding_7,
output_filenames: ref __binding_8,
module_config: ref __binding_9,
opt_level: ref __binding_10,
backend_features: ref __binding_11,
msvc_imps_needed: ref __binding_12,
is_pe_coff: ref __binding_13,
target_can_use_split_dwarf: ref __binding_14,
target_arch: ref __binding_15,
target_is_like_darwin: ref __binding_16,
target_is_like_aix: ref __binding_17,
target_is_like_gpu: ref __binding_18,
split_debuginfo: ref __binding_19,
split_dwarf_kind: ref __binding_20,
pointer_size: ref __binding_21,
remark: ref __binding_22,
remark_dir: ref __binding_23,
incr_comp_session_dir: ref __binding_24,
parallel: ref __binding_25 } => {
::rustc_serialize::Encodable::<__E>::encode(__binding_0,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_1,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_2,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_3,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_4,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_5,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_6,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_7,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_8,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_9,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_10,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_11,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_12,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_13,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_14,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_15,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_16,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_17,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_18,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_19,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_20,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_21,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_22,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_23,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_24,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_25,
__encoder);
}
}
}
}
};Encodable, const _: () =
{
impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
for CodegenContext {
fn decode(__decoder: &mut __D) -> Self {
CodegenContext {
lto: ::rustc_serialize::Decodable::decode(__decoder),
use_linker_plugin_lto: ::rustc_serialize::Decodable::decode(__decoder),
dylib_lto: ::rustc_serialize::Decodable::decode(__decoder),
prefer_dynamic: ::rustc_serialize::Decodable::decode(__decoder),
save_temps: ::rustc_serialize::Decodable::decode(__decoder),
fewer_names: ::rustc_serialize::Decodable::decode(__decoder),
time_trace: ::rustc_serialize::Decodable::decode(__decoder),
crate_types: ::rustc_serialize::Decodable::decode(__decoder),
output_filenames: ::rustc_serialize::Decodable::decode(__decoder),
module_config: ::rustc_serialize::Decodable::decode(__decoder),
opt_level: ::rustc_serialize::Decodable::decode(__decoder),
backend_features: ::rustc_serialize::Decodable::decode(__decoder),
msvc_imps_needed: ::rustc_serialize::Decodable::decode(__decoder),
is_pe_coff: ::rustc_serialize::Decodable::decode(__decoder),
target_can_use_split_dwarf: ::rustc_serialize::Decodable::decode(__decoder),
target_arch: ::rustc_serialize::Decodable::decode(__decoder),
target_is_like_darwin: ::rustc_serialize::Decodable::decode(__decoder),
target_is_like_aix: ::rustc_serialize::Decodable::decode(__decoder),
target_is_like_gpu: ::rustc_serialize::Decodable::decode(__decoder),
split_debuginfo: ::rustc_serialize::Decodable::decode(__decoder),
split_dwarf_kind: ::rustc_serialize::Decodable::decode(__decoder),
pointer_size: ::rustc_serialize::Decodable::decode(__decoder),
remark: ::rustc_serialize::Decodable::decode(__decoder),
remark_dir: ::rustc_serialize::Decodable::decode(__decoder),
incr_comp_session_dir: ::rustc_serialize::Decodable::decode(__decoder),
parallel: ::rustc_serialize::Decodable::decode(__decoder),
}
}
}
};Decodable)]
320pub struct CodegenContext {
321// Resources needed when running LTO
322pub lto: Lto,
323pub use_linker_plugin_lto: bool,
324pub dylib_lto: bool,
325pub prefer_dynamic: bool,
326pub save_temps: bool,
327pub fewer_names: bool,
328pub time_trace: bool,
329pub crate_types: Vec<CrateType>,
330pub output_filenames: Arc<OutputFilenames>,
331pub module_config: Arc<ModuleConfig>,
332pub opt_level: OptLevel,
333pub backend_features: Vec<String>,
334pub msvc_imps_needed: bool,
335pub is_pe_coff: bool,
336pub target_can_use_split_dwarf: bool,
337pub target_arch: String,
338pub target_is_like_darwin: bool,
339pub target_is_like_aix: bool,
340pub target_is_like_gpu: bool,
341pub split_debuginfo: rustc_target::spec::SplitDebuginfo,
342pub split_dwarf_kind: rustc_session::config::SplitDwarfKind,
343pub pointer_size: Size,
344345/// LLVM optimizations for which we want to print remarks.
346pub remark: Passes,
347/// Directory into which should the LLVM optimization remarks be written.
348 /// If `None`, they will be written to stderr.
349pub remark_dir: Option<PathBuf>,
350/// The incremental compilation session directory, or None if we are not
351 /// compiling incrementally
352pub incr_comp_session_dir: Option<PathBuf>,
353/// `true` if the codegen should be run in parallel.
354 ///
355 /// Depends on [`ExtraBackendMethods::supports_parallel()`] and `-Zno_parallel_backend`.
356pub parallel: bool,
357}
358359fn generate_thin_lto_work<B: WriteBackendMethods>(
360 cgcx: &CodegenContext,
361 prof: &SelfProfilerRef,
362 dcx: DiagCtxtHandle<'_>,
363 exported_symbols_for_lto: &[String],
364 each_linked_rlib_for_lto: &[PathBuf],
365 needs_thin_lto: Vec<ThinLtoInput<B>>,
366) -> Vec<(ThinLtoWorkItem<B>, u64)> {
367let _prof_timer = prof.generic_activity("codegen_thin_generate_lto_work");
368369let (lto_modules, copy_jobs) = B::run_thin_lto(
370cgcx,
371prof,
372dcx,
373exported_symbols_for_lto,
374each_linked_rlib_for_lto,
375needs_thin_lto,
376 );
377lto_modules378 .into_iter()
379 .map(|module| {
380let cost = module.cost();
381 (ThinLtoWorkItem::ThinLto(module), cost)
382 })
383 .chain(copy_jobs.into_iter().map(|wp| {
384 (
385 ThinLtoWorkItem::CopyPostLtoArtifacts(CachedModuleCodegen {
386 name: wp.cgu_name.clone(),
387 source: wp,
388 }),
3890, // copying is very cheap
390)
391 }))
392 .collect()
393}
394395enum MaybeLtoModules<B: WriteBackendMethods> {
396 NoLto(CompiledModules),
397 FatLto { cgcx: CodegenContext, needs_fat_lto: Vec<FatLtoInput<B>> },
398 ThinLto { cgcx: CodegenContext, needs_thin_lto: Vec<ThinLtoInput<B>> },
399}
400401fn need_bitcode_in_object(tcx: TyCtxt<'_>) -> bool {
402let sess = tcx.sess;
403sess.opts.cg.embed_bitcode
404 && tcx.crate_types().contains(&CrateType::Rlib)
405 && sess.opts.output_types.contains_key(&OutputType::Exe)
406}
407408fn need_pre_lto_bitcode_for_incr_comp(sess: &Session) -> bool {
409if sess.opts.incremental.is_none() {
410return false;
411 }
412413match sess.lto() {
414 Lto::No => false,
415 Lto::Fat | Lto::Thin | Lto::ThinLocal => true,
416 }
417}
418419pub(crate) fn start_async_codegen<B: ExtraBackendMethods>(
420 backend: B,
421 tcx: TyCtxt<'_>,
422 allocator_module: Option<ModuleCodegen<B::Module>>,
423) -> OngoingCodegen<B> {
424let (coordinator_send, coordinator_receive) = channel();
425426let no_builtins = {
'done:
{
for i in tcx.hir_krate_attrs() {
#[allow(unused_imports)]
use rustc_hir::attrs::AttributeKind::*;
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(NoBuiltins) => {
break 'done Some(());
}
rustc_hir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}.is_some()find_attr!(tcx, crate, NoBuiltins);
427428let regular_config = ModuleConfig::new(ModuleKind::Regular, tcx, no_builtins);
429let allocator_config = ModuleConfig::new(ModuleKind::Allocator, tcx, no_builtins);
430431let (shared_emitter, shared_emitter_main) = SharedEmitter::new();
432let (codegen_worker_send, codegen_worker_receive) = channel();
433434let coordinator_thread = start_executing_work(
435backend.clone(),
436tcx,
437shared_emitter,
438codegen_worker_send,
439coordinator_receive,
440Arc::new(regular_config),
441Arc::new(allocator_config),
442allocator_module,
443coordinator_send.clone(),
444 );
445446OngoingCodegen {
447backend,
448449codegen_worker_receive,
450shared_emitter_main,
451 coordinator: Coordinator {
452 sender: coordinator_send,
453 future: Some(coordinator_thread),
454 phantom: PhantomData,
455 },
456 output_filenames: Arc::clone(tcx.output_filenames(())),
457 }
458}
459460fn copy_all_cgu_workproducts_to_incr_comp_cache_dir(
461 sess: &Session,
462 compiled_modules: &CompiledModules,
463) -> FxIndexMap<WorkProductId, WorkProduct> {
464let mut work_products = FxIndexMap::default();
465466if sess.opts.incremental.is_none() {
467return work_products;
468 }
469470let _timer = sess.timer("copy_all_cgu_workproducts_to_incr_comp_cache_dir");
471472for module in compiled_modules.modules.iter().filter(|m| m.kind == ModuleKind::Regular) {
473let mut files = Vec::new();
474if let Some(object_file_path) = &module.object {
475 files.push((OutputType::Object.extension(), object_file_path.as_path()));
476 }
477if let Some(dwarf_object_file_path) = &module.dwarf_object {
478 files.push(("dwo", dwarf_object_file_path.as_path()));
479 }
480if let Some(path) = &module.assembly {
481 files.push((OutputType::Assembly.extension(), path.as_path()));
482 }
483if let Some(path) = &module.llvm_ir {
484 files.push((OutputType::LlvmAssembly.extension(), path.as_path()));
485 }
486if let Some(path) = &module.bytecode {
487 files.push((OutputType::Bitcode.extension(), path.as_path()));
488 }
489if let Some((id, product)) = copy_cgu_workproduct_to_incr_comp_cache_dir(
490 sess,
491&module.name,
492 files.as_slice(),
493&module.links_from_incr_cache,
494 ) {
495 work_products.insert(id, product);
496 }
497 }
498499work_products500}
501502pub fn produce_final_output_artifacts(
503 sess: &Session,
504 compiled_modules: &CompiledModules,
505 crate_output: &OutputFilenames,
506) {
507let mut user_wants_bitcode = false;
508let mut user_wants_objects = false;
509510// Produce final compile outputs.
511let copy_gracefully = |from: &Path, to: &OutFileName| match to {
512 OutFileName::Stdoutif let Err(e) = copy_to_stdout(from) => {
513sess.dcx().emit_err(errors::CopyPath::new(from, to.as_path(), e));
514 }
515 OutFileName::Real(path) if let Err(e) = fs::copy(from, path) => {
516sess.dcx().emit_err(errors::CopyPath::new(from, path, e));
517 }
518_ => {}
519 };
520521let copy_if_one_unit = |output_type: OutputType, keep_numbered: bool| {
522if let [module] = &compiled_modules.modules[..] {
523// 1) Only one codegen unit. In this case it's no difficulty
524 // to copy `foo.0.x` to `foo.x`.
525let path = crate_output.temp_path_for_cgu(output_type, &module.name);
526let output = crate_output.path(output_type);
527if !output_type.is_text_output() && output.is_tty() {
528sess.dcx()
529 .emit_err(errors::BinaryOutputToTty { shorthand: output_type.shorthand() });
530 } else {
531copy_gracefully(&path, &output);
532 }
533if !sess.opts.cg.save_temps && !keep_numbered {
534// The user just wants `foo.x`, not `foo.#module-name#.x`.
535ensure_removed(sess.dcx(), &path);
536 }
537 } else {
538if crate_output.outputs.contains_explicit_name(&output_type) {
539// 2) Multiple codegen units, with `--emit foo=some_name`. We have
540 // no good solution for this case, so warn the user.
541sess.dcx()
542 .emit_warn(errors::IgnoringEmitPath { extension: output_type.extension() });
543 } else if crate_output.single_output_file.is_some() {
544// 3) Multiple codegen units, with `-o some_name`. We have
545 // no good solution for this case, so warn the user.
546sess.dcx().emit_warn(errors::IgnoringOutput { extension: output_type.extension() });
547 } else {
548// 4) Multiple codegen units, but no explicit name. We
549 // just leave the `foo.0.x` files in place.
550 // (We don't have to do any work in this case.)
551}
552 }
553 };
554555// Flag to indicate whether the user explicitly requested bitcode.
556 // Otherwise, we produced it only as a temporary output, and will need
557 // to get rid of it.
558for output_type in crate_output.outputs.keys() {
559match *output_type {
560 OutputType::Bitcode => {
561 user_wants_bitcode = true;
562// Copy to .bc, but always keep the .0.bc. There is a later
563 // check to figure out if we should delete .0.bc files, or keep
564 // them for making an rlib.
565copy_if_one_unit(OutputType::Bitcode, true);
566 }
567 OutputType::ThinLinkBitcode => {
568 copy_if_one_unit(OutputType::ThinLinkBitcode, false);
569 }
570 OutputType::LlvmAssembly => {
571 copy_if_one_unit(OutputType::LlvmAssembly, false);
572 }
573 OutputType::Assembly => {
574 copy_if_one_unit(OutputType::Assembly, false);
575 }
576 OutputType::Object => {
577 user_wants_objects = true;
578 copy_if_one_unit(OutputType::Object, true);
579 }
580 OutputType::Mir | OutputType::Metadata | OutputType::Exe | OutputType::DepInfo => {}
581 }
582 }
583584// Clean up unwanted temporary files.
585586 // We create the following files by default:
587 // - #crate#.#module-name#.rcgu.bc
588 // - #crate#.#module-name#.rcgu.o
589 // - #crate#.o (linked from crate.##.rcgu.o)
590 // - #crate#.bc (copied from crate.##.rcgu.bc)
591 // We may create additional files if requested by the user (through
592 // `-C save-temps` or `--emit=` flags).
593594if !sess.opts.cg.save_temps {
595// Remove the temporary .#module-name#.rcgu.o objects. If the user didn't
596 // explicitly request bitcode (with --emit=bc), and the bitcode is not
597 // needed for building an rlib, then we must remove .#module-name#.bc as
598 // well.
599600 // Specific rules for keeping .#module-name#.rcgu.bc:
601 // - If the user requested bitcode (`user_wants_bitcode`), and
602 // codegen_units > 1, then keep it.
603 // - If the user requested bitcode but codegen_units == 1, then we
604 // can toss .#module-name#.rcgu.bc because we copied it to .bc earlier.
605 // - If we're not building an rlib and the user didn't request
606 // bitcode, then delete .#module-name#.rcgu.bc.
607 // If you change how this works, also update back::link::link_rlib,
608 // where .#module-name#.rcgu.bc files are (maybe) deleted after making an
609 // rlib.
610let needs_crate_object = crate_output.outputs.contains_key(&OutputType::Exe);
611612let keep_numbered_bitcode = user_wants_bitcode && sess.codegen_units().as_usize() > 1;
613614let keep_numbered_objects =
615needs_crate_object || (user_wants_objects && sess.codegen_units().as_usize() > 1);
616617for module in compiled_modules.modules.iter() {
618if !keep_numbered_objects {
619if let Some(ref path) = module.object {
620 ensure_removed(sess.dcx(), path);
621 }
622623if let Some(ref path) = module.dwarf_object {
624 ensure_removed(sess.dcx(), path);
625 }
626 }
627628if let Some(ref path) = module.bytecode {
629if !keep_numbered_bitcode {
630 ensure_removed(sess.dcx(), path);
631 }
632 }
633 }
634635if !user_wants_bitcode636 && let Some(ref allocator_module) = compiled_modules.allocator_module
637 && let Some(ref path) = allocator_module.bytecode
638 {
639ensure_removed(sess.dcx(), path);
640 }
641 }
642643if sess.opts.json_artifact_notifications {
644if let [module] = &compiled_modules.modules[..] {
645module.for_each_output(|_path, ty| {
646if sess.opts.output_types.contains_key(&ty) {
647let descr = ty.shorthand();
648// for single cgu file is renamed to drop cgu specific suffix
649 // so we regenerate it the same way
650let path = crate_output.path(ty);
651sess.dcx().emit_artifact_notification(path.as_path(), descr);
652 }
653 });
654 } else {
655for module in &compiled_modules.modules {
656 module.for_each_output(|path, ty| {
657if sess.opts.output_types.contains_key(&ty) {
658let descr = ty.shorthand();
659 sess.dcx().emit_artifact_notification(&path, descr);
660 }
661 });
662 }
663 }
664 }
665666// We leave the following files around by default:
667 // - #crate#.o
668 // - #crate#.bc
669 // These are used in linking steps and will be cleaned up afterward.
670}
671672pub(crate) enum WorkItem<B: WriteBackendMethods> {
673/// Optimize a newly codegened, totally unoptimized module.
674Optimize(ModuleCodegen<B::Module>),
675/// Copy the post-LTO artifacts from the incremental cache to the output
676 /// directory.
677CopyPostLtoArtifacts(CachedModuleCodegen),
678}
679680enum ThinLtoWorkItem<B: WriteBackendMethods> {
681/// Copy the post-LTO artifacts from the incremental cache to the output
682 /// directory.
683CopyPostLtoArtifacts(CachedModuleCodegen),
684/// Performs thin-LTO on the given module.
685ThinLto(lto::ThinModule<B>),
686}
687688// `pthread_setname()` on *nix ignores anything beyond the first 15
689// bytes. Use short descriptions to maximize the space available for
690// the module name.
691#[cfg(not(windows))]
692fn desc(short: &str, _long: &str, name: &str) -> String {
693// The short label is three bytes, and is followed by a space. That
694 // leaves 11 bytes for the CGU name. How we obtain those 11 bytes
695 // depends on the CGU name form.
696 //
697 // - Non-incremental, e.g. `regex.f10ba03eb5ec7975-cgu.0`: the part
698 // before the `-cgu.0` is the same for every CGU, so use the
699 // `cgu.0` part. The number suffix will be different for each
700 // CGU.
701 //
702 // - Incremental (normal), e.g. `2i52vvl2hco29us0`: use the whole
703 // name because each CGU will have a unique ASCII hash, and the
704 // first 11 bytes will be enough to identify it.
705 //
706 // - Incremental (with `-Zhuman-readable-cgu-names`), e.g.
707 // `regex.f10ba03eb5ec7975-re_builder.volatile`: use the whole
708 // name. The first 11 bytes won't be enough to uniquely identify
709 // it, but no obvious substring will, and this is a rarely used
710 // option so it doesn't matter much.
711 //
712match (&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);
713let name = if let Some(index) = name.find("-cgu.") {
714&name[index + 1..] // +1 skips the leading '-'.
715} else {
716name717 };
718::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} {1}", short, name))
})format!("{short} {name}")719}
720721// Windows has no thread name length limit, so use more descriptive names.
722#[cfg(windows)]
723fn desc(_short: &str, long: &str, name: &str) -> String {
724format!("{long} {name}")
725}
726727impl<B: WriteBackendMethods> WorkItem<B> {
728/// Generate a short description of this work item suitable for use as a thread name.
729fn short_description(&self) -> String {
730match self {
731 WorkItem::Optimize(m) => desc("opt", "optimize module", &m.name),
732 WorkItem::CopyPostLtoArtifacts(m) => desc("cpy", "copy LTO artifacts for", &m.name),
733 }
734 }
735}
736737impl<B: WriteBackendMethods> ThinLtoWorkItem<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 ThinLtoWorkItem::CopyPostLtoArtifacts(m) => {
742desc("cpy", "copy LTO artifacts for", &m.name)
743 }
744 ThinLtoWorkItem::ThinLto(m) => desc("lto", "thin-LTO module", m.name()),
745 }
746 }
747}
748749/// A result produced by the backend.
750pub(crate) enum WorkItemResult<B: WriteBackendMethods> {
751/// The backend has finished compiling a CGU, nothing more required.
752Finished(CompiledModule),
753754/// The backend has finished compiling a CGU, which now needs to go through
755 /// fat LTO.
756NeedsFatLto(FatLtoInput<B>),
757758/// The backend has finished compiling a CGU, which now needs to go through
759 /// thin LTO.
760NeedsThinLto(String, B::ModuleBuffer),
761}
762763pub enum FatLtoInput<B: WriteBackendMethods> {
764 Serialized { name: String, bitcode_path: PathBuf },
765 InMemory(ModuleCodegen<B::Module>),
766}
767768pub enum ThinLtoInput<B: WriteBackendMethods> {
769 Red { name: String, buffer: SerializedModule<B::ModuleBuffer> },
770 Green { wp: WorkProduct, bitcode_path: PathBuf },
771}
772773/// Actual LTO type we end up choosing based on multiple factors.
774pub(crate) enum ComputedLtoType {
775 No,
776 Thin,
777 Fat,
778}
779780pub(crate) fn compute_per_cgu_lto_type(
781 sess_lto: &Lto,
782 linker_does_lto: bool,
783 sess_crate_types: &[CrateType],
784) -> ComputedLtoType {
785// If the linker does LTO, we don't have to do it. Note that we
786 // keep doing full LTO, if it is requested, as not to break the
787 // assumption that the output will be a single module.
788789 // We ignore a request for full crate graph LTO if the crate type
790 // is only an rlib, as there is no full crate graph to process,
791 // that'll happen later.
792 //
793 // This use case currently comes up primarily for targets that
794 // require LTO so the request for LTO is always unconditionally
795 // passed down to the backend, but we don't actually want to do
796 // anything about it yet until we've got a final product.
797let is_rlib = #[allow(non_exhaustive_omitted_patterns)] match sess_crate_types {
[CrateType::Rlib] => true,
_ => false,
}matches!(sess_crate_types, [CrateType::Rlib]);
798799match sess_lto {
800 Lto::ThinLocalif !linker_does_lto => ComputedLtoType::Thin,
801 Lto::Thinif !linker_does_lto && !is_rlib => ComputedLtoType::Thin,
802 Lto::Fatif !is_rlib => ComputedLtoType::Fat,
803_ => ComputedLtoType::No,
804 }
805}
806807fn execute_optimize_work_item<B: WriteBackendMethods>(
808 cgcx: &CodegenContext,
809 prof: &SelfProfilerRef,
810 shared_emitter: SharedEmitter,
811mut module: ModuleCodegen<B::Module>,
812) -> WorkItemResult<B> {
813let _timer = prof.generic_activity_with_arg("codegen_module_optimize", &*module.name);
814815 B::optimize(cgcx, prof, &shared_emitter, &mut module, &cgcx.module_config);
816817// After we've done the initial round of optimizations we need to
818 // decide whether to synchronously codegen this module or ship it
819 // back to the coordinator thread for further LTO processing (which
820 // has to wait for all the initial modules to be optimized).
821822let lto_type =
823compute_per_cgu_lto_type(&cgcx.lto, cgcx.use_linker_plugin_lto, &cgcx.crate_types);
824825// If we're doing some form of incremental LTO then we need to be sure to
826 // save our module to disk first.
827let bitcode = if cgcx.module_config.emit_pre_lto_bc {
828let filename = pre_lto_bitcode_filename(&module.name);
829cgcx.incr_comp_session_dir.as_ref().map(|path| path.join(&filename))
830 } else {
831None832 };
833834match lto_type {
835 ComputedLtoType::No => {
836let module = B::codegen(cgcx, &prof, &shared_emitter, module, &cgcx.module_config);
837 WorkItemResult::Finished(module)
838 }
839 ComputedLtoType::Thin => {
840let thin_buffer = B::serialize_module(module.module_llvm, true);
841if let Some(path) = bitcode {
842 fs::write(&path, thin_buffer.data()).unwrap_or_else(|e| {
843{
::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);
844 });
845 }
846 WorkItemResult::NeedsThinLto(module.name, thin_buffer)
847 }
848 ComputedLtoType::Fat => match bitcode {
849Some(path) => {
850let buffer = B::serialize_module(module.module_llvm, false);
851 fs::write(&path, buffer.data()).unwrap_or_else(|e| {
852{
::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);
853 });
854 WorkItemResult::NeedsFatLto(FatLtoInput::Serialized {
855 name: module.name,
856 bitcode_path: path,
857 })
858 }
859None => WorkItemResult::NeedsFatLto(FatLtoInput::InMemory(module)),
860 },
861 }
862}
863864fn execute_copy_from_cache_work_item(
865 cgcx: &CodegenContext,
866 prof: &SelfProfilerRef,
867 shared_emitter: SharedEmitter,
868 module: CachedModuleCodegen,
869) -> CompiledModule {
870let _timer =
871prof.generic_activity_with_arg("codegen_copy_artifacts_from_incr_cache", &*module.name);
872873let dcx = DiagCtxt::new(Box::new(shared_emitter));
874let dcx = dcx.handle();
875876let incr_comp_session_dir = cgcx.incr_comp_session_dir.as_ref().unwrap();
877878let mut links_from_incr_cache = Vec::new();
879880let mut load_from_incr_comp_dir = |output_path: PathBuf, saved_path: &str| {
881let source_file = in_incr_comp_dir(incr_comp_session_dir, saved_path);
882{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/back/write.rs:882",
"rustc_codegen_ssa::back::write", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/back/write.rs"),
::tracing_core::__macro_support::Option::Some(882u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::write"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("copying preexisting module `{0}` from {1:?} to {2}",
module.name, source_file, output_path.display()) as
&dyn Value))])
});
} else { ; }
};debug!(
883"copying preexisting module `{}` from {:?} to {}",
884 module.name,
885 source_file,
886 output_path.display()
887 );
888match link_or_copy(&source_file, &output_path) {
889Ok(_) => {
890links_from_incr_cache.push(source_file);
891Some(output_path)
892 }
893Err(error) => {
894dcx.emit_err(errors::CopyPathBuf { source_file, output_path, error });
895None896 }
897 }
898 };
899900let dwarf_object =
901module.source.saved_files.get("dwo").as_ref().and_then(|saved_dwarf_object_file| {
902let dwarf_obj_out = cgcx903 .output_filenames
904 .split_dwarf_path(cgcx.split_debuginfo, cgcx.split_dwarf_kind, &module.name)
905 .expect(
906"saved dwarf object in work product but `split_dwarf_path` returned `None`",
907 );
908load_from_incr_comp_dir(dwarf_obj_out, saved_dwarf_object_file)
909 });
910911let mut load_from_incr_cache = |perform, output_type: OutputType| {
912if perform {
913let saved_file = module.source.saved_files.get(output_type.extension())?;
914let output_path = cgcx.output_filenames.temp_path_for_cgu(output_type, &module.name);
915load_from_incr_comp_dir(output_path, &saved_file)
916 } else {
917None918 }
919 };
920921let module_config = &cgcx.module_config;
922let should_emit_obj = module_config.emit_obj != EmitObj::None;
923let assembly = load_from_incr_cache(module_config.emit_asm, OutputType::Assembly);
924let llvm_ir = load_from_incr_cache(module_config.emit_ir, OutputType::LlvmAssembly);
925let bytecode = load_from_incr_cache(module_config.emit_bc, OutputType::Bitcode);
926let object = load_from_incr_cache(should_emit_obj, OutputType::Object);
927if should_emit_obj && object.is_none() {
928dcx.emit_fatal(errors::NoSavedObjectFile { cgu_name: &module.name })
929 }
930931CompiledModule {
932links_from_incr_cache,
933 kind: ModuleKind::Regular,
934 name: module.name,
935object,
936dwarf_object,
937bytecode,
938assembly,
939llvm_ir,
940 }
941}
942943fn do_fat_lto<B: WriteBackendMethods>(
944 sess: &Session,
945 cgcx: &CodegenContext,
946 shared_emitter: SharedEmitter,
947 tm_factory: TargetMachineFactoryFn<B>,
948 exported_symbols_for_lto: &[String],
949 each_linked_rlib_for_lto: &[PathBuf],
950 needs_fat_lto: Vec<FatLtoInput<B>>,
951) -> CompiledModule {
952let _timer = sess.prof.verbose_generic_activity("LLVM_fatlto");
953954let dcx = DiagCtxt::new(Box::new(shared_emitter.clone()));
955let dcx = dcx.handle();
956957check_lto_allowed(&cgcx, dcx);
958959 B::optimize_and_codegen_fat_lto(
960sess,
961cgcx,
962&shared_emitter,
963tm_factory,
964exported_symbols_for_lto,
965each_linked_rlib_for_lto,
966needs_fat_lto,
967 )
968}
969970fn do_thin_lto<B: WriteBackendMethods>(
971 cgcx: &CodegenContext,
972 prof: &SelfProfilerRef,
973 shared_emitter: SharedEmitter,
974 tm_factory: TargetMachineFactoryFn<B>,
975 exported_symbols_for_lto: &[String],
976 each_linked_rlib_for_lto: &[PathBuf],
977 needs_thin_lto: Vec<ThinLtoInput<B>>,
978) -> Vec<CompiledModule> {
979let _timer = prof.verbose_generic_activity("LLVM_thinlto");
980981let dcx = DiagCtxt::new(Box::new(shared_emitter.clone()));
982let dcx = dcx.handle();
983984check_lto_allowed(&cgcx, dcx);
985986let (coordinator_send, coordinator_receive) = channel();
987988// First up, convert our jobserver into a helper thread so we can use normal
989 // mpsc channels to manage our messages and such.
990 // After we've requested tokens then we'll, when we can,
991 // get tokens on `coordinator_receive` which will
992 // get managed in the main loop below.
993let coordinator_send2 = coordinator_send.clone();
994let helper = jobserver::client()
995 .into_helper_thread(move |token| {
996drop(coordinator_send2.send(ThinLtoMessage::Token(token)));
997 })
998 .expect("failed to spawn helper thread");
9991000let mut work_items = ::alloc::vec::Vec::new()vec![];
10011002// We have LTO work to do. Perform the serial work here of
1003 // figuring out what we're going to LTO and then push a
1004 // bunch of work items onto our queue to do LTO. This all
1005 // happens on the coordinator thread but it's very quick so
1006 // we don't worry about tokens.
1007for (work, cost) in generate_thin_lto_work::<B>(
1008 cgcx,
1009 prof,
1010 dcx,
1011&exported_symbols_for_lto,
1012&each_linked_rlib_for_lto,
1013 needs_thin_lto,
1014 ) {
1015let insertion_index =
1016 work_items.binary_search_by_key(&cost, |&(_, cost)| cost).unwrap_or_else(|e| e);
1017 work_items.insert(insertion_index, (work, cost));
1018if cgcx.parallel {
1019 helper.request_token();
1020 }
1021 }
10221023let mut codegen_aborted = None;
10241025// These are the Jobserver Tokens we currently hold. Does not include
1026 // the implicit Token the compiler process owns no matter what.
1027let mut tokens = ::alloc::vec::Vec::new()vec![];
10281029// Amount of tokens that are used (including the implicit token).
1030let mut used_token_count = 0;
10311032let mut compiled_modules = ::alloc::vec::Vec::new()vec![];
10331034// Run the message loop while there's still anything that needs message
1035 // processing. Note that as soon as codegen is aborted we simply want to
1036 // wait for all existing work to finish, so many of the conditions here
1037 // only apply if codegen hasn't been aborted as they represent pending
1038 // work to be done.
1039loop {
1040if codegen_aborted.is_none() {
1041if used_token_count == 0 && work_items.is_empty() {
1042// All codegen work is done.
1043break;
1044 }
10451046// Spin up what work we can, only doing this while we've got available
1047 // parallelism slots and work left to spawn.
1048while used_token_count < tokens.len() + 1
1049&& let Some((item, _)) = work_items.pop()
1050 {
1051 spawn_thin_lto_work(
1052&cgcx,
1053 prof,
1054 shared_emitter.clone(),
1055 Arc::clone(&tm_factory),
1056 coordinator_send.clone(),
1057 item,
1058 );
1059 used_token_count += 1;
1060 }
1061 } else {
1062// Don't queue up any more work if codegen was aborted, we're
1063 // just waiting for our existing children to finish.
1064if used_token_count == 0 {
1065break;
1066 }
1067 }
10681069// Relinquish accidentally acquired extra tokens. Subtract 1 for the implicit token.
1070tokens.truncate(used_token_count.saturating_sub(1));
10711072match coordinator_receive.recv().unwrap() {
1073// Save the token locally and the next turn of the loop will use
1074 // this to spawn a new unit of work, or it may get dropped
1075 // immediately if we have no more work to spawn.
1076ThinLtoMessage::Token(token) => match token {
1077Ok(token) => {
1078tokens.push(token);
1079 }
1080Err(e) => {
1081let msg = &::alloc::__export::must_use({
::alloc::fmt::format(format_args!("failed to acquire jobserver token: {0}",
e))
})format!("failed to acquire jobserver token: {e}");
1082shared_emitter.fatal(msg);
1083codegen_aborted = Some(FatalError);
1084 }
1085 },
10861087 ThinLtoMessage::WorkItem { result } => {
1088// If a thread exits successfully then we drop a token associated
1089 // with that worker and update our `used_token_count` count.
1090 // We may later re-acquire a token to continue running more work.
1091 // We may also not actually drop a token here if the worker was
1092 // running with an "ephemeral token".
1093used_token_count -= 1;
10941095match result {
1096Ok(compiled_module) => compiled_modules.push(compiled_module),
1097Err(Some(WorkerFatalError)) => {
1098// Like `CodegenAborted`, wait for remaining work to finish.
1099codegen_aborted = Some(FatalError);
1100 }
1101Err(None) => {
1102// If the thread failed that means it panicked, so
1103 // we abort immediately.
1104::rustc_middle::util::bug::bug_fmt(format_args!("worker thread panicked"));bug!("worker thread panicked");
1105 }
1106 }
1107 }
1108 }
1109 }
11101111if let Some(codegen_aborted) = codegen_aborted {
1112codegen_aborted.raise();
1113 }
11141115compiled_modules1116}
11171118fn execute_thin_lto_work_item<B: WriteBackendMethods>(
1119 cgcx: &CodegenContext,
1120 prof: &SelfProfilerRef,
1121 shared_emitter: SharedEmitter,
1122 tm_factory: TargetMachineFactoryFn<B>,
1123 module: lto::ThinModule<B>,
1124) -> CompiledModule {
1125let _timer = prof.generic_activity_with_arg("codegen_module_perform_lto", module.name());
11261127 B::optimize_and_codegen_thin(cgcx, prof, &shared_emitter, tm_factory, module)
1128}
11291130/// Messages sent to the coordinator.
1131pub(crate) enum Message<B: WriteBackendMethods> {
1132/// A jobserver token has become available. Sent from the jobserver helper
1133 /// thread.
1134Token(io::Result<Acquired>),
11351136/// The backend has finished processing a work item for a codegen unit.
1137 /// Sent from a backend worker thread.
1138WorkItem { result: Result<WorkItemResult<B>, Option<WorkerFatalError>> },
11391140/// The frontend has finished generating something (backend IR or a
1141 /// post-LTO artifact) for a codegen unit, and it should be passed to the
1142 /// backend. Sent from the main thread.
1143CodegenDone { llvm_work_item: WorkItem<B>, cost: u64 },
11441145/// Similar to `CodegenDone`, but for reusing a pre-LTO artifact
1146 /// Sent from the main thread.
1147AddImportOnlyModule { bitcode_path: PathBuf, work_product: WorkProduct },
11481149/// The frontend has finished generating everything for all codegen units.
1150 /// Sent from the main thread.
1151CodegenComplete,
11521153/// Some normal-ish compiler error occurred, and codegen should be wound
1154 /// down. Sent from the main thread.
1155CodegenAborted,
1156}
11571158/// Messages sent to the coordinator.
1159pub(crate) enum ThinLtoMessage {
1160/// A jobserver token has become available. Sent from the jobserver helper
1161 /// thread.
1162Token(io::Result<Acquired>),
11631164/// The backend has finished processing a work item for a codegen unit.
1165 /// Sent from a backend worker thread.
1166WorkItem { result: Result<CompiledModule, Option<WorkerFatalError>> },
1167}
11681169/// A message sent from the coordinator thread to the main thread telling it to
1170/// process another codegen unit.
1171pub struct CguMessage;
11721173// A cut-down version of `rustc_errors::DiagInner` that impls `Send`, which
1174// can be used to send diagnostics from codegen threads to the main thread.
1175// It's missing the following fields from `rustc_errors::DiagInner`.
1176// - `span`: it doesn't impl `Send`.
1177// - `suggestions`: it doesn't impl `Send`, and isn't used for codegen
1178// diagnostics.
1179// - `sort_span`: it doesn't impl `Send`.
1180// - `is_lint`: lints aren't relevant during codegen.
1181// - `emitted_at`: not used for codegen diagnostics.
1182struct Diagnostic {
1183 span: Vec<SpanData>,
1184 level: Level,
1185 messages: Vec<(DiagMessage, Style)>,
1186 code: Option<ErrCode>,
1187 children: Vec<Subdiagnostic>,
1188 args: DiagArgMap,
1189}
11901191// A cut-down version of `rustc_errors::Subdiag` that impls `Send`. It's
1192// missing the following fields from `rustc_errors::Subdiag`.
1193// - `span`: it doesn't impl `Send`.
1194struct Subdiagnostic {
1195 level: Level,
1196 messages: Vec<(DiagMessage, Style)>,
1197}
11981199#[derive(#[automatically_derived]
impl ::core::cmp::PartialEq for MainThreadState {
#[inline]
fn eq(&self, other: &MainThreadState) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq, #[automatically_derived]
impl ::core::clone::Clone for MainThreadState {
#[inline]
fn clone(&self) -> MainThreadState { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for MainThreadState { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for MainThreadState {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
MainThreadState::Idle => "Idle",
MainThreadState::Codegenning => "Codegenning",
MainThreadState::Lending => "Lending",
})
}
}Debug)]
1200enum MainThreadState {
1201/// Doing nothing.
1202Idle,
12031204/// Doing codegen, i.e. MIR-to-LLVM-IR conversion.
1205Codegenning,
12061207/// Idle, but lending the compiler process's Token to an LLVM thread so it can do useful work.
1208Lending,
1209}
12101211fn start_executing_work<B: ExtraBackendMethods>(
1212 backend: B,
1213 tcx: TyCtxt<'_>,
1214 shared_emitter: SharedEmitter,
1215 codegen_worker_send: Sender<CguMessage>,
1216 coordinator_receive: Receiver<Message<B>>,
1217 regular_config: Arc<ModuleConfig>,
1218 allocator_config: Arc<ModuleConfig>,
1219mut allocator_module: Option<ModuleCodegen<B::Module>>,
1220 coordinator_send: Sender<Message<B>>,
1221) -> thread::JoinHandle<Result<MaybeLtoModules<B>, ()>> {
1222let sess = tcx.sess;
1223let prof = sess.prof.clone();
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.
1234let coordinator_send2 = coordinator_send.clone();
1235let helper = jobserver::client()
1236 .into_helper_thread(move |token| {
1237drop(coordinator_send2.send(Message::Token::<B>(token)));
1238 })
1239 .expect("failed to spawn helper thread");
12401241let opt_level = tcx.backend_optimization_level(());
1242let backend_features = tcx.global_backend_features(()).clone();
1243let tm_factory = backend.target_machine_factory(tcx.sess, opt_level, &backend_features);
12441245let remark_dir = if let Some(ref dir) = sess.opts.unstable_opts.remark_dir {
1246let result = fs::create_dir_all(dir).and_then(|_| dir.canonicalize());
1247match result {
1248Ok(dir) => Some(dir),
1249Err(error) => sess.dcx().emit_fatal(ErrorCreatingRemarkDir { error }),
1250 }
1251 } else {
1252None1253 };
12541255let cgcx = CodegenContext {
1256 crate_types: tcx.crate_types().to_vec(),
1257 lto: sess.lto(),
1258 use_linker_plugin_lto: sess.opts.cg.linker_plugin_lto.enabled(),
1259 dylib_lto: sess.opts.unstable_opts.dylib_lto,
1260 prefer_dynamic: sess.opts.cg.prefer_dynamic,
1261 fewer_names: sess.fewer_names(),
1262 save_temps: sess.opts.cg.save_temps,
1263 time_trace: sess.opts.unstable_opts.llvm_time_trace,
1264 remark: sess.opts.cg.remark.clone(),
1265remark_dir,
1266 incr_comp_session_dir: sess.incr_comp_session_dir_opt().map(|r| r.clone()),
1267 output_filenames: Arc::clone(tcx.output_filenames(())),
1268 module_config: regular_config,
1269opt_level,
1270backend_features,
1271 msvc_imps_needed: msvc_imps_needed(tcx),
1272 is_pe_coff: tcx.sess.target.is_like_windows,
1273 target_can_use_split_dwarf: tcx.sess.target_can_use_split_dwarf(),
1274 target_arch: tcx.sess.target.arch.to_string(),
1275 target_is_like_darwin: tcx.sess.target.is_like_darwin,
1276 target_is_like_aix: tcx.sess.target.is_like_aix,
1277 target_is_like_gpu: tcx.sess.target.is_like_gpu,
1278 split_debuginfo: tcx.sess.split_debuginfo(),
1279 split_dwarf_kind: tcx.sess.opts.unstable_opts.split_dwarf_kind,
1280 parallel: backend.supports_parallel() && !sess.opts.unstable_opts.no_parallel_backend,
1281 pointer_size: tcx.data_layout.pointer_size(),
1282 };
12831284// This is the "main loop" of parallel work happening for parallel codegen.
1285 // It's here that we manage parallelism, schedule work, and work with
1286 // messages coming from clients.
1287 //
1288 // There are a few environmental pre-conditions that shape how the system
1289 // is set up:
1290 //
1291 // - Error reporting can only happen on the main thread because that's the
1292 // only place where we have access to the compiler `Session`.
1293 // - LLVM work can be done on any thread.
1294 // - Codegen can only happen on the main thread.
1295 // - Each thread doing substantial work must be in possession of a `Token`
1296 // from the `Jobserver`.
1297 // - The compiler process always holds one `Token`. Any additional `Tokens`
1298 // have to be requested from the `Jobserver`.
1299 //
1300 // Error Reporting
1301 // ===============
1302 // The error reporting restriction is handled separately from the rest: We
1303 // set up a `SharedEmitter` that holds an open channel to the main thread.
1304 // When an error occurs on any thread, the shared emitter will send the
1305 // error message to the receiver main thread (`SharedEmitterMain`). The
1306 // main thread will periodically query this error message queue and emit
1307 // any error messages it has received. It might even abort compilation if
1308 // it has received a fatal error. In this case we rely on all other threads
1309 // being torn down automatically with the main thread.
1310 // Since the main thread will often be busy doing codegen work, error
1311 // reporting will be somewhat delayed, since the message queue can only be
1312 // checked in between two work packages.
1313 //
1314 // Work Processing Infrastructure
1315 // ==============================
1316 // The work processing infrastructure knows three major actors:
1317 //
1318 // - the coordinator thread,
1319 // - the main thread, and
1320 // - LLVM worker threads
1321 //
1322 // The coordinator thread is running a message loop. It instructs the main
1323 // thread about what work to do when, and it will spawn off LLVM worker
1324 // threads as open LLVM WorkItems become available.
1325 //
1326 // The job of the main thread is to codegen CGUs into LLVM work packages
1327 // (since the main thread is the only thread that can do this). The main
1328 // thread will block until it receives a message from the coordinator, upon
1329 // which it will codegen one CGU, send it to the coordinator and block
1330 // again. This way the coordinator can control what the main thread is
1331 // doing.
1332 //
1333 // The coordinator keeps a queue of LLVM WorkItems, and when a `Token` is
1334 // available, it will spawn off a new LLVM worker thread and let it process
1335 // a WorkItem. When a LLVM worker thread is done with its WorkItem,
1336 // it will just shut down, which also frees all resources associated with
1337 // the given LLVM module, and sends a message to the coordinator that the
1338 // WorkItem has been completed.
1339 //
1340 // Work Scheduling
1341 // ===============
1342 // The scheduler's goal is to minimize the time it takes to complete all
1343 // work there is, however, we also want to keep memory consumption low
1344 // if possible. These two goals are at odds with each other: If memory
1345 // consumption were not an issue, we could just let the main thread produce
1346 // LLVM WorkItems at full speed, assuring maximal utilization of
1347 // Tokens/LLVM worker threads. However, since codegen is usually faster
1348 // than LLVM processing, the queue of LLVM WorkItems would fill up and each
1349 // WorkItem potentially holds on to a substantial amount of memory.
1350 //
1351 // So the actual goal is to always produce just enough LLVM WorkItems as
1352 // not to starve our LLVM worker threads. That means, once we have enough
1353 // WorkItems in our queue, we can block the main thread, so it does not
1354 // produce more until we need them.
1355 //
1356 // Doing LLVM Work on the Main Thread
1357 // ----------------------------------
1358 // Since the main thread owns the compiler process's implicit `Token`, it is
1359 // wasteful to keep it blocked without doing any work. Therefore, what we do
1360 // in this case is: We spawn off an additional LLVM worker thread that helps
1361 // reduce the queue. The work it is doing corresponds to the implicit
1362 // `Token`. The coordinator will mark the main thread as being busy with
1363 // LLVM work. (The actual work happens on another OS thread but we just care
1364 // about `Tokens`, not actual threads).
1365 //
1366 // When any LLVM worker thread finishes while the main thread is marked as
1367 // "busy with LLVM work", we can do a little switcheroo: We give the Token
1368 // of the just finished thread to the LLVM worker thread that is working on
1369 // behalf of the main thread's implicit Token, thus freeing up the main
1370 // thread again. The coordinator can then again decide what the main thread
1371 // should do. This allows the coordinator to make decisions at more points
1372 // in time.
1373 //
1374 // Striking a Balance between Throughput and Memory Consumption
1375 // ------------------------------------------------------------
1376 // Since our two goals, (1) use as many Tokens as possible and (2) keep
1377 // memory consumption as low as possible, are in conflict with each other,
1378 // we have to find a trade off between them. Right now, the goal is to keep
1379 // all workers busy, which means that no worker should find the queue empty
1380 // when it is ready to start.
1381 // How do we do achieve this? Good question :) We actually never know how
1382 // many `Tokens` are potentially available so it's hard to say how much to
1383 // fill up the queue before switching the main thread to LLVM work. Also we
1384 // currently don't have a means to estimate how long a running LLVM worker
1385 // will still be busy with it's current WorkItem. However, we know the
1386 // maximal count of available Tokens that makes sense (=the number of CPU
1387 // cores), so we can take a conservative guess. The heuristic we use here
1388 // is implemented in the `queue_full_enough()` function.
1389 //
1390 // Some Background on Jobservers
1391 // -----------------------------
1392 // It's worth also touching on the management of parallelism here. We don't
1393 // want to just spawn a thread per work item because while that's optimal
1394 // parallelism it may overload a system with too many threads or violate our
1395 // configuration for the maximum amount of cpu to use for this process. To
1396 // manage this we use the `jobserver` crate.
1397 //
1398 // Job servers are an artifact of GNU make and are used to manage
1399 // parallelism between processes. A jobserver is a glorified IPC semaphore
1400 // basically. Whenever we want to run some work we acquire the semaphore,
1401 // and whenever we're done with that work we release the semaphore. In this
1402 // manner we can ensure that the maximum number of parallel workers is
1403 // capped at any one point in time.
1404 //
1405 // LTO and the coordinator thread
1406 // ------------------------------
1407 //
1408 // The final job the coordinator thread is responsible for is managing LTO
1409 // and how that works. When LTO is requested what we'll do is collect all
1410 // optimized LLVM modules into a local vector on the coordinator. Once all
1411 // modules have been codegened and optimized we hand this to the `lto`
1412 // module for further optimization. The `lto` module will return back a list
1413 // of more modules to work on, which the coordinator will continue to spawn
1414 // work for.
1415 //
1416 // Each LLVM module is automatically sent back to the coordinator for LTO if
1417 // necessary. There's already optimizations in place to avoid sending work
1418 // back to the coordinator if LTO isn't requested.
1419let f = move || {
1420let _profiler = if cgcx.time_trace { B::thread_profiler() } else { Box::new(()) };
14211422// This is where we collect codegen units that have gone all the way
1423 // through codegen and LLVM.
1424let mut compiled_modules = ::alloc::vec::Vec::new()vec![];
1425let mut needs_fat_lto = Vec::new();
1426let mut needs_thin_lto = Vec::new();
1427let mut lto_import_only_modules = Vec::new();
14281429/// Possible state transitions:
1430 /// - Ongoing -> Completed
1431 /// - Ongoing -> Aborted
1432 /// - Completed -> Aborted
1433#[derive(#[automatically_derived]
impl ::core::fmt::Debug for CodegenState {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
CodegenState::Ongoing => "Ongoing",
CodegenState::Completed => "Completed",
CodegenState::Aborted => "Aborted",
})
}
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for CodegenState {
#[inline]
fn eq(&self, other: &CodegenState) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq)]
1434enum CodegenState {
1435 Ongoing,
1436 Completed,
1437 Aborted,
1438 }
1439use CodegenState::*;
1440let mut codegen_state = Ongoing;
14411442// This is the queue of LLVM work items that still need processing.
1443let mut work_items = Vec::<(WorkItem<B>, u64)>::new();
14441445// This are the Jobserver Tokens we currently hold. Does not include
1446 // the implicit Token the compiler process owns no matter what.
1447let mut tokens = Vec::new();
14481449let mut main_thread_state = MainThreadState::Idle;
14501451// How many LLVM worker threads are running while holding a Token. This
1452 // *excludes* any that the main thread is lending a Token to.
1453let mut running_with_own_token = 0;
14541455// How many LLVM worker threads are running in total. This *includes*
1456 // any that the main thread is lending a Token to.
1457let running_with_any_token = |main_thread_state, running_with_own_token| {
1458running_with_own_token1459 + if main_thread_state == MainThreadState::Lending { 1 } else { 0 }
1460 };
14611462let mut llvm_start_time: Option<VerboseTimingGuard<'_>> = None;
14631464if let Some(allocator_module) = &mut allocator_module {
1465 B::optimize(&cgcx, &prof, &shared_emitter, allocator_module, &allocator_config);
1466 }
14671468// Run the message loop while there's still anything that needs message
1469 // processing. Note that as soon as codegen is aborted we simply want to
1470 // wait for all existing work to finish, so many of the conditions here
1471 // only apply if codegen hasn't been aborted as they represent pending
1472 // work to be done.
1473loop {
1474// While there are still CGUs to be codegened, the coordinator has
1475 // to decide how to utilize the compiler processes implicit Token:
1476 // For codegenning more CGU or for running them through LLVM.
1477if codegen_state == Ongoing {
1478if main_thread_state == MainThreadState::Idle {
1479// Compute the number of workers that will be running once we've taken as many
1480 // items from the work queue as we can, plus one for the main thread. It's not
1481 // critically important that we use this instead of just
1482 // `running_with_own_token`, but it prevents the `queue_full_enough` heuristic
1483 // from fluctuating just because a worker finished up and we decreased the
1484 // `running_with_own_token` count, even though we're just going to increase it
1485 // right after this when we put a new worker to work.
1486let extra_tokens = tokens.len().checked_sub(running_with_own_token).unwrap();
1487let additional_running = std::cmp::min(extra_tokens, work_items.len());
1488let anticipated_running = running_with_own_token + additional_running + 1;
14891490if !queue_full_enough(work_items.len(), anticipated_running) {
1491// The queue is not full enough, process more codegen units:
1492if codegen_worker_send.send(CguMessage).is_err() {
1493{
::core::panicking::panic_fmt(format_args!("Could not send CguMessage to main thread"));
}panic!("Could not send CguMessage to main thread")1494 }
1495main_thread_state = MainThreadState::Codegenning;
1496 } else {
1497// The queue is full enough to not let the worker
1498 // threads starve. Use the implicit Token to do some
1499 // LLVM work too.
1500let (item, _) =
1501work_items.pop().expect("queue empty - queue_full_enough() broken?");
1502main_thread_state = MainThreadState::Lending;
1503spawn_work(
1504&cgcx,
1505&prof,
1506shared_emitter.clone(),
1507coordinator_send.clone(),
1508&mut llvm_start_time,
1509item,
1510 );
1511 }
1512 }
1513 } else if codegen_state == Completed {
1514if running_with_any_token(main_thread_state, running_with_own_token) == 0
1515&& work_items.is_empty()
1516 {
1517// All codegen work is done.
1518break;
1519 }
15201521// In this branch, we know that everything has been codegened,
1522 // so it's just a matter of determining whether the implicit
1523 // Token is free to use for LLVM work.
1524match main_thread_state {
1525 MainThreadState::Idle => {
1526if let Some((item, _)) = work_items.pop() {
1527main_thread_state = MainThreadState::Lending;
1528spawn_work(
1529&cgcx,
1530&prof,
1531shared_emitter.clone(),
1532coordinator_send.clone(),
1533&mut llvm_start_time,
1534item,
1535 );
1536 } else {
1537// There is no unstarted work, so let the main thread
1538 // take over for a running worker. Otherwise the
1539 // implicit token would just go to waste.
1540 // We reduce the `running` counter by one. The
1541 // `tokens.truncate()` below will take care of
1542 // giving the Token back.
1543if !(running_with_own_token > 0) {
::core::panicking::panic("assertion failed: running_with_own_token > 0")
};assert!(running_with_own_token > 0);
1544running_with_own_token -= 1;
1545main_thread_state = MainThreadState::Lending;
1546 }
1547 }
1548 MainThreadState::Codegenning => ::rustc_middle::util::bug::bug_fmt(format_args!("codegen worker should not be codegenning after codegen was already completed"))bug!(
1549"codegen worker should not be codegenning after \
1550 codegen was already completed"
1551),
1552 MainThreadState::Lending => {
1553// Already making good use of that token
1554}
1555 }
1556 } else {
1557// Don't queue up any more work if codegen was aborted, we're
1558 // just waiting for our existing children to finish.
1559if !(codegen_state == Aborted) {
::core::panicking::panic("assertion failed: codegen_state == Aborted")
};assert!(codegen_state == Aborted);
1560if running_with_any_token(main_thread_state, running_with_own_token) == 0 {
1561break;
1562 }
1563 }
15641565// Spin up what work we can, only doing this while we've got available
1566 // parallelism slots and work left to spawn.
1567if codegen_state != Aborted {
1568while running_with_own_token < tokens.len()
1569 && let Some((item, _)) = work_items.pop()
1570 {
1571 spawn_work(
1572&cgcx,
1573&prof,
1574 shared_emitter.clone(),
1575 coordinator_send.clone(),
1576&mut llvm_start_time,
1577 item,
1578 );
1579 running_with_own_token += 1;
1580 }
1581 }
15821583// Relinquish accidentally acquired extra tokens.
1584tokens.truncate(running_with_own_token);
15851586match coordinator_receive.recv().unwrap() {
1587// Save the token locally and the next turn of the loop will use
1588 // this to spawn a new unit of work, or it may get dropped
1589 // immediately if we have no more work to spawn.
1590Message::Token(token) => {
1591match token {
1592Ok(token) => {
1593tokens.push(token);
15941595if main_thread_state == MainThreadState::Lending {
1596// If the main thread token is used for LLVM work
1597 // at the moment, we turn that thread into a regular
1598 // LLVM worker thread, so the main thread is free
1599 // to react to codegen demand.
1600main_thread_state = MainThreadState::Idle;
1601running_with_own_token += 1;
1602 }
1603 }
1604Err(e) => {
1605let msg = &::alloc::__export::must_use({
::alloc::fmt::format(format_args!("failed to acquire jobserver token: {0}",
e))
})format!("failed to acquire jobserver token: {e}");
1606shared_emitter.fatal(msg);
1607codegen_state = Aborted;
1608 }
1609 }
1610 }
16111612 Message::CodegenDone { llvm_work_item, cost } => {
1613// We keep the queue sorted by estimated processing cost,
1614 // so that more expensive items are processed earlier. This
1615 // is good for throughput as it gives the main thread more
1616 // time to fill up the queue and it avoids scheduling
1617 // expensive items to the end.
1618 // Note, however, that this is not ideal for memory
1619 // consumption, as LLVM module sizes are not evenly
1620 // distributed.
1621let insertion_index = work_items.binary_search_by_key(&cost, |&(_, cost)| cost);
1622let insertion_index = match insertion_index {
1623Ok(idx) | Err(idx) => idx,
1624 };
1625work_items.insert(insertion_index, (llvm_work_item, cost));
16261627if cgcx.parallel {
1628helper.request_token();
1629 }
1630match (&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);
1631main_thread_state = MainThreadState::Idle;
1632 }
16331634 Message::CodegenComplete => {
1635if codegen_state != Aborted {
1636codegen_state = Completed;
1637 }
1638match (&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);
1639main_thread_state = MainThreadState::Idle;
1640 }
16411642// If codegen is aborted that means translation was aborted due
1643 // to some normal-ish compiler error. In this situation we want
1644 // to exit as soon as possible, but we want to make sure all
1645 // existing work has finished. Flag codegen as being done, and
1646 // then conditions above will ensure no more work is spawned but
1647 // we'll keep executing this loop until `running_with_own_token`
1648 // hits 0.
1649Message::CodegenAborted => {
1650codegen_state = Aborted;
1651 }
16521653 Message::WorkItem { result } => {
1654// If a thread exits successfully then we drop a token associated
1655 // with that worker and update our `running_with_own_token` count.
1656 // We may later re-acquire a token to continue running more work.
1657 // We may also not actually drop a token here if the worker was
1658 // running with an "ephemeral token".
1659if main_thread_state == MainThreadState::Lending {
1660main_thread_state = MainThreadState::Idle;
1661 } else {
1662running_with_own_token -= 1;
1663 }
16641665match result {
1666Ok(WorkItemResult::Finished(compiled_module)) => {
1667compiled_modules.push(compiled_module);
1668 }
1669Ok(WorkItemResult::NeedsFatLto(fat_lto_input)) => {
1670if !needs_thin_lto.is_empty() {
::core::panicking::panic("assertion failed: needs_thin_lto.is_empty()")
};assert!(needs_thin_lto.is_empty());
1671needs_fat_lto.push(fat_lto_input);
1672 }
1673Ok(WorkItemResult::NeedsThinLto(name, thin_buffer)) => {
1674if !needs_fat_lto.is_empty() {
::core::panicking::panic("assertion failed: needs_fat_lto.is_empty()")
};assert!(needs_fat_lto.is_empty());
1675needs_thin_lto.push(ThinLtoInput::Red {
1676name,
1677 buffer: SerializedModule::Local(thin_buffer),
1678 });
1679 }
1680Err(Some(WorkerFatalError)) => {
1681// Like `CodegenAborted`, wait for remaining work to finish.
1682codegen_state = Aborted;
1683 }
1684Err(None) => {
1685// If the thread failed that means it panicked, so
1686 // we abort immediately.
1687::rustc_middle::util::bug::bug_fmt(format_args!("worker thread panicked"));bug!("worker thread panicked");
1688 }
1689 }
1690 }
16911692 Message::AddImportOnlyModule { bitcode_path, work_product } => {
1693match (&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);
1694match (&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);
1695lto_import_only_modules.push((bitcode_path, work_product));
1696main_thread_state = MainThreadState::Idle;
1697 }
1698 }
1699 }
17001701// Drop to print timings
1702drop(llvm_start_time);
17031704if codegen_state == Aborted {
1705return Err(());
1706 }
17071708drop(codegen_state);
1709drop(tokens);
1710drop(helper);
1711if !work_items.is_empty() {
::core::panicking::panic("assertion failed: work_items.is_empty()")
};assert!(work_items.is_empty());
17121713if !needs_fat_lto.is_empty() {
1714if !compiled_modules.is_empty() {
::core::panicking::panic("assertion failed: compiled_modules.is_empty()")
};assert!(compiled_modules.is_empty());
1715if !needs_thin_lto.is_empty() {
::core::panicking::panic("assertion failed: needs_thin_lto.is_empty()")
};assert!(needs_thin_lto.is_empty());
17161717if let Some(allocator_module) = allocator_module.take() {
1718needs_fat_lto.push(FatLtoInput::InMemory(allocator_module));
1719 }
17201721for (bitcode_path, wp) in lto_import_only_modules {
1722 needs_fat_lto.push(FatLtoInput::Serialized { name: wp.cgu_name, bitcode_path })
1723 }
17241725return Ok(MaybeLtoModules::FatLto { cgcx, needs_fat_lto });
1726 } else if !needs_thin_lto.is_empty() || !lto_import_only_modules.is_empty() {
1727if !compiled_modules.is_empty() {
::core::panicking::panic("assertion failed: compiled_modules.is_empty()")
};assert!(compiled_modules.is_empty());
1728if !needs_fat_lto.is_empty() {
::core::panicking::panic("assertion failed: needs_fat_lto.is_empty()")
};assert!(needs_fat_lto.is_empty());
17291730for (bitcode_path, wp) in lto_import_only_modules {
1731 needs_thin_lto.push(ThinLtoInput::Green { wp, bitcode_path })
1732 }
17331734if cgcx.lto == Lto::ThinLocal {
1735compiled_modules.extend(do_thin_lto::<B>(
1736&cgcx,
1737&prof,
1738shared_emitter.clone(),
1739tm_factory,
1740&exported_symbols_for_lto,
1741&[],
1742needs_thin_lto,
1743 ));
1744 } else {
1745if let Some(allocator_module) = allocator_module.take() {
1746let thin_buffer = B::serialize_module(allocator_module.module_llvm, true);
1747needs_thin_lto.push(ThinLtoInput::Red {
1748 name: allocator_module.name,
1749 buffer: SerializedModule::Local(thin_buffer),
1750 });
1751 }
17521753return Ok(MaybeLtoModules::ThinLto { cgcx, needs_thin_lto });
1754 }
1755 }
17561757Ok(MaybeLtoModules::NoLto(CompiledModules {
1758 modules: compiled_modules,
1759 allocator_module: allocator_module.map(|allocator_module| {
1760 B::codegen(&cgcx, &prof, &shared_emitter, allocator_module, &allocator_config)
1761 }),
1762 }))
1763 };
1764return std::thread::Builder::new()
1765 .name("coordinator".to_owned())
1766 .spawn(f)
1767 .expect("failed to spawn coordinator thread");
17681769// A heuristic that determines if we have enough LLVM WorkItems in the
1770 // queue so that the main thread can do LLVM work instead of codegen
1771fn queue_full_enough(items_in_queue: usize, workers_running: usize) -> bool {
1772// This heuristic scales ahead-of-time codegen according to available
1773 // concurrency, as measured by `workers_running`. The idea is that the
1774 // more concurrency we have available, the more demand there will be for
1775 // work items, and the fuller the queue should be kept to meet demand.
1776 // An important property of this approach is that we codegen ahead of
1777 // time only as much as necessary, so as to keep fewer LLVM modules in
1778 // memory at once, thereby reducing memory consumption.
1779 //
1780 // When the number of workers running is less than the max concurrency
1781 // available to us, this heuristic can cause us to instruct the main
1782 // thread to work on an LLVM item (that is, tell it to "LLVM") instead
1783 // of codegen, even though it seems like it *should* be codegenning so
1784 // that we can create more work items and spawn more LLVM workers.
1785 //
1786 // But this is not a problem. When the main thread is told to LLVM,
1787 // according to this heuristic and how work is scheduled, there is
1788 // always at least one item in the queue, and therefore at least one
1789 // pending jobserver token request. If there *is* more concurrency
1790 // available, we will immediately receive a token, which will upgrade
1791 // the main thread's LLVM worker to a real one (conceptually), and free
1792 // up the main thread to codegen if necessary. On the other hand, if
1793 // there isn't more concurrency, then the main thread working on an LLVM
1794 // item is appropriate, as long as the queue is full enough for demand.
1795 //
1796 // Speaking of which, how full should we keep the queue? Probably less
1797 // full than you'd think. A lot has to go wrong for the queue not to be
1798 // full enough and for that to have a negative effect on compile times.
1799 //
1800 // Workers are unlikely to finish at exactly the same time, so when one
1801 // finishes and takes another work item off the queue, we often have
1802 // ample time to codegen at that point before the next worker finishes.
1803 // But suppose that codegen takes so long that the workers exhaust the
1804 // queue, and we have one or more workers that have nothing to work on.
1805 // Well, it might not be so bad. Of all the LLVM modules we create and
1806 // optimize, one has to finish last. It's not necessarily the case that
1807 // by losing some concurrency for a moment, we delay the point at which
1808 // that last LLVM module is finished and the rest of compilation can
1809 // proceed. Also, when we can't take advantage of some concurrency, we
1810 // give tokens back to the job server. That enables some other rustc to
1811 // potentially make use of the available concurrency. That could even
1812 // *decrease* overall compile time if we're lucky. But yes, if no other
1813 // rustc can make use of the concurrency, then we've squandered it.
1814 //
1815 // However, keeping the queue full is also beneficial when we have a
1816 // surge in available concurrency. Then items can be taken from the
1817 // queue immediately, without having to wait for codegen.
1818 //
1819 // So, the heuristic below tries to keep one item in the queue for every
1820 // four running workers. Based on limited benchmarking, this appears to
1821 // be more than sufficient to avoid increasing compilation times.
1822let quarter_of_workers = workers_running - 3 * workers_running / 4;
1823items_in_queue > 0 && items_in_queue >= quarter_of_workers1824 }
1825}
18261827/// `FatalError` is explicitly not `Send`.
1828#[must_use]
1829pub(crate) struct WorkerFatalError;
18301831fn spawn_work<'a, B: WriteBackendMethods>(
1832 cgcx: &CodegenContext,
1833 prof: &'a SelfProfilerRef,
1834 shared_emitter: SharedEmitter,
1835 coordinator_send: Sender<Message<B>>,
1836 llvm_start_time: &mut Option<VerboseTimingGuard<'a>>,
1837 work: WorkItem<B>,
1838) {
1839if llvm_start_time.is_none() {
1840*llvm_start_time = Some(prof.verbose_generic_activity("LLVM_passes"));
1841 }
18421843let cgcx = cgcx.clone();
1844let prof = prof.clone();
18451846let name = work.short_description();
1847let f = move || {
1848let _profiler = if cgcx.time_trace { B::thread_profiler() } else { Box::new(()) };
18491850let result = std::panic::catch_unwind(AssertUnwindSafe(|| match work {
1851 WorkItem::Optimize(m) => execute_optimize_work_item(&cgcx, &prof, shared_emitter, m),
1852 WorkItem::CopyPostLtoArtifacts(m) => WorkItemResult::Finished(
1853execute_copy_from_cache_work_item(&cgcx, &prof, shared_emitter, m),
1854 ),
1855 }));
18561857let msg = match result {
1858Ok(result) => Message::WorkItem::<B> { result: Ok(result) },
18591860// We ignore any `FatalError` coming out of `execute_work_item`, as a
1861 // diagnostic was already sent off to the main thread - just surface
1862 // that there was an error in this worker.
1863Err(err) if err.is::<FatalErrorMarker>() => {
1864 Message::WorkItem::<B> { result: Err(Some(WorkerFatalError)) }
1865 }
18661867Err(_) => Message::WorkItem::<B> { result: Err(None) },
1868 };
1869drop(coordinator_send.send(msg));
1870 };
1871 std::thread::Builder::new().name(name).spawn(f).expect("failed to spawn work thread");
1872}
18731874fn spawn_thin_lto_work<B: WriteBackendMethods>(
1875 cgcx: &CodegenContext,
1876 prof: &SelfProfilerRef,
1877 shared_emitter: SharedEmitter,
1878 tm_factory: TargetMachineFactoryFn<B>,
1879 coordinator_send: Sender<ThinLtoMessage>,
1880 work: ThinLtoWorkItem<B>,
1881) {
1882let cgcx = cgcx.clone();
1883let prof = prof.clone();
18841885let name = work.short_description();
1886let f = move || {
1887let _profiler = if cgcx.time_trace { B::thread_profiler() } else { Box::new(()) };
18881889let result = std::panic::catch_unwind(AssertUnwindSafe(|| match work {
1890 ThinLtoWorkItem::CopyPostLtoArtifacts(m) => {
1891execute_copy_from_cache_work_item(&cgcx, &prof, shared_emitter, m)
1892 }
1893 ThinLtoWorkItem::ThinLto(m) => {
1894execute_thin_lto_work_item(&cgcx, &prof, shared_emitter, tm_factory, m)
1895 }
1896 }));
18971898let msg = match result {
1899Ok(result) => ThinLtoMessage::WorkItem { result: Ok(result) },
19001901// We ignore any `FatalError` coming out of `execute_work_item`, as a
1902 // diagnostic was already sent off to the main thread - just surface
1903 // that there was an error in this worker.
1904Err(err) if err.is::<FatalErrorMarker>() => {
1905 ThinLtoMessage::WorkItem { result: Err(Some(WorkerFatalError)) }
1906 }
19071908Err(_) => ThinLtoMessage::WorkItem { result: Err(None) },
1909 };
1910drop(coordinator_send.send(msg));
1911 };
1912 std::thread::Builder::new().name(name).spawn(f).expect("failed to spawn work thread");
1913}
19141915enum SharedEmitterMessage {
1916 Diagnostic(Diagnostic),
1917 InlineAsmError(InlineAsmError),
1918 Fatal(String),
1919}
19201921pub struct InlineAsmError {
1922pub span: SpanData,
1923pub msg: String,
1924pub level: Level,
1925pub source: Option<(String, Vec<InnerSpan>)>,
1926}
19271928#[derive(#[automatically_derived]
impl ::core::clone::Clone for SharedEmitter {
#[inline]
fn clone(&self) -> SharedEmitter {
SharedEmitter { sender: ::core::clone::Clone::clone(&self.sender) }
}
}Clone)]
1929pub struct SharedEmitter {
1930 sender: Sender<SharedEmitterMessage>,
1931}
19321933pub struct SharedEmitterMain {
1934 receiver: Receiver<SharedEmitterMessage>,
1935}
19361937impl SharedEmitter {
1938fn new() -> (SharedEmitter, SharedEmitterMain) {
1939let (sender, receiver) = channel();
19401941 (SharedEmitter { sender }, SharedEmitterMain { receiver })
1942 }
19431944pub fn inline_asm_error(&self, err: InlineAsmError) {
1945drop(self.sender.send(SharedEmitterMessage::InlineAsmError(err)));
1946 }
19471948fn fatal(&self, msg: &str) {
1949drop(self.sender.send(SharedEmitterMessage::Fatal(msg.to_string())));
1950 }
1951}
19521953impl Emitterfor SharedEmitter {
1954fn emit_diagnostic(&mut self, mut diag: rustc_errors::DiagInner) {
1955// Check that we aren't missing anything interesting when converting to
1956 // the cut-down local `DiagInner`.
1957if !!diag.span.has_span_labels() {
::core::panicking::panic("assertion failed: !diag.span.has_span_labels()")
};assert!(!diag.span.has_span_labels());
1958match (&diag.suggestions, &Suggestions::Enabled(::alloc::vec::Vec::new())) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val, &*right_val,
::core::option::Option::None);
}
}
};assert_eq!(diag.suggestions, Suggestions::Enabled(vec![]));
1959match (&diag.sort_span, &rustc_span::DUMMY_SP) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val, &*right_val,
::core::option::Option::None);
}
}
};assert_eq!(diag.sort_span, rustc_span::DUMMY_SP);
1960match (&diag.is_lint, &None) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val, &*right_val,
::core::option::Option::None);
}
}
};assert_eq!(diag.is_lint, None);
1961// No sensible check for `diag.emitted_at`.
19621963let args = mem::replace(&mut diag.args, DiagArgMap::default());
1964drop(
1965self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
1966 span: diag.span.primary_spans().iter().map(|span| span.data()).collect::<Vec<_>>(),
1967 level: diag.level(),
1968 messages: diag.messages,
1969 code: diag.code,
1970 children: diag1971 .children
1972 .into_iter()
1973 .map(|child| Subdiagnostic { level: child.level, messages: child.messages })
1974 .collect(),
1975args,
1976 })),
1977 );
1978 }
19791980fn source_map(&self) -> Option<&SourceMap> {
1981None1982 }
1983}
19841985impl SharedEmitterMain {
1986fn check(&self, sess: &Session, blocking: bool) {
1987loop {
1988let message = if blocking {
1989match self.receiver.recv() {
1990Ok(message) => Ok(message),
1991Err(_) => Err(()),
1992 }
1993 } else {
1994match self.receiver.try_recv() {
1995Ok(message) => Ok(message),
1996Err(_) => Err(()),
1997 }
1998 };
19992000match message {
2001Ok(SharedEmitterMessage::Diagnostic(diag)) => {
2002// The diagnostic has been received on the main thread.
2003 // Convert it back to a full `Diagnostic` and emit.
2004let dcx = sess.dcx();
2005let mut d =
2006 rustc_errors::DiagInner::new_with_messages(diag.level, diag.messages);
2007d.span = MultiSpan::from_spans(
2008diag.span.into_iter().map(|span| span.span()).collect(),
2009 );
2010d.code = diag.code; // may be `None`, that's ok
2011d.children = diag2012 .children
2013 .into_iter()
2014 .map(|sub| rustc_errors::Subdiag {
2015 level: sub.level,
2016 messages: sub.messages,
2017 span: MultiSpan::new(),
2018 })
2019 .collect();
2020d.args = diag.args;
2021dcx.emit_diagnostic(d);
2022sess.dcx().abort_if_errors();
2023 }
2024Ok(SharedEmitterMessage::InlineAsmError(inner)) => {
2025{
match inner.level {
Level::Error | Level::Warning | Level::Note => {}
ref left_val => {
::core::panicking::assert_matches_failed(left_val,
"Level::Error | Level::Warning | Level::Note",
::core::option::Option::None);
}
}
};assert_matches!(inner.level, Level::Error | Level::Warning | Level::Note);
2026let mut err = Diag::<()>::new(sess.dcx(), inner.level, inner.msg);
2027if !inner.span.is_dummy() {
2028err.span(inner.span.span());
2029 }
20302031// Point to the generated assembly if it is available.
2032if let Some((buffer, spans)) = inner.source {
2033let source = sess2034 .source_map()
2035 .new_source_file(FileName::inline_asm_source_code(&buffer), buffer);
2036let spans: Vec<_> = spans2037 .iter()
2038 .map(|sp| {
2039Span::with_root_ctxt(
2040source.normalized_byte_pos(sp.start as u32),
2041source.normalized_byte_pos(sp.end as u32),
2042 )
2043 })
2044 .collect();
2045err.span_note(spans, "instantiated into assembly here");
2046 }
20472048err.emit();
2049 }
2050Ok(SharedEmitterMessage::Fatal(msg)) => {
2051sess.dcx().fatal(msg);
2052 }
2053Err(_) => {
2054break;
2055 }
2056 }
2057 }
2058 }
2059}
20602061pub struct Coordinator<B: WriteBackendMethods> {
2062 sender: Sender<Message<B>>,
2063 future: Option<thread::JoinHandle<Result<MaybeLtoModules<B>, ()>>>,
2064// Only used for the Message type.
2065phantom: PhantomData<B>,
2066}
20672068impl<B: WriteBackendMethods> Coordinator<B> {
2069fn join(mut self) -> std::thread::Result<Result<MaybeLtoModules<B>, ()>> {
2070self.future.take().unwrap().join()
2071 }
2072}
20732074impl<B: WriteBackendMethods> Dropfor Coordinator<B> {
2075fn drop(&mut self) {
2076if let Some(future) = self.future.take() {
2077// If we haven't joined yet, signal to the coordinator that it should spawn no more
2078 // work, and wait for worker threads to finish.
2079drop(self.sender.send(Message::CodegenAborted::<B>));
2080drop(future.join());
2081 }
2082 }
2083}
20842085pub struct OngoingCodegen<B: WriteBackendMethods> {
2086 backend: B,
2087 output_filenames: Arc<OutputFilenames>,
2088// Field order below is intended to terminate the coordinator thread before two fields below
2089 // drop and prematurely close channels used by coordinator thread. See `Coordinator`'s
2090 // `Drop` implementation for more info.
2091pub(crate) coordinator: Coordinator<B>,
2092 codegen_worker_receive: Receiver<CguMessage>,
2093 shared_emitter_main: SharedEmitterMain,
2094}
20952096impl<B: WriteBackendMethods> OngoingCodegen<B> {
2097pub fn join(
2098self,
2099 sess: &Session,
2100 crate_info: &CrateInfo,
2101 ) -> (CompiledModules, FxIndexMap<WorkProductId, WorkProduct>) {
2102self.shared_emitter_main.check(sess, true);
21032104let maybe_lto_modules = sess.time("join_worker_thread", || match self.coordinator.join() {
2105Ok(Ok(maybe_lto_modules)) => maybe_lto_modules,
2106Ok(Err(())) => {
2107sess.dcx().abort_if_errors();
2108{
::core::panicking::panic_fmt(format_args!("expected abort due to worker thread errors"));
}panic!("expected abort due to worker thread errors")2109 }
2110Err(_) => {
2111::rustc_middle::util::bug::bug_fmt(format_args!("panic during codegen/LLVM phase"));bug!("panic during codegen/LLVM phase");
2112 }
2113 });
21142115sess.dcx().abort_if_errors();
21162117let (shared_emitter, shared_emitter_main) = SharedEmitter::new();
21182119// Catch fatal errors to ensure shared_emitter_main.check() can emit the actual diagnostics
2120let compiled_modules = catch_fatal_errors(|| match maybe_lto_modules {
2121 MaybeLtoModules::NoLto(compiled_modules) => {
2122drop(shared_emitter);
2123compiled_modules2124 }
2125 MaybeLtoModules::FatLto { cgcx, needs_fat_lto } => {
2126let tm_factory = self.backend.target_machine_factory(
2127sess,
2128cgcx.opt_level,
2129&cgcx.backend_features,
2130 );
21312132CompiledModules {
2133 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(
2134 sess,
2135&cgcx,
2136 shared_emitter,
2137 tm_factory,
2138&crate_info.exported_symbols_for_lto,
2139&crate_info.each_linked_rlib_file_for_lto,
2140 needs_fat_lto,
2141 )],
2142 allocator_module: None,
2143 }
2144 }
2145 MaybeLtoModules::ThinLto { cgcx, needs_thin_lto } => {
2146let tm_factory = self.backend.target_machine_factory(
2147sess,
2148cgcx.opt_level,
2149&cgcx.backend_features,
2150 );
21512152CompiledModules {
2153 modules: do_thin_lto::<B>(
2154&cgcx,
2155&sess.prof,
2156shared_emitter,
2157tm_factory,
2158&crate_info.exported_symbols_for_lto,
2159&crate_info.each_linked_rlib_file_for_lto,
2160needs_thin_lto,
2161 ),
2162 allocator_module: None,
2163 }
2164 }
2165 });
21662167shared_emitter_main.check(sess, true);
21682169sess.dcx().abort_if_errors();
21702171let mut compiled_modules =
2172compiled_modules.expect("fatal error emitted but not sent to SharedEmitter");
21732174// Regardless of what order these modules completed in, report them to
2175 // the backend in the same order every time to ensure that we're handing
2176 // out deterministic results.
2177compiled_modules.modules.sort_by(|a, b| a.name.cmp(&b.name));
21782179let work_products =
2180copy_all_cgu_workproducts_to_incr_comp_cache_dir(sess, &compiled_modules);
2181produce_final_output_artifacts(sess, &compiled_modules, &self.output_filenames);
21822183 (compiled_modules, work_products)
2184 }
21852186pub(crate) fn codegen_finished(&self, tcx: TyCtxt<'_>) {
2187self.wait_for_signal_to_codegen_item();
2188self.check_for_errors(tcx.sess);
2189drop(self.coordinator.sender.send(Message::CodegenComplete::<B>));
2190 }
21912192pub(crate) fn check_for_errors(&self, sess: &Session) {
2193self.shared_emitter_main.check(sess, false);
2194 }
21952196pub(crate) fn wait_for_signal_to_codegen_item(&self) {
2197match self.codegen_worker_receive.recv() {
2198Ok(CguMessage) => {
2199// Ok to proceed.
2200}
2201Err(_) => {
2202// One of the LLVM threads must have panicked, fall through so
2203 // error handling can be reached.
2204}
2205 }
2206 }
2207}
22082209pub(crate) fn submit_codegened_module_to_llvm<B: WriteBackendMethods>(
2210 coordinator: &Coordinator<B>,
2211 module: ModuleCodegen<B::Module>,
2212 cost: u64,
2213) {
2214let llvm_work_item = WorkItem::Optimize(module);
2215drop(coordinator.sender.send(Message::CodegenDone::<B> { llvm_work_item, cost }));
2216}
22172218pub(crate) fn submit_post_lto_module_to_llvm<B: WriteBackendMethods>(
2219 coordinator: &Coordinator<B>,
2220 module: CachedModuleCodegen,
2221) {
2222let llvm_work_item = WorkItem::CopyPostLtoArtifacts(module);
2223drop(coordinator.sender.send(Message::CodegenDone::<B> { llvm_work_item, cost: 0 }));
2224}
22252226pub(crate) fn submit_pre_lto_module_to_llvm<B: WriteBackendMethods>(
2227 tcx: TyCtxt<'_>,
2228 coordinator: &Coordinator<B>,
2229 module: CachedModuleCodegen,
2230) {
2231let filename = pre_lto_bitcode_filename(&module.name);
2232let bitcode_path = in_incr_comp_dir_sess(tcx.sess, &filename);
2233// Schedule the module to be loaded
2234drop(
2235coordinator2236 .sender
2237 .send(Message::AddImportOnlyModule::<B> { bitcode_path, work_product: module.source }),
2238 );
2239}
22402241fn pre_lto_bitcode_filename(module_name: &str) -> String {
2242::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}.{1}", module_name,
PRE_LTO_BC_EXT))
})format!("{module_name}.{PRE_LTO_BC_EXT}")2243}
22442245fn msvc_imps_needed(tcx: TyCtxt<'_>) -> bool {
2246// This should never be true (because it's not supported). If it is true,
2247 // something is wrong with commandline arg validation.
2248if !!(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!(
2249 !(tcx.sess.opts.cg.linker_plugin_lto.enabled()
2250 && tcx.sess.target.is_like_windows
2251 && tcx.sess.opts.cg.prefer_dynamic)
2252 );
22532254// We need to generate _imp__ symbol if we are generating an rlib or we include one
2255 // indirectly from ThinLTO. In theory these are not needed as ThinLTO could resolve
2256 // these, but it currently does not do so.
2257let can_have_static_objects =
2258tcx.sess.lto() == Lto::Thin || tcx.crate_types().contains(&CrateType::Rlib);
22592260tcx.sess.target.is_like_windows &&
2261can_have_static_objects &&
2262// ThinLTO can't handle this workaround in all cases, so we don't
2263 // emit the `__imp_` symbols. Instead we make them unnecessary by disallowing
2264 // dynamic linking when linker plugin LTO is enabled.
2265!tcx.sess.opts.cg.linker_plugin_lto.enabled()
2266}