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