1use std::marker::PhantomData;
2use std::num::NonZero;
3use std::panic::AssertUnwindSafe;
4use std::path::{Path, PathBuf};
5use std::sync::Arc;
6use std::sync::mpsc::{Receiver, Sender, channel};
7use std::{assert_matches, fs, io, mem, str, thread};
89use rustc_abi::Size;
10use rustc_data_structures::jobserver::{self, Acquired};
11use rustc_data_structures::profiling::{SelfProfilerRef, VerboseTimingGuard};
12use rustc_errors::emitter::Emitter;
13use rustc_errors::{
14Diag, DiagArgMap, DiagCtxt, DiagCtxtHandle, DiagMessage, ErrCode, FatalError, FatalErrorMarker,
15Level, MultiSpan, Style, Sublevel, Suggestions, catch_fatal_errors,
16};
17use rustc_fs_util::link_or_copy;
18use rustc_incremental::{
19copy_cgu_workproduct_to_incr_comp_cache_dir, in_incr_comp_dir_sess, in_old_incr_comp_dir_sess,
20};
21use rustc_macros::{Decodable, Encodable};
22use rustc_metadata::fs::copy_to_stdout;
23use rustc_middle::dep_graph::{WorkProduct, WorkProductMap};
24use rustc_middle::ty::TyCtxt;
25use rustc_session::config::{
26self, Lto, OptLevel, OutFileName, OutputFilenames, OutputType, Passes, SwitchWithOptPath,
27};
28use rustc_session::{IncrCompSession, Session};
29use rustc_span::source_map::SourceMap;
30use rustc_span::{FileName, InnerSpan, Span, SpanData, bug};
31use rustc_structures::CrateType;
32use rustc_target::spec::{MergeFunctions, SanitizerSet};
33use tracing::debug;
3435use crate::back::link::ensure_removed;
36use crate::back::lto::{self, SerializedModule, check_lto_allowed};
37use crate::diagnostics::ErrorCreatingRemarkDir;
38use crate::traits::*;
39use crate::{
40CachedModuleCodegen, CompiledModule, CompiledModules, CrateInfo, ModuleCodegen, ModuleKind,
41diagnostics,
42};
4344const PRE_LTO_BC_EXT: &str = "pre-lto.bc";
4546/// What kind of object file to emit.
47#[derive(#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for EmitObj { }
#[automatically_derived]
impl ::core::clone::Clone for EmitObj {
#[inline]
fn clone(&self) -> Self {
let _: ::core::clone::AssertParamIsClone<BitcodeSection>;
*self
}
}Clone, #[automatically_derived]
impl ::core::marker::Copy for EmitObj { }Copy, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for EmitObj { }
#[automatically_derived]
impl ::core::cmp::PartialEq for EmitObj {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other) &&
match (self, other) {
(Self::ObjectCode(__self_0), Self::ObjectCode(__arg1_0)) =>
__self_0 == __arg1_0,
_ => true,
}
}
}PartialEq, const _: () =
{
impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
for EmitObj {
fn encode(&self, __encoder: &mut __E) {
let disc =
match *self {
EmitObj::None => { 0usize }
EmitObj::Bitcode => { 1usize }
EmitObj::ObjectCode(ref __binding_0) => { 2usize }
};
::rustc_serialize::Encoder::emit_u8(__encoder, disc as u8);
match *self {
EmitObj::None => {}
EmitObj::Bitcode => {}
EmitObj::ObjectCode(ref __binding_0) => {
::rustc_serialize::Encodable::<__E>::encode(__binding_0,
__encoder);
}
}
}
}
};Encodable, const _: () =
{
impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
for EmitObj {
fn decode(__decoder: &mut __D) -> Self {
match ::rustc_serialize::Decoder::read_u8(__decoder) as usize
{
0usize => { EmitObj::None }
1usize => { EmitObj::Bitcode }
2usize => {
EmitObj::ObjectCode(::rustc_serialize::Decodable::decode(__decoder))
}
n => {
::core::panicking::panic_fmt(format_args!("invalid enum variant tag while decoding `EmitObj`, expected 0..3, actual {0}",
n));
}
}
}
}
};Decodable)]
48pub enum EmitObj {
49// No object file.
50None,
5152// Just uncompressed llvm bitcode. Provides easy compatibility with
53 // emscripten's ecc compiler, when used as the linker.
54Bitcode,
5556// Object code, possibly augmented with a bitcode section.
57ObjectCode(BitcodeSection),
58}
5960/// What kind of llvm bitcode section to embed in an object file.
61#[derive(#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for BitcodeSection { }
#[automatically_derived]
impl ::core::clone::Clone for BitcodeSection {
#[inline]
fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for BitcodeSection { }Copy, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for BitcodeSection { }
#[automatically_derived]
impl ::core::cmp::PartialEq for BitcodeSection {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other)
}
}PartialEq, const _: () =
{
impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
for BitcodeSection {
fn encode(&self, __encoder: &mut __E) {
let disc =
match *self {
BitcodeSection::None => { 0usize }
BitcodeSection::Full => { 1usize }
};
::rustc_serialize::Encoder::emit_u8(__encoder, disc as u8);
}
}
};Encodable, const _: () =
{
impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
for BitcodeSection {
fn decode(__decoder: &mut __D) -> Self {
match ::rustc_serialize::Decoder::read_u8(__decoder) as usize
{
0usize => { BitcodeSection::None }
1usize => { BitcodeSection::Full }
n => {
::core::panicking::panic_fmt(format_args!("invalid enum variant tag while decoding `BitcodeSection`, expected 0..2, actual {0}",
n));
}
}
}
}
};Decodable)]
62pub enum BitcodeSection {
63// No bitcode section.
64None,
6566// A full, uncompressed bitcode section.
67Full,
68}
6970/// Module-specific configuration for `optimize_and_codegen`.
71#[derive(const _: () =
{
impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
for ModuleConfig {
fn encode(&self, __encoder: &mut __E) {
let ModuleConfig {
passes: ref __binding_0,
opt_level: ref __binding_1,
pgo_gen: ref __binding_2,
pgo_use: ref __binding_3,
pgo_sample_use: ref __binding_4,
debug_info_for_profiling: ref __binding_5,
instrument_coverage: ref __binding_6,
sanitizer: ref __binding_7,
sanitizer_cfi_diag: ref __binding_8,
sanitizer_cfi_recover: ref __binding_9,
sanitizer_recover: ref __binding_10,
sanitizer_dataflow_abilist: ref __binding_11,
sanitizer_memory_track_origins: ref __binding_12,
emit_pre_lto_bc: ref __binding_13,
emit_bc: ref __binding_14,
emit_ir: ref __binding_15,
emit_asm: ref __binding_16,
emit_obj: ref __binding_17,
emit_thin_lto_summary: ref __binding_18,
verify_llvm_ir: ref __binding_19,
lint_llvm_ir: ref __binding_20,
no_prepopulate_passes: ref __binding_21,
no_builtins: ref __binding_22,
vectorize_loop: ref __binding_23,
vectorize_slp: ref __binding_24,
merge_functions: ref __binding_25,
emit_lifetime_markers: ref __binding_26,
llvm_plugins: ref __binding_27,
autodiff: ref __binding_28,
autodiff_post_passes: ref __binding_29,
offload: ref __binding_30 } = *self;
::rustc_serialize::Encodable::<__E>::encode(__binding_0,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_1,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_2,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_3,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_4,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_5,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_6,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_7,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_8,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_9,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_10,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_11,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_12,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_13,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_14,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_15,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_16,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_17,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_18,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_19,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_20,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_21,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_22,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_23,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_24,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_25,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_26,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_27,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_28,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_29,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_30,
__encoder);
}
}
};Encodable, const _: () =
{
impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
for ModuleConfig {
fn decode(__decoder: &mut __D) -> Self {
ModuleConfig {
passes: ::rustc_serialize::Decodable::decode(__decoder),
opt_level: ::rustc_serialize::Decodable::decode(__decoder),
pgo_gen: ::rustc_serialize::Decodable::decode(__decoder),
pgo_use: ::rustc_serialize::Decodable::decode(__decoder),
pgo_sample_use: ::rustc_serialize::Decodable::decode(__decoder),
debug_info_for_profiling: ::rustc_serialize::Decodable::decode(__decoder),
instrument_coverage: ::rustc_serialize::Decodable::decode(__decoder),
sanitizer: ::rustc_serialize::Decodable::decode(__decoder),
sanitizer_cfi_diag: ::rustc_serialize::Decodable::decode(__decoder),
sanitizer_cfi_recover: ::rustc_serialize::Decodable::decode(__decoder),
sanitizer_recover: ::rustc_serialize::Decodable::decode(__decoder),
sanitizer_dataflow_abilist: ::rustc_serialize::Decodable::decode(__decoder),
sanitizer_memory_track_origins: ::rustc_serialize::Decodable::decode(__decoder),
emit_pre_lto_bc: ::rustc_serialize::Decodable::decode(__decoder),
emit_bc: ::rustc_serialize::Decodable::decode(__decoder),
emit_ir: ::rustc_serialize::Decodable::decode(__decoder),
emit_asm: ::rustc_serialize::Decodable::decode(__decoder),
emit_obj: ::rustc_serialize::Decodable::decode(__decoder),
emit_thin_lto_summary: ::rustc_serialize::Decodable::decode(__decoder),
verify_llvm_ir: ::rustc_serialize::Decodable::decode(__decoder),
lint_llvm_ir: ::rustc_serialize::Decodable::decode(__decoder),
no_prepopulate_passes: ::rustc_serialize::Decodable::decode(__decoder),
no_builtins: ::rustc_serialize::Decodable::decode(__decoder),
vectorize_loop: ::rustc_serialize::Decodable::decode(__decoder),
vectorize_slp: ::rustc_serialize::Decodable::decode(__decoder),
merge_functions: ::rustc_serialize::Decodable::decode(__decoder),
emit_lifetime_markers: ::rustc_serialize::Decodable::decode(__decoder),
llvm_plugins: ::rustc_serialize::Decodable::decode(__decoder),
autodiff: ::rustc_serialize::Decodable::decode(__decoder),
autodiff_post_passes: ::rustc_serialize::Decodable::decode(__decoder),
offload: ::rustc_serialize::Decodable::decode(__decoder),
}
}
}
};Decodable)]
72pub struct ModuleConfig {
73/// Names of additional optimization passes to run.
74pub passes: Vec<String>,
75/// Some(level) to optimize at a certain level, or None to run
76 /// absolutely no optimizations (used for the allocator module).
77pub opt_level: Option<config::OptLevel>,
7879pub pgo_gen: SwitchWithOptPath,
80pub pgo_use: Option<PathBuf>,
81pub pgo_sample_use: Option<PathBuf>,
82pub debug_info_for_profiling: bool,
83pub instrument_coverage: bool,
8485pub sanitizer: SanitizerSet,
86pub sanitizer_cfi_diag: Option<bool>,
87pub sanitizer_cfi_recover: Option<bool>,
88pub sanitizer_recover: SanitizerSet,
89pub sanitizer_dataflow_abilist: Vec<String>,
90pub sanitizer_memory_track_origins: usize,
9192// Flags indicating which outputs to produce.
93pub emit_pre_lto_bc: bool,
94pub emit_bc: bool,
95pub emit_ir: bool,
96pub emit_asm: bool,
97pub emit_obj: EmitObj,
98pub emit_thin_lto_summary: bool,
99100// Miscellaneous flags. These are mostly copied from command-line
101 // options.
102pub verify_llvm_ir: bool,
103pub lint_llvm_ir: bool,
104pub no_prepopulate_passes: bool,
105pub no_builtins: bool,
106pub vectorize_loop: bool,
107pub vectorize_slp: bool,
108pub merge_functions: bool,
109pub emit_lifetime_markers: bool,
110pub llvm_plugins: Vec<String>,
111pub autodiff: Vec<config::AutoDiff>,
112pub autodiff_post_passes: Option<String>,
113pub offload: Vec<config::Offload>,
114}
115116impl ModuleConfig {
117pub(crate) fn new(kind: ModuleKind, tcx: TyCtxt<'_>, no_builtins: bool) -> ModuleConfig {
118// If it's a regular module, use `$regular`, otherwise use `$other`.
119 // `$regular` and `$other` are evaluated lazily.
120macro_rules! if_regular {
121 ($regular: expr, $other: expr) => {
122if let ModuleKind::Regular = kind { $regular } else { $other }
123 };
124 }
125126let sess = tcx.sess;
127let opt_level_and_size = if let ModuleKind::Regular = kind { Some(sess.opts.optimize) } else { None }if_regular!(Some(sess.opts.optimize), None);
128129let save_temps = sess.opts.cg.save_temps;
130131let should_emit_obj = sess.opts.output_types.contains_key(&OutputType::Exe)
132 || match kind {
133 ModuleKind::Regular => sess.opts.output_types.contains_key(&OutputType::Object),
134 ModuleKind::Allocator => false,
135 };
136137let emit_obj = if !should_emit_obj {
138 EmitObj::None139 } else if sess.target.obj_is_bitcode
140 || (sess.opts.cg.linker_plugin_lto.enabled()
141 && (!no_builtins || tcx.sess.is_sanitizer_cfi_enabled()))
142 {
143// This case is selected if the target uses objects as bitcode, or
144 // if linker plugin LTO is enabled. In the linker plugin LTO case
145 // the assumption is that the final link-step will read the bitcode
146 // and convert it to object code. This may be done by either the
147 // native linker or rustc itself.
148 //
149 // By default this branch is skipped for `#![no_builtins]` crates so
150 // they emit native object files (machine code), not LLVM bitcode
151 // objects for the linker (see rust-lang/rust#146133).
152 //
153 // However, when LLVM CFI is enabled (`-Zsanitizer=cfi`), this
154 // breaks LLVM's expected pipeline: LLVM emits `llvm.type.test`
155 // intrinsics and related metadata that must be lowered by LLVM's
156 // `LowerTypeTests` pass before instruction selection during
157 // link-time LTO. Otherwise, `llvm.type.test` intrinsics and related
158 // metadata are not lowered by LLVM's `LowerTypeTests` pass before
159 // reaching the target backend, and LLVM may abort during codegen
160 // (for example in SelectionDAG type legalization) (see
161 // rust-lang/rust#142284).
162 //
163 // Therefore, with `-Clinker-plugin-lto` and `-Zsanitizer=cfi`, a
164 // `#![no_builtins]` crate must still use rustc's `EmitObj::Bitcode`
165 // path (and emit LLVM bitcode in the `.o` for linker-based LTO).
166EmitObj::Bitcode167 } else if need_bitcode_in_object(tcx) || sess.target.requires_lto {
168 EmitObj::ObjectCode(BitcodeSection::Full)
169 } else {
170 EmitObj::ObjectCode(BitcodeSection::None)
171 };
172173ModuleConfig {
174 passes: if let ModuleKind::Regular = kind {
sess.opts.cg.passes.clone()
} else { ::alloc::vec::Vec::new() }if_regular!(sess.opts.cg.passes.clone(), vec![]),
175176 opt_level: opt_level_and_size,
177178 pgo_gen: if let ModuleKind::Regular = kind {
sess.opts.cg.profile_generate.clone()
} else { SwitchWithOptPath::Disabled }if_regular!(
179 sess.opts.cg.profile_generate.clone(),
180 SwitchWithOptPath::Disabled
181 ),
182 pgo_use: if let ModuleKind::Regular = kind {
sess.opts.cg.profile_use.clone()
} else { None }if_regular!(sess.opts.cg.profile_use.clone(), None),
183 pgo_sample_use: if let ModuleKind::Regular = kind {
sess.opts.cg.profile_sample_use.clone()
} else { None }if_regular!(sess.opts.cg.profile_sample_use.clone(), None),
184 debug_info_for_profiling: sess.opts.unstable_opts.debuginfo_for_profiling,
185 instrument_coverage: if let ModuleKind::Regular = kind {
sess.instrument_coverage()
} else { false }if_regular!(sess.instrument_coverage(), false),
186187 sanitizer: if let ModuleKind::Regular = kind {
sess.sanitizers()
} else { SanitizerSet::empty() }if_regular!(sess.sanitizers(), SanitizerSet::empty()),
188 sanitizer_cfi_diag: if let ModuleKind::Regular = kind {
sess.opts.unstable_opts.sanitizer_cfi_diag
} else { None }if_regular!(sess.opts.unstable_opts.sanitizer_cfi_diag, None),
189 sanitizer_cfi_recover: if let ModuleKind::Regular = kind {
sess.opts.unstable_opts.sanitizer_cfi_recover
} else { None }if_regular!(sess.opts.unstable_opts.sanitizer_cfi_recover, None),
190 sanitizer_dataflow_abilist: if let ModuleKind::Regular = kind {
sess.opts.unstable_opts.sanitizer_dataflow_abilist.clone()
} else { Vec::new() }if_regular!(
191 sess.opts.unstable_opts.sanitizer_dataflow_abilist.clone(),
192 Vec::new()
193 ),
194 sanitizer_recover: if let ModuleKind::Regular = kind {
sess.opts.unstable_opts.sanitizer_recover
} else { SanitizerSet::empty() }if_regular!(
195 sess.opts.unstable_opts.sanitizer_recover,
196 SanitizerSet::empty()
197 ),
198 sanitizer_memory_track_origins: if let ModuleKind::Regular = kind {
sess.opts.unstable_opts.sanitizer_memory_track_origins
} else { 0 }if_regular!(
199 sess.opts.unstable_opts.sanitizer_memory_track_origins,
2000
201),
202203 emit_pre_lto_bc: if let ModuleKind::Regular = kind {
save_temps || need_pre_lto_bitcode_for_incr_comp(sess)
} else { false }if_regular!(
204 save_temps || need_pre_lto_bitcode_for_incr_comp(sess),
205false
206),
207 emit_bc: if let ModuleKind::Regular = kind {
save_temps || sess.opts.output_types.contains_key(&OutputType::Bitcode)
} else { save_temps }if_regular!(
208 save_temps || sess.opts.output_types.contains_key(&OutputType::Bitcode),
209 save_temps
210 ),
211 emit_ir: if let ModuleKind::Regular = kind {
sess.opts.output_types.contains_key(&OutputType::LlvmAssembly)
} else { false }if_regular!(
212 sess.opts.output_types.contains_key(&OutputType::LlvmAssembly),
213false
214),
215 emit_asm: if let ModuleKind::Regular = kind {
sess.opts.output_types.contains_key(&OutputType::Assembly)
} else { false }if_regular!(
216 sess.opts.output_types.contains_key(&OutputType::Assembly),
217false
218),
219emit_obj,
220 emit_thin_lto_summary: if let ModuleKind::Regular = kind {
sess.opts.output_types.contains_key(&OutputType::ThinLinkBitcode)
} else { false }if_regular!(
221 sess.opts.output_types.contains_key(&OutputType::ThinLinkBitcode),
222false
223),
224225 verify_llvm_ir: sess.verify_llvm_ir(),
226 lint_llvm_ir: sess.opts.unstable_opts.lint_llvm_ir,
227 no_prepopulate_passes: sess.opts.cg.no_prepopulate_passes,
228 no_builtins: no_builtins || sess.target.no_builtins,
229230// Copy what clang does by turning on loop vectorization at O2 and
231 // slp vectorization at O3.
232vectorize_loop: !sess.opts.cg.no_vectorize_loops
233 && (sess.opts.optimize == config::OptLevel::More234 || sess.opts.optimize == config::OptLevel::Aggressive),
235 vectorize_slp: !sess.opts.cg.no_vectorize_slp
236 && sess.opts.optimize == config::OptLevel::Aggressive,
237238// Some targets (namely, NVPTX) interact badly with the
239 // MergeFunctions pass. This is because MergeFunctions can generate
240 // new function calls which may interfere with the target calling
241 // convention; e.g. for the NVPTX target, PTX kernels should not
242 // call other PTX kernels. MergeFunctions can also be configured to
243 // generate aliases instead, but aliases are not supported by some
244 // backends (again, NVPTX). Therefore, allow targets to opt out of
245 // the MergeFunctions pass, but otherwise keep the pass enabled (at
246 // O2 and O3) since it can be useful for reducing code size.
247merge_functions: match sess248 .opts
249 .unstable_opts
250 .merge_functions
251 .unwrap_or(sess.target.merge_functions)
252 {
253 MergeFunctions::Disabled => false,
254 MergeFunctions::Trampolines | MergeFunctions::Aliases => {
255use config::OptLevel::*;
256match sess.opts.optimize {
257Aggressive | More | SizeMin | Size => true,
258Less | No => false,
259 }
260 }
261 },
262263 emit_lifetime_markers: sess.emit_lifetime_markers(),
264 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![]),
265 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![]),
266 autodiff_post_passes: if let ModuleKind::Regular = kind {
sess.opts.unstable_opts.autodiff_post_passes.clone()
} else { None }if_regular!(
267 sess.opts.unstable_opts.autodiff_post_passes.clone(),
268None
269),
270 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![]),
271 }
272 }
273274pub fn bitcode_needed(&self) -> bool {
275self.emit_bc
276 || self.emit_thin_lto_summary
277 || self.emit_obj == EmitObj::Bitcode278 || self.emit_obj == EmitObj::ObjectCode(BitcodeSection::Full)
279 }
280281pub fn embed_bitcode(&self) -> bool {
282self.emit_obj == EmitObj::ObjectCode(BitcodeSection::Full)
283 }
284}
285286/// Configuration passed to the function returned by the `target_machine_factory`.
287pub struct TargetMachineFactoryConfig {
288/// Split DWARF is enabled in LLVM by checking that `TM.MCOptions.SplitDwarfFile` isn't empty,
289 /// so the path to the dwarf object has to be provided when we create the target machine.
290 /// This can be ignored by backends which do not need it for their Split DWARF support.
291pub split_dwarf_file: Option<PathBuf>,
292293/// The name of the output object file. Used for setting OutputFilenames in target options
294 /// so that LLVM can emit the CodeView S_OBJNAME record in pdb files
295pub output_obj_file: Option<PathBuf>,
296}
297298impl TargetMachineFactoryConfig {
299pub fn new(cgcx: &CodegenContext, module_name: &str) -> TargetMachineFactoryConfig {
300let split_dwarf_file = if cgcx.target_can_use_split_dwarf {
301cgcx.output_filenames.split_dwarf_path(
302cgcx.split_debuginfo,
303cgcx.split_dwarf_kind,
304module_name,
305 )
306 } else {
307None308 };
309310let output_obj_file =
311Some(cgcx.output_filenames.temp_path_for_cgu(OutputType::Object, module_name));
312TargetMachineFactoryConfig { split_dwarf_file, output_obj_file }
313 }
314}
315316pub type TargetMachineFactoryFn<B> = Arc<
317dyn Fn(
318DiagCtxtHandle<'_>,
319TargetMachineFactoryConfig,
320 ) -> <B as WriteBackendMethods>::TargetMachine321 + Send322 + Sync,
323>;
324325/// Additional resources used by optimize_and_codegen (not module specific)
326#[derive(#[automatically_derived]
impl ::core::clone::Clone for CodegenContext {
#[inline]
fn clone(&self) -> Self {
Self {
lto: ::core::clone::Clone::clone(&self.lto),
use_linker_plugin_lto: ::core::clone::Clone::clone(&self.use_linker_plugin_lto),
dylib_lto: ::core::clone::Clone::clone(&self.dylib_lto),
prefer_dynamic: ::core::clone::Clone::clone(&self.prefer_dynamic),
save_temps: ::core::clone::Clone::clone(&self.save_temps),
fewer_names: ::core::clone::Clone::clone(&self.fewer_names),
time_trace: ::core::clone::Clone::clone(&self.time_trace),
crate_types: ::core::clone::Clone::clone(&self.crate_types),
output_filenames: ::core::clone::Clone::clone(&self.output_filenames),
module_config: ::core::clone::Clone::clone(&self.module_config),
opt_level: ::core::clone::Clone::clone(&self.opt_level),
msvc_imps_needed: ::core::clone::Clone::clone(&self.msvc_imps_needed),
is_pe_coff: ::core::clone::Clone::clone(&self.is_pe_coff),
target_can_use_split_dwarf: ::core::clone::Clone::clone(&self.target_can_use_split_dwarf),
target_arch: ::core::clone::Clone::clone(&self.target_arch),
target_is_like_darwin: ::core::clone::Clone::clone(&self.target_is_like_darwin),
target_is_like_aix: ::core::clone::Clone::clone(&self.target_is_like_aix),
target_is_like_gpu: ::core::clone::Clone::clone(&self.target_is_like_gpu),
split_debuginfo: ::core::clone::Clone::clone(&self.split_debuginfo),
split_dwarf_kind: ::core::clone::Clone::clone(&self.split_dwarf_kind),
pointer_size: ::core::clone::Clone::clone(&self.pointer_size),
remark: ::core::clone::Clone::clone(&self.remark),
remark_dir: ::core::clone::Clone::clone(&self.remark_dir),
old_incr_comp_session_dir: ::core::clone::Clone::clone(&self.old_incr_comp_session_dir),
new_incr_comp_session_dir: ::core::clone::Clone::clone(&self.new_incr_comp_session_dir),
parallel: ::core::clone::Clone::clone(&self.parallel),
}
}
}Clone, const _: () =
{
impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
for CodegenContext {
fn encode(&self, __encoder: &mut __E) {
let CodegenContext {
lto: ref __binding_0,
use_linker_plugin_lto: ref __binding_1,
dylib_lto: ref __binding_2,
prefer_dynamic: ref __binding_3,
save_temps: ref __binding_4,
fewer_names: ref __binding_5,
time_trace: ref __binding_6,
crate_types: ref __binding_7,
output_filenames: ref __binding_8,
module_config: ref __binding_9,
opt_level: ref __binding_10,
msvc_imps_needed: ref __binding_11,
is_pe_coff: ref __binding_12,
target_can_use_split_dwarf: ref __binding_13,
target_arch: ref __binding_14,
target_is_like_darwin: ref __binding_15,
target_is_like_aix: ref __binding_16,
target_is_like_gpu: ref __binding_17,
split_debuginfo: ref __binding_18,
split_dwarf_kind: ref __binding_19,
pointer_size: ref __binding_20,
remark: ref __binding_21,
remark_dir: ref __binding_22,
old_incr_comp_session_dir: ref __binding_23,
new_incr_comp_session_dir: ref __binding_24,
parallel: ref __binding_25 } = *self;
::rustc_serialize::Encodable::<__E>::encode(__binding_0,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_1,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_2,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_3,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_4,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_5,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_6,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_7,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_8,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_9,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_10,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_11,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_12,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_13,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_14,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_15,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_16,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_17,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_18,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_19,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_20,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_21,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_22,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_23,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_24,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_25,
__encoder);
}
}
};Encodable, const _: () =
{
impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
for CodegenContext {
fn decode(__decoder: &mut __D) -> Self {
CodegenContext {
lto: ::rustc_serialize::Decodable::decode(__decoder),
use_linker_plugin_lto: ::rustc_serialize::Decodable::decode(__decoder),
dylib_lto: ::rustc_serialize::Decodable::decode(__decoder),
prefer_dynamic: ::rustc_serialize::Decodable::decode(__decoder),
save_temps: ::rustc_serialize::Decodable::decode(__decoder),
fewer_names: ::rustc_serialize::Decodable::decode(__decoder),
time_trace: ::rustc_serialize::Decodable::decode(__decoder),
crate_types: ::rustc_serialize::Decodable::decode(__decoder),
output_filenames: ::rustc_serialize::Decodable::decode(__decoder),
module_config: ::rustc_serialize::Decodable::decode(__decoder),
opt_level: ::rustc_serialize::Decodable::decode(__decoder),
msvc_imps_needed: ::rustc_serialize::Decodable::decode(__decoder),
is_pe_coff: ::rustc_serialize::Decodable::decode(__decoder),
target_can_use_split_dwarf: ::rustc_serialize::Decodable::decode(__decoder),
target_arch: ::rustc_serialize::Decodable::decode(__decoder),
target_is_like_darwin: ::rustc_serialize::Decodable::decode(__decoder),
target_is_like_aix: ::rustc_serialize::Decodable::decode(__decoder),
target_is_like_gpu: ::rustc_serialize::Decodable::decode(__decoder),
split_debuginfo: ::rustc_serialize::Decodable::decode(__decoder),
split_dwarf_kind: ::rustc_serialize::Decodable::decode(__decoder),
pointer_size: ::rustc_serialize::Decodable::decode(__decoder),
remark: ::rustc_serialize::Decodable::decode(__decoder),
remark_dir: ::rustc_serialize::Decodable::decode(__decoder),
old_incr_comp_session_dir: ::rustc_serialize::Decodable::decode(__decoder),
new_incr_comp_session_dir: ::rustc_serialize::Decodable::decode(__decoder),
parallel: ::rustc_serialize::Decodable::decode(__decoder),
}
}
}
};Decodable)]
327pub struct CodegenContext {
328// Resources needed when running LTO
329pub lto: Lto,
330pub use_linker_plugin_lto: bool,
331pub dylib_lto: bool,
332pub prefer_dynamic: bool,
333pub save_temps: bool,
334pub fewer_names: bool,
335pub time_trace: bool,
336pub crate_types: Vec<CrateType>,
337pub output_filenames: Arc<OutputFilenames>,
338pub module_config: Arc<ModuleConfig>,
339pub opt_level: OptLevel,
340pub msvc_imps_needed: bool,
341pub is_pe_coff: bool,
342pub target_can_use_split_dwarf: bool,
343pub target_arch: String,
344pub target_is_like_darwin: bool,
345pub target_is_like_aix: bool,
346pub target_is_like_gpu: bool,
347pub split_debuginfo: rustc_target::spec::SplitDebuginfo,
348pub split_dwarf_kind: rustc_session::config::SplitDwarfKind,
349pub pointer_size: Size,
350351/// LLVM optimizations for which we want to print remarks.
352pub remark: Passes,
353/// Directory into which should the LLVM optimization remarks be written.
354 /// If `None`, they will be written to stderr.
355pub remark_dir: Option<PathBuf>,
356/// The previous incremental compilation session directory, or None if we
357 /// are not compiling incrementally or there is no previous session.
358pub old_incr_comp_session_dir: Option<PathBuf>,
359/// The incremental compilation session directory, or None if we are not
360 /// compiling incrementally
361pub new_incr_comp_session_dir: Option<PathBuf>,
362/// `Some(limit)` if the codegen should be run in parallel.
363 ///
364 /// Depends on [`WriteBackendMethods::supports_parallel()`] and `--jobs-backend`.
365pub parallel: Option<NonZero<usize>>,
366}
367368fn generate_thin_lto_work<B: WriteBackendMethods>(
369 cgcx: &CodegenContext,
370 prof: &SelfProfilerRef,
371 dcx: DiagCtxtHandle<'_>,
372 exported_symbols_for_lto: &[String],
373 each_linked_rlib_for_lto: &[PathBuf],
374 needs_thin_lto: Vec<ThinLtoInput<B>>,
375) -> Vec<(ThinLtoWorkItem<B>, u64)> {
376let _prof_timer = prof.generic_activity("codegen_thin_generate_lto_work");
377378let (lto_modules, copy_jobs) = B::run_thin_lto(
379cgcx,
380prof,
381dcx,
382exported_symbols_for_lto,
383each_linked_rlib_for_lto,
384needs_thin_lto,
385 );
386lto_modules387 .into_iter()
388 .map(|module| {
389let cost = module.cost();
390 (ThinLtoWorkItem::ThinLto(module), cost)
391 })
392 .chain(copy_jobs.into_iter().map(|wp| {
393 (
394 ThinLtoWorkItem::CopyPostLtoArtifacts(CachedModuleCodegen {
395 name: wp.cgu_name.clone(),
396 source: wp,
397 }),
3980, // copying is very cheap
399)
400 }))
401 .collect()
402}
403404enum MaybeLtoModules<B: WriteBackendMethods> {
405 NoLto(CompiledModules),
406 FatLto { cgcx: CodegenContext, needs_fat_lto: Vec<FatLtoInput<B>> },
407 ThinLto { cgcx: CodegenContext, needs_thin_lto: Vec<ThinLtoInput<B>> },
408}
409410fn need_bitcode_in_object(tcx: TyCtxt<'_>) -> bool {
411let sess = tcx.sess;
412sess.opts.cg.embed_bitcode
413 && tcx.crate_types().contains(&CrateType::Rlib)
414 && sess.opts.output_types.contains_key(&OutputType::Exe)
415}
416417fn need_pre_lto_bitcode_for_incr_comp(sess: &Session) -> bool {
418if sess.opts.incremental.is_none() {
419return false;
420 }
421422match sess.lto() {
423 Lto::No => false,
424 Lto::Fat | Lto::Thin | Lto::ThinLocal => true,
425 }
426}
427428pub(crate) fn start_async_codegen<B: WriteBackendMethods>(
429 backend: B,
430 tcx: TyCtxt<'_>,
431 regular_config: Arc<ModuleConfig>,
432 allocator_config: Arc<ModuleConfig>,
433 allocator_module: Option<ModuleCodegen<B::Module>>,
434) -> OngoingCodegen<B> {
435let (coordinator_send, coordinator_receive) = channel();
436437let (shared_emitter, shared_emitter_main) = SharedEmitter::new();
438let (codegen_worker_send, codegen_worker_receive) = channel();
439440let coordinator_thread = start_executing_work(
441backend.clone(),
442tcx,
443shared_emitter,
444codegen_worker_send,
445coordinator_receive,
446regular_config,
447allocator_config,
448allocator_module,
449coordinator_send.clone(),
450 );
451452OngoingCodegen {
453backend,
454455codegen_worker_receive,
456shared_emitter_main,
457 coordinator: Coordinator {
458 sender: coordinator_send,
459 future: Some(coordinator_thread),
460 phantom: PhantomData,
461 },
462 output_filenames: Arc::clone(tcx.output_filenames(())),
463 }
464}
465466fn copy_all_cgu_workproducts_to_incr_comp_cache_dir(
467 sess: &Session,
468 incr_comp_session: Option<&IncrCompSession>,
469 compiled_modules: &CompiledModules,
470) -> WorkProductMap {
471let mut work_products = WorkProductMap::default();
472473if sess.opts.incremental.is_none() || sess.opts.unstable_opts.disable_incr_comp_backend_caching
474 {
475return work_products;
476 }
477478let _timer = sess.timer("copy_all_cgu_workproducts_to_incr_comp_cache_dir");
479480for module in compiled_modules.modules.iter().filter(|m| m.kind == ModuleKind::Regular) {
481let mut files = Vec::new();
482if let Some(object_file_path) = &module.object {
483 files.push((OutputType::Object.extension(), object_file_path.as_path()));
484 }
485if let Some(global_asm_object_file_path) = &module.global_asm_object {
486 files.push(("asm.o", global_asm_object_file_path.as_path()));
487 }
488if let Some(dwarf_object_file_path) = &module.dwarf_object {
489 files.push(("dwo", dwarf_object_file_path.as_path()));
490 }
491if let Some(path) = &module.assembly {
492 files.push((OutputType::Assembly.extension(), path.as_path()));
493 }
494if let Some(path) = &module.llvm_ir {
495 files.push((OutputType::LlvmAssembly.extension(), path.as_path()));
496 }
497if let Some(path) = &module.bytecode {
498 files.push((OutputType::Bitcode.extension(), path.as_path()));
499 }
500let (id, product) = copy_cgu_workproduct_to_incr_comp_cache_dir(
501 sess,
502 incr_comp_session.unwrap(),
503&module.name,
504 files.as_slice(),
505 );
506 work_products.insert(id, product);
507 }
508509work_products510}
511512pub fn produce_final_output_artifacts(
513 sess: &Session,
514 compiled_modules: &CompiledModules,
515 crate_output: &OutputFilenames,
516) {
517let mut user_wants_bitcode = false;
518let mut user_wants_objects = false;
519520// Produce final compile outputs.
521let copy_gracefully = |from: &Path, to: &OutFileName| match to {
522 OutFileName::Stdoutif let Err(e) = copy_to_stdout(from) => {
523sess.dcx().emit_err(diagnostics::CopyPath::new(from, to.as_path(), e));
524 }
525 OutFileName::Real(path) if let Err(e) = fs::copy(from, path) => {
526sess.dcx().emit_err(diagnostics::CopyPath::new(from, path, e));
527 }
528_ => {}
529 };
530531let copy_if_one_unit = |output_type: OutputType, keep_numbered: bool| {
532if let [module] = &compiled_modules.modules[..] {
533// 1) Only one codegen unit. In this case it's no difficulty
534 // to copy `foo.0.x` to `foo.x`.
535let path = crate_output.temp_path_for_cgu(output_type, &module.name);
536let output = crate_output.path(output_type);
537if !output_type.is_text_output() && output.is_tty() {
538sess.dcx().emit_err(diagnostics::BinaryOutputToTty {
539 shorthand: output_type.shorthand(),
540 });
541 } else {
542copy_gracefully(&path, &output);
543 }
544if !sess.opts.cg.save_temps && !keep_numbered {
545// The user just wants `foo.x`, not `foo.#module-name#.x`.
546ensure_removed(sess.dcx(), &path);
547 }
548 } else {
549if crate_output.outputs.contains_explicit_name(&output_type) {
550// 2) Multiple codegen units, with `--emit foo=some_name`. We have
551 // no good solution for this case, so warn the user.
552sess.dcx().emit_warn(diagnostics::IgnoringEmitPath {
553 extension: output_type.extension(),
554 });
555 } else if crate_output.single_output_file.is_some() {
556// 3) Multiple codegen units, with `-o some_name`. We have
557 // no good solution for this case, so warn the user.
558sess.dcx()
559 .emit_warn(diagnostics::IgnoringOutput { extension: output_type.extension() });
560 } else {
561// 4) Multiple codegen units, but no explicit name. We
562 // just leave the `foo.0.x` files in place.
563 // (We don't have to do any work in this case.)
564}
565 }
566 };
567568// Flag to indicate whether the user explicitly requested bitcode.
569 // Otherwise, we produced it only as a temporary output, and will need
570 // to get rid of it.
571for output_type in crate_output.outputs.keys() {
572match *output_type {
573 OutputType::Bitcode => {
574 user_wants_bitcode = true;
575// Copy to .bc, but always keep the .0.bc. There is a later
576 // check to figure out if we should delete .0.bc files, or keep
577 // them for making an rlib.
578copy_if_one_unit(OutputType::Bitcode, true);
579 }
580 OutputType::ThinLinkBitcode => {
581 copy_if_one_unit(OutputType::ThinLinkBitcode, false);
582 }
583 OutputType::LlvmAssembly => {
584 copy_if_one_unit(OutputType::LlvmAssembly, false);
585 }
586 OutputType::Assembly => {
587 copy_if_one_unit(OutputType::Assembly, false);
588 }
589 OutputType::Object => {
590 user_wants_objects = true;
591 copy_if_one_unit(OutputType::Object, true);
592 }
593 OutputType::Mir | OutputType::Metadata | OutputType::Exe | OutputType::DepInfo => {}
594 }
595 }
596597// Clean up unwanted temporary files.
598599 // We create the following files by default:
600 // - #crate#.#module-name#.rcgu.bc
601 // - #crate#.#module-name#.rcgu.o
602 // - #crate#.o (linked from crate.##.rcgu.o)
603 // - #crate#.bc (copied from crate.##.rcgu.bc)
604 // We may create additional files if requested by the user (through
605 // `-C save-temps` or `--emit=` flags).
606607if !sess.opts.cg.save_temps {
608// Remove the temporary .#module-name#.rcgu.o objects. If the user didn't
609 // explicitly request bitcode (with --emit=bc), and the bitcode is not
610 // needed for building an rlib, then we must remove .#module-name#.bc as
611 // well.
612613 // Specific rules for keeping .#module-name#.rcgu.bc:
614 // - If the user requested bitcode (`user_wants_bitcode`), and
615 // codegen_units > 1, then keep it.
616 // - If the user requested bitcode but codegen_units == 1, then we
617 // can toss .#module-name#.rcgu.bc because we copied it to .bc earlier.
618 // - If we're not building an rlib and the user didn't request
619 // bitcode, then delete .#module-name#.rcgu.bc.
620 // If you change how this works, also update back::link::link_rlib,
621 // where .#module-name#.rcgu.bc files are (maybe) deleted after making an
622 // rlib.
623let needs_crate_object = crate_output.outputs.contains_key(&OutputType::Exe);
624625let keep_numbered_bitcode = user_wants_bitcode && sess.codegen_units().as_usize() > 1;
626627let keep_numbered_objects =
628needs_crate_object || (user_wants_objects && sess.codegen_units().as_usize() > 1);
629630for module in compiled_modules.modules.iter() {
631if !keep_numbered_objects {
632if let Some(ref path) = module.object {
633 ensure_removed(sess.dcx(), path);
634 }
635636if let Some(ref path) = module.global_asm_object {
637 ensure_removed(sess.dcx(), path);
638 }
639640if let Some(ref path) = module.dwarf_object {
641 ensure_removed(sess.dcx(), path);
642 }
643 }
644645if let Some(ref path) = module.bytecode {
646if !keep_numbered_bitcode {
647 ensure_removed(sess.dcx(), path);
648 }
649 }
650 }
651652if !user_wants_bitcode653 && let Some(ref allocator_module) = compiled_modules.allocator_module
654 && let Some(ref path) = allocator_module.bytecode
655 {
656ensure_removed(sess.dcx(), path);
657 }
658 }
659660if sess.opts.json_artifact_notifications {
661if let [module] = &compiled_modules.modules[..] {
662module.for_each_output(|_path, ty| {
663if sess.opts.output_types.contains_key(&ty) {
664let descr = ty.shorthand();
665// for single cgu file is renamed to drop cgu specific suffix
666 // so we regenerate it the same way
667let path = crate_output.path(ty);
668sess.dcx().emit_artifact_notification(path.as_path(), descr);
669 }
670 });
671 } else {
672for module in &compiled_modules.modules {
673 module.for_each_output(|path, ty| {
674if sess.opts.output_types.contains_key(&ty) {
675let descr = ty.shorthand();
676 sess.dcx().emit_artifact_notification(&path, descr);
677 }
678 });
679 }
680 }
681 }
682683// We leave the following files around by default:
684 // - #crate#.o
685 // - #crate#.bc
686 // These are used in linking steps and will be cleaned up afterward.
687}
688689pub(crate) enum WorkItem<B: WriteBackendMethods> {
690/// Optimize a newly codegened, totally unoptimized module.
691Optimize(ModuleCodegen<B::Module>),
692/// Copy the post-LTO artifacts from the incremental cache to the output
693 /// directory.
694CopyPostLtoArtifacts(CachedModuleCodegen),
695}
696697enum ThinLtoWorkItem<B: WriteBackendMethods> {
698/// Copy the post-LTO artifacts from the incremental cache to the output
699 /// directory.
700CopyPostLtoArtifacts(CachedModuleCodegen),
701/// Performs thin-LTO on the given module.
702ThinLto(lto::ThinModule<B>),
703}
704705// `pthread_setname()` on *nix ignores anything beyond the first 15
706// bytes. Use short descriptions to maximize the space available for
707// the module name.
708#[cfg(not(windows))]
709fn desc(short: &str, _long: &str, name: &str) -> String {
710// The short label is three bytes, and is followed by a space. That
711 // leaves 11 bytes for the CGU name. How we obtain those 11 bytes
712 // depends on the CGU name form.
713 //
714 // - Non-incremental, e.g. `regex.f10ba03eb5ec7975-cgu.0`: the part
715 // before the `-cgu.0` is the same for every CGU, so use the
716 // `cgu.0` part. The number suffix will be different for each
717 // CGU.
718 //
719 // - Incremental (normal), e.g. `2i52vvl2hco29us0`: use the whole
720 // name because each CGU will have a unique ASCII hash, and the
721 // first 11 bytes will be enough to identify it.
722 //
723 // - Incremental (with `-Zhuman-readable-cgu-names`), e.g.
724 // `regex.f10ba03eb5ec7975-re_builder.volatile`: use the whole
725 // name. The first 11 bytes won't be enough to uniquely identify
726 // it, but no obvious substring will, and this is a rarely used
727 // option so it doesn't matter much.
728 //
729{
match (&short.len(), &3) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(short.len(), 3);
730let name = if let Some(index) = name.find("-cgu.") {
731&name[index + 1..] // +1 skips the leading '-'.
732} else {
733name734 };
735::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} {1}", short, name))
})format!("{short} {name}")736}
737738// Windows has no thread name length limit, so use more descriptive names.
739#[cfg(windows)]
740fn desc(_short: &str, long: &str, name: &str) -> String {
741format!("{long} {name}")
742}
743744impl<B: WriteBackendMethods> WorkItem<B> {
745/// Generate a short description of this work item suitable for use as a thread name.
746fn short_description(&self) -> String {
747match self {
748 WorkItem::Optimize(m) => desc("opt", "optimize module", &m.name),
749 WorkItem::CopyPostLtoArtifacts(m) => desc("cpy", "copy LTO artifacts for", &m.name),
750 }
751 }
752}
753754impl<B: WriteBackendMethods> ThinLtoWorkItem<B> {
755/// Generate a short description of this work item suitable for use as a thread name.
756fn short_description(&self) -> String {
757match self {
758 ThinLtoWorkItem::CopyPostLtoArtifacts(m) => {
759desc("cpy", "copy LTO artifacts for", &m.name)
760 }
761 ThinLtoWorkItem::ThinLto(m) => desc("lto", "thin-LTO module", m.name()),
762 }
763 }
764}
765766/// A result produced by the backend.
767pub(crate) enum WorkItemResult<B: WriteBackendMethods> {
768/// The backend has finished compiling a CGU, nothing more required.
769Finished(CompiledModule),
770771/// The backend has finished compiling a CGU, which now needs to go through
772 /// fat LTO.
773NeedsFatLto(FatLtoInput<B>),
774775/// The backend has finished compiling a CGU, which now needs to go through
776 /// thin LTO.
777NeedsThinLto(String, B::ModuleBuffer),
778}
779780pub enum FatLtoInput<B: WriteBackendMethods> {
781 Serialized { name: String, bitcode_path: PathBuf },
782 InMemory(ModuleCodegen<B::Module>),
783}
784785pub enum ThinLtoInput<B: WriteBackendMethods> {
786 Red { name: String, buffer: SerializedModule<B::ModuleBuffer> },
787 Green { wp: WorkProduct, bitcode_path: PathBuf },
788}
789790/// Actual LTO type we end up choosing based on multiple factors.
791pub(crate) enum ComputedLtoType {
792 No,
793 Thin,
794 Fat,
795}
796797pub(crate) fn compute_per_cgu_lto_type(
798 sess_lto: &Lto,
799 linker_does_lto: bool,
800 sess_crate_types: &[CrateType],
801) -> ComputedLtoType {
802// If the linker does LTO, we don't have to do it. Note that we
803 // keep doing full LTO, if it is requested, as not to break the
804 // assumption that the output will be a single module.
805806 // We ignore a request for full crate graph LTO if the crate type
807 // is only an rlib, as there is no full crate graph to process,
808 // that'll happen later.
809 //
810 // This use case currently comes up primarily for targets that
811 // require LTO so the request for LTO is always unconditionally
812 // passed down to the backend, but we don't actually want to do
813 // anything about it yet until we've got a final product.
814let is_rlib = #[allow(non_exhaustive_omitted_patterns)] match sess_crate_types {
[CrateType::Rlib] => true,
_ => false,
}matches!(sess_crate_types, [CrateType::Rlib]);
815816match sess_lto {
817 Lto::ThinLocalif !linker_does_lto => ComputedLtoType::Thin,
818 Lto::Thinif !linker_does_lto && !is_rlib => ComputedLtoType::Thin,
819 Lto::Fatif !is_rlib => ComputedLtoType::Fat,
820_ => ComputedLtoType::No,
821 }
822}
823824fn execute_optimize_work_item<B: WriteBackendMethods>(
825 cgcx: &CodegenContext,
826 prof: &SelfProfilerRef,
827 shared_emitter: SharedEmitter,
828mut module: ModuleCodegen<B::Module>,
829) -> WorkItemResult<B> {
830let _timer = prof.generic_activity_with_arg("codegen_module_optimize", &*module.name);
831832 B::optimize(cgcx, prof, &shared_emitter, &mut module, &cgcx.module_config);
833834// After we've done the initial round of optimizations we need to
835 // decide whether to synchronously codegen this module or ship it
836 // back to the coordinator thread for further LTO processing (which
837 // has to wait for all the initial modules to be optimized).
838839let lto_type =
840compute_per_cgu_lto_type(&cgcx.lto, cgcx.use_linker_plugin_lto, &cgcx.crate_types);
841842// If we're doing some form of incremental LTO then we need to be sure to
843 // save our module to disk first.
844let bitcode = if cgcx.module_config.emit_pre_lto_bc {
845let filename = pre_lto_bitcode_filename(&module.name);
846cgcx.new_incr_comp_session_dir.as_ref().map(|path| path.join(&filename))
847 } else {
848None849 };
850851match lto_type {
852 ComputedLtoType::No => {
853let module = B::codegen(cgcx, &prof, &shared_emitter, module, &cgcx.module_config);
854 WorkItemResult::Finished(module)
855 }
856 ComputedLtoType::Thin => {
857let thin_buffer = B::serialize_module(module.module_llvm, true);
858if let Some(path) = bitcode {
859 fs::write(&path, thin_buffer.data()).unwrap_or_else(|e| {
860{
::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);
861 });
862 }
863 WorkItemResult::NeedsThinLto(module.name, thin_buffer)
864 }
865 ComputedLtoType::Fat => match bitcode {
866Some(path) => {
867let buffer = B::serialize_module(module.module_llvm, false);
868 fs::write(&path, buffer.data()).unwrap_or_else(|e| {
869{
::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);
870 });
871 WorkItemResult::NeedsFatLto(FatLtoInput::Serialized {
872 name: module.name,
873 bitcode_path: path,
874 })
875 }
876None => WorkItemResult::NeedsFatLto(FatLtoInput::InMemory(module)),
877 },
878 }
879}
880881fn execute_copy_from_cache_work_item(
882 cgcx: &CodegenContext,
883 prof: &SelfProfilerRef,
884 shared_emitter: SharedEmitter,
885 module: CachedModuleCodegen,
886) -> CompiledModule {
887let _timer =
888prof.generic_activity_with_arg("codegen_copy_artifacts_from_incr_cache", &*module.name);
889890let dcx = DiagCtxt::new(Box::new(shared_emitter));
891let dcx = dcx.handle();
892893let incr_comp_session_dir = cgcx.old_incr_comp_session_dir.as_ref().unwrap();
894895let load_from_incr_comp_dir = |output_path: PathBuf, saved_path: &str| {
896let source_file_in_incr_comp_dir = incr_comp_session_dir.join(saved_path);
897{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_codegen_ssa/src/back/write.rs:897",
"rustc_codegen_ssa::back::write", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_codegen_ssa/src/back/write.rs"),
::tracing_core::__macro_support::Option::Some(897u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::write"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("copying preexisting module `{0}` from {1:?} to {2}",
module.name, source_file_in_incr_comp_dir,
output_path.display()) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(
898"copying preexisting module `{}` from {:?} to {}",
899 module.name,
900 source_file_in_incr_comp_dir,
901 output_path.display()
902 );
903match link_or_copy(&source_file_in_incr_comp_dir, &output_path) {
904Ok(_) => Some(output_path),
905Err(error) => {
906dcx.emit_err(diagnostics::CopyPathBuf {
907 source_file: source_file_in_incr_comp_dir,
908output_path,
909error,
910 });
911None912 }
913 }
914 };
915916let dwarf_object =
917module.source.saved_files.get("dwo").as_ref().and_then(|saved_dwarf_object_file| {
918let dwarf_obj_out = cgcx919 .output_filenames
920 .split_dwarf_path(cgcx.split_debuginfo, cgcx.split_dwarf_kind, &module.name)
921 .expect(
922"saved dwarf object in work product but `split_dwarf_path` returned `None`",
923 );
924load_from_incr_comp_dir(dwarf_obj_out, saved_dwarf_object_file)
925 });
926927let load_from_incr_cache = |perform, output_type: OutputType| {
928if perform {
929let saved_file = module.source.saved_files.get(output_type.extension())?;
930let output_path = cgcx.output_filenames.temp_path_for_cgu(output_type, &module.name);
931load_from_incr_comp_dir(output_path, &saved_file)
932 } else {
933None934 }
935 };
936937let module_config = &cgcx.module_config;
938let should_emit_obj = module_config.emit_obj != EmitObj::None;
939let assembly = load_from_incr_cache(module_config.emit_asm, OutputType::Assembly);
940let llvm_ir = load_from_incr_cache(module_config.emit_ir, OutputType::LlvmAssembly);
941let bytecode = load_from_incr_cache(module_config.emit_bc, OutputType::Bitcode);
942let object = load_from_incr_cache(should_emit_obj, OutputType::Object);
943let global_asm_object =
944if should_emit_obj && let Some(saved_file) = module.source.saved_files.get("asm.o") {
945let output_path = cgcx.output_filenames.temp_path_ext_for_cgu("asm.o", &module.name);
946load_from_incr_comp_dir(output_path, &saved_file)
947 } else {
948None949 };
950if should_emit_obj && object.is_none() {
951dcx.emit_fatal(diagnostics::NoSavedObjectFile { cgu_name: &module.name })
952 }
953954CompiledModule {
955 kind: ModuleKind::Regular,
956 name: module.name,
957object,
958global_asm_object,
959dwarf_object,
960bytecode,
961assembly,
962llvm_ir,
963 }
964}
965966fn do_fat_lto<B: WriteBackendMethods>(
967 sess: &Session,
968 cgcx: &CodegenContext,
969 shared_emitter: SharedEmitter,
970 tm_factory: TargetMachineFactoryFn<B>,
971 exported_symbols_for_lto: &[String],
972 each_linked_rlib_for_lto: &[PathBuf],
973 needs_fat_lto: Vec<FatLtoInput<B>>,
974) -> CompiledModule {
975let _timer = sess.prof.verbose_generic_activity("LLVM_fatlto");
976977let dcx = DiagCtxt::new(Box::new(shared_emitter.clone()));
978let dcx = dcx.handle();
979980check_lto_allowed(&cgcx, dcx);
981982 B::optimize_and_codegen_fat_lto(
983sess,
984cgcx,
985&shared_emitter,
986tm_factory,
987exported_symbols_for_lto,
988each_linked_rlib_for_lto,
989needs_fat_lto,
990 )
991}
992993fn do_thin_lto<B: WriteBackendMethods>(
994 cgcx: &CodegenContext,
995 prof: &SelfProfilerRef,
996 shared_emitter: SharedEmitter,
997 tm_factory: TargetMachineFactoryFn<B>,
998 exported_symbols_for_lto: &[String],
999 each_linked_rlib_for_lto: &[PathBuf],
1000 needs_thin_lto: Vec<ThinLtoInput<B>>,
1001) -> Vec<CompiledModule> {
1002let _timer = prof.verbose_generic_activity("LLVM_thinlto");
10031004let dcx = DiagCtxt::new(Box::new(shared_emitter.clone()));
1005let dcx = dcx.handle();
10061007check_lto_allowed(&cgcx, dcx);
10081009let (coordinator_send, coordinator_receive) = channel();
10101011// First up, convert our jobserver into a helper thread so we can use normal
1012 // mpsc channels to manage our messages and such.
1013 // After we've requested tokens then we'll, when we can,
1014 // get tokens on `coordinator_receive` which will
1015 // get managed in the main loop below.
1016 // Note that using `jobserver::Proxy` is not necessary here, the code below always acquires
1017 // tokens before releasing them, so we can never accidentally release the last token
1018 // permanently held by rustc process.
1019let jobserver_helper = cgcx.parallel.map(|_| {
1020let coordinator_send2 = coordinator_send.clone();
1021 jobserver::client()
1022 .into_helper_thread(move |token| {
1023drop(coordinator_send2.send(ThinLtoMessage::Token(token)));
1024 })
1025 .expect("failed to spawn helper thread")
1026 });
10271028let mut work_items = ::alloc::vec::Vec::new()vec![];
10291030// We have LTO work to do. Perform the serial work here of
1031 // figuring out what we're going to LTO and then push a
1032 // bunch of work items onto our queue to do LTO. This all
1033 // happens on the coordinator thread but it's very quick so
1034 // we don't worry about tokens.
1035for (i, (work, cost)) in generate_thin_lto_work::<B>(
1036 cgcx,
1037 prof,
1038 dcx,
1039&exported_symbols_for_lto,
1040&each_linked_rlib_for_lto,
1041 needs_thin_lto,
1042 )
1043 .into_iter()
1044 .enumerate()
1045 {
1046let insertion_index =
1047 work_items.binary_search_by_key(&cost, |&(_, cost)| cost).unwrap_or_else(|e| e);
1048 work_items.insert(insertion_index, (work, cost));
1049if let Some(helper) = &jobserver_helper
1050 && i < cgcx.parallel.unwrap().get()
1051 {
1052 helper.request_token();
1053 }
1054 }
10551056let mut codegen_aborted = None;
10571058// These are the Jobserver Tokens we currently hold. Does not include
1059 // the implicit Token the compiler process owns no matter what.
1060let mut tokens = ::alloc::vec::Vec::new()vec![];
10611062// Amount of tokens that are used (including the implicit token).
1063let mut used_token_count = 0;
10641065let mut compiled_modules = ::alloc::vec::Vec::new()vec![];
10661067// Run the message loop while there's still anything that needs message
1068 // processing. Note that as soon as codegen is aborted we simply want to
1069 // wait for all existing work to finish, so many of the conditions here
1070 // only apply if codegen hasn't been aborted as they represent pending
1071 // work to be done.
1072loop {
1073if codegen_aborted.is_none() {
1074if used_token_count == 0 && work_items.is_empty() {
1075// All codegen work is done.
1076break;
1077 }
10781079// Spin up what work we can, only doing this while we've got available
1080 // parallelism slots and work left to spawn.
1081while used_token_count < tokens.len() + 1
1082&& let Some((item, _)) = work_items.pop()
1083 {
1084 spawn_thin_lto_work(
1085&cgcx,
1086 prof,
1087 shared_emitter.clone(),
1088 Arc::clone(&tm_factory),
1089 coordinator_send.clone(),
1090 item,
1091 );
1092 used_token_count += 1;
1093 }
1094 } else {
1095// Don't queue up any more work if codegen was aborted, we're
1096 // just waiting for our existing children to finish.
1097if used_token_count == 0 {
1098break;
1099 }
1100 }
11011102// Relinquish accidentally acquired extra tokens. Subtract 1 for the implicit token.
1103tokens.truncate(used_token_count.saturating_sub(1));
11041105match coordinator_receive.recv().unwrap() {
1106// Save the token locally and the next turn of the loop will use
1107 // this to spawn a new unit of work, or it may get dropped
1108 // immediately if we have no more work to spawn.
1109ThinLtoMessage::Token(token) => match token {
1110Ok(token) => {
1111tokens.push(token);
1112 }
1113Err(e) => {
1114let msg = &::alloc::__export::must_use({
::alloc::fmt::format(format_args!("failed to acquire jobserver token: {0}",
e))
})format!("failed to acquire jobserver token: {e}");
1115shared_emitter.fatal(msg);
1116codegen_aborted = Some(FatalError);
1117 }
1118 },
11191120 ThinLtoMessage::WorkItem { result } => {
1121// If a thread exits successfully then we drop a token associated
1122 // with that worker and update our `used_token_count` count.
1123 // We may later re-acquire a token to continue running more work.
1124 // We may also not actually drop a token here if the worker was
1125 // running with an "ephemeral token".
1126used_token_count -= 1;
11271128match result {
1129Ok(compiled_module) => compiled_modules.push(compiled_module),
1130Err(Some(WorkerFatalError)) => {
1131// Like `CodegenAborted`, wait for remaining work to finish.
1132codegen_aborted = Some(FatalError);
1133 }
1134Err(None) => {
1135// If the thread failed that means it panicked, so
1136 // we abort immediately.
1137::rustc_span::macros::bug_impl(None, format_args!("worker thread panicked"),
Location::caller());bug!("worker thread panicked");
1138 }
1139 }
1140 }
1141 }
1142 }
11431144if let Some(codegen_aborted) = codegen_aborted {
1145codegen_aborted.raise();
1146 }
11471148compiled_modules1149}
11501151/// Messages sent to the coordinator.
1152pub(crate) enum Message<B: WriteBackendMethods> {
1153/// A jobserver token has become available. Sent from the jobserver helper
1154 /// thread.
1155Token(io::Result<Acquired>),
11561157/// The backend has finished processing a work item for a codegen unit.
1158 /// Sent from a backend worker thread.
1159WorkItem { result: Result<WorkItemResult<B>, Option<WorkerFatalError>> },
11601161/// The frontend has finished generating something (backend IR or a
1162 /// post-LTO artifact) for a codegen unit, and it should be passed to the
1163 /// backend. Sent from the main thread.
1164CodegenDone { llvm_work_item: WorkItem<B>, cost: u64 },
11651166/// Similar to `CodegenDone`, but for reusing a pre-LTO artifact
1167 /// Sent from the main thread.
1168AddImportOnlyModule { bitcode_path: PathBuf, work_product: WorkProduct },
11691170/// The frontend has finished generating everything for all codegen units.
1171 /// Sent from the main thread.
1172CodegenComplete,
11731174/// Some normal-ish compiler error occurred, and codegen should be wound
1175 /// down. Sent from the main thread.
1176CodegenAborted,
1177}
11781179/// Messages sent to the coordinator.
1180pub(crate) enum ThinLtoMessage {
1181/// A jobserver token has become available. Sent from the jobserver helper
1182 /// thread.
1183Token(io::Result<Acquired>),
11841185/// The backend has finished processing a work item for a codegen unit.
1186 /// Sent from a backend worker thread.
1187WorkItem { result: Result<CompiledModule, Option<WorkerFatalError>> },
1188}
11891190/// A message sent from the coordinator thread to the main thread telling it to
1191/// process another codegen unit.
1192pub struct CguMessage;
11931194// A cut-down version of `rustc_errors::DiagInner` that impls `Send`, which
1195// can be used to send diagnostics from codegen threads to the main thread.
1196// It's missing the following fields from `rustc_errors::DiagInner`.
1197// - `span`: it doesn't impl `Send`.
1198// - `suggestions`: it doesn't impl `Send`, and isn't used for codegen
1199// diagnostics.
1200// - `is_lint`: lints aren't relevant during codegen.
1201// - `emitted_at`: not used for codegen diagnostics.
1202struct Diagnostic {
1203 span: Vec<SpanData>,
1204 level: Level,
1205 messages: Vec<(DiagMessage, Style)>,
1206 code: Option<ErrCode>,
1207 children: Vec<Subdiagnostic>,
1208 args: DiagArgMap,
1209}
12101211// A cut-down version of `rustc_errors::Subdiag` that impls `Send`. It's
1212// missing the following fields from `rustc_errors::Subdiag`.
1213// - `span`: it doesn't impl `Send`.
1214struct Subdiagnostic {
1215 level: Sublevel,
1216 messages: Vec<(DiagMessage, Style)>,
1217}
12181219#[derive(#[automatically_derived]
impl ::core::marker::StructuralPartialEq for MainThreadState { }
#[automatically_derived]
impl ::core::cmp::PartialEq for MainThreadState {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other)
}
}PartialEq, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for MainThreadState { }
#[automatically_derived]
impl ::core::clone::Clone for MainThreadState {
#[inline]
fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for MainThreadState { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for MainThreadState {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
MainThreadState::Idle => "Idle",
MainThreadState::Codegenning => "Codegenning",
MainThreadState::Lending => "Lending",
})
}
}Debug)]
1220enum MainThreadState {
1221/// Doing nothing.
1222Idle,
12231224/// Doing codegen, i.e. MIR-to-LLVM-IR conversion.
1225Codegenning,
12261227/// Idle, but lending the compiler process's Token to an LLVM thread so it can do useful work.
1228Lending,
1229}
12301231fn start_executing_work<B: WriteBackendMethods>(
1232 backend: B,
1233 tcx: TyCtxt<'_>,
1234 shared_emitter: SharedEmitter,
1235 codegen_worker_send: Sender<CguMessage>,
1236 coordinator_receive: Receiver<Message<B>>,
1237 regular_config: Arc<ModuleConfig>,
1238 allocator_config: Arc<ModuleConfig>,
1239mut allocator_module: Option<ModuleCodegen<B::Module>>,
1240 coordinator_send: Sender<Message<B>>,
1241) -> thread::JoinHandle<Result<MaybeLtoModules<B>, ()>> {
1242let sess = tcx.sess;
1243let prof = sess.prof.clone();
12441245// Compute the set of symbols we need to retain when doing thin local LTO (if we need to)
1246let exported_symbols_for_lto =
1247if sess.lto() == Lto::ThinLocal { lto::exported_symbols_for_lto(tcx, &[]) } else { ::alloc::vec::Vec::new()vec![] };
12481249// First up, convert our jobserver into a helper thread so we can use normal
1250 // mpsc channels to manage our messages and such.
1251 // After we've requested tokens then we'll, when we can,
1252 // get tokens on `coordinator_receive` which will
1253 // get managed in the main loop below.
1254 // Note that using `jobserver::Proxy` is not necessary here, the code below always acquires
1255 // tokens before releasing them, so we can never accidentally release the last token
1256 // permanently held by rustc process.
1257let parallel = match sess.opts.jobs.backend {
1258Some(n) if backend.supports_parallel() => Some(n),
1259_ => None,
1260 };
1261let jobserver_helper = parallel.map(|_| {
1262let coordinator_send2 = coordinator_send.clone();
1263 jobserver::client()
1264 .into_helper_thread(move |token| {
1265drop(coordinator_send2.send(Message::Token::<B>(token)));
1266 })
1267 .expect("failed to spawn helper thread")
1268 });
12691270let opt_level = tcx.backend_optimization_level(());
1271let tm_factory = backend.target_machine_factory(tcx.sess, opt_level);
12721273let remark_dir = if let Some(ref dir) = sess.opts.unstable_opts.remark_dir {
1274let result = fs::create_dir_all(dir).and_then(|_| dir.canonicalize());
1275match result {
1276Ok(dir) => Some(dir),
1277Err(error) => sess.dcx().emit_fatal(ErrorCreatingRemarkDir { error }),
1278 }
1279 } else {
1280None1281 };
12821283let cgcx = CodegenContext {
1284 crate_types: tcx.crate_types().to_vec(),
1285 lto: sess.lto(),
1286 use_linker_plugin_lto: sess.opts.cg.linker_plugin_lto.enabled(),
1287 dylib_lto: sess.opts.unstable_opts.dylib_lto,
1288 prefer_dynamic: sess.opts.cg.prefer_dynamic,
1289 fewer_names: sess.fewer_names(),
1290 save_temps: sess.opts.cg.save_temps,
1291 time_trace: sess.opts.unstable_opts.llvm_time_trace,
1292 remark: sess.opts.cg.remark.clone(),
1293remark_dir,
1294 old_incr_comp_session_dir: tcx1295 .incr_comp_session
1296 .as_ref()
1297 .and_then(|incr_comp_session| incr_comp_session.old_session_directory.as_deref())
1298 .map(ToOwned::to_owned),
1299 new_incr_comp_session_dir: tcx1300 .incr_comp_session
1301 .as_ref()
1302 .map(|incr_comp_session| (&*incr_comp_session.new_session_directory).to_owned()),
1303 output_filenames: Arc::clone(tcx.output_filenames(())),
1304 module_config: regular_config,
1305opt_level,
1306 msvc_imps_needed: msvc_imps_needed(tcx),
1307 is_pe_coff: tcx.sess.target.is_like_windows,
1308 target_can_use_split_dwarf: tcx.sess.target_can_use_split_dwarf(),
1309 target_arch: tcx.sess.target.arch.to_string(),
1310 target_is_like_darwin: tcx.sess.target.is_like_darwin,
1311 target_is_like_aix: tcx.sess.target.is_like_aix,
1312 target_is_like_gpu: tcx.sess.target.is_like_gpu,
1313 split_debuginfo: tcx.sess.split_debuginfo(),
1314 split_dwarf_kind: tcx.sess.opts.unstable_opts.split_dwarf_kind,
1315parallel,
1316 pointer_size: tcx.data_layout.pointer_size(),
1317 };
13181319// This is the "main loop" of parallel work happening for parallel codegen.
1320 // It's here that we manage parallelism, schedule work, and work with
1321 // messages coming from clients.
1322 //
1323 // There are a few environmental pre-conditions that shape how the system
1324 // is set up:
1325 //
1326 // - Error reporting can only happen on the main thread because that's the
1327 // only place where we have access to the compiler `Session`.
1328 // - LLVM work can be done on any thread.
1329 // - Codegen can only happen on the main thread.
1330 // - Each thread doing substantial work must be in possession of a `Token`
1331 // from the `Jobserver`.
1332 // - The compiler process always holds one `Token`. Any additional `Tokens`
1333 // have to be requested from the `Jobserver`.
1334 //
1335 // Error Reporting
1336 // ===============
1337 // The error reporting restriction is handled separately from the rest: We
1338 // set up a `SharedEmitter` that holds an open channel to the main thread.
1339 // When an error occurs on any thread, the shared emitter will send the
1340 // error message to the receiver main thread (`SharedEmitterMain`). The
1341 // main thread will periodically query this error message queue and emit
1342 // any error messages it has received. It might even abort compilation if
1343 // it has received a fatal error. In this case we rely on all other threads
1344 // being torn down automatically with the main thread.
1345 // Since the main thread will often be busy doing codegen work, error
1346 // reporting will be somewhat delayed, since the message queue can only be
1347 // checked in between two work packages.
1348 //
1349 // Work Processing Infrastructure
1350 // ==============================
1351 // The work processing infrastructure knows three major actors:
1352 //
1353 // - the coordinator thread,
1354 // - the main thread, and
1355 // - LLVM worker threads
1356 //
1357 // The coordinator thread is running a message loop. It instructs the main
1358 // thread about what work to do when, and it will spawn off LLVM worker
1359 // threads as open LLVM WorkItems become available.
1360 //
1361 // The job of the main thread is to codegen CGUs into LLVM work packages
1362 // (since the main thread is the only thread that can do this). The main
1363 // thread will block until it receives a message from the coordinator, upon
1364 // which it will codegen one CGU, send it to the coordinator and block
1365 // again. This way the coordinator can control what the main thread is
1366 // doing.
1367 //
1368 // The coordinator keeps a queue of LLVM WorkItems, and when a `Token` is
1369 // available, it will spawn off a new LLVM worker thread and let it process
1370 // a WorkItem. When a LLVM worker thread is done with its WorkItem,
1371 // it will just shut down, which also frees all resources associated with
1372 // the given LLVM module, and sends a message to the coordinator that the
1373 // WorkItem has been completed.
1374 //
1375 // Work Scheduling
1376 // ===============
1377 // The scheduler's goal is to minimize the time it takes to complete all
1378 // work there is, however, we also want to keep memory consumption low
1379 // if possible. These two goals are at odds with each other: If memory
1380 // consumption were not an issue, we could just let the main thread produce
1381 // LLVM WorkItems at full speed, assuring maximal utilization of
1382 // Tokens/LLVM worker threads. However, since codegen is usually faster
1383 // than LLVM processing, the queue of LLVM WorkItems would fill up and each
1384 // WorkItem potentially holds on to a substantial amount of memory.
1385 //
1386 // So the actual goal is to always produce just enough LLVM WorkItems as
1387 // not to starve our LLVM worker threads. That means, once we have enough
1388 // WorkItems in our queue, we can block the main thread, so it does not
1389 // produce more until we need them.
1390 //
1391 // Doing LLVM Work on the Main Thread
1392 // ----------------------------------
1393 // Since the main thread owns the compiler process's implicit `Token`, it is
1394 // wasteful to keep it blocked without doing any work. Therefore, what we do
1395 // in this case is: We spawn off an additional LLVM worker thread that helps
1396 // reduce the queue. The work it is doing corresponds to the implicit
1397 // `Token`. The coordinator will mark the main thread as being busy with
1398 // LLVM work. (The actual work happens on another OS thread but we just care
1399 // about `Tokens`, not actual threads).
1400 //
1401 // When any LLVM worker thread finishes while the main thread is marked as
1402 // "busy with LLVM work", we can do a little switcheroo: We give the Token
1403 // of the just finished thread to the LLVM worker thread that is working on
1404 // behalf of the main thread's implicit Token, thus freeing up the main
1405 // thread again. The coordinator can then again decide what the main thread
1406 // should do. This allows the coordinator to make decisions at more points
1407 // in time.
1408 //
1409 // Striking a Balance between Throughput and Memory Consumption
1410 // ------------------------------------------------------------
1411 // Since our two goals, (1) use as many Tokens as possible and (2) keep
1412 // memory consumption as low as possible, are in conflict with each other,
1413 // we have to find a trade off between them. Right now, the goal is to keep
1414 // all workers busy, which means that no worker should find the queue empty
1415 // when it is ready to start.
1416 // How do we do achieve this? Good question :) We actually never know how
1417 // many `Tokens` are potentially available so it's hard to say how much to
1418 // fill up the queue before switching the main thread to LLVM work. Also we
1419 // currently don't have a means to estimate how long a running LLVM worker
1420 // will still be busy with it's current WorkItem. However, we know the
1421 // maximal count of available Tokens that makes sense (=the number of CPU
1422 // cores), so we can take a conservative guess. The heuristic we use here
1423 // is implemented in the `queue_full_enough()` function.
1424 //
1425 // Some Background on Jobservers
1426 // -----------------------------
1427 // It's worth also touching on the management of parallelism here. We don't
1428 // want to just spawn a thread per work item because while that's optimal
1429 // parallelism it may overload a system with too many threads or violate our
1430 // configuration for the maximum amount of cpu to use for this process. To
1431 // manage this we use the `jobserver` crate.
1432 //
1433 // Job servers are an artifact of GNU make and are used to manage
1434 // parallelism between processes. A jobserver is a glorified IPC semaphore
1435 // basically. Whenever we want to run some work we acquire the semaphore,
1436 // and whenever we're done with that work we release the semaphore. In this
1437 // manner we can ensure that the maximum number of parallel workers is
1438 // capped at any one point in time.
1439 //
1440 // LTO and the coordinator thread
1441 // ------------------------------
1442 //
1443 // The final job the coordinator thread is responsible for is managing LTO
1444 // and how that works. When LTO is requested what we'll do is collect all
1445 // optimized LLVM modules into a local vector on the coordinator. Once all
1446 // modules have been codegened and optimized we hand this to the `lto`
1447 // module for further optimization. The `lto` module will return back a list
1448 // of more modules to work on, which the coordinator will continue to spawn
1449 // work for.
1450 //
1451 // Each LLVM module is automatically sent back to the coordinator for LTO if
1452 // necessary. There's already optimizations in place to avoid sending work
1453 // back to the coordinator if LTO isn't requested.
1454let f = move || {
1455let _profiler = if cgcx.time_trace { B::thread_profiler() } else { Box::new(()) };
14561457// This is where we collect codegen units that have gone all the way
1458 // through codegen and LLVM.
1459let mut compiled_modules = ::alloc::vec::Vec::new()vec![];
1460let mut needs_fat_lto = Vec::new();
1461let mut needs_thin_lto = Vec::new();
1462let mut lto_import_only_modules = Vec::new();
14631464/// Possible state transitions:
1465 /// - Ongoing -> Completed
1466 /// - Ongoing -> Aborted
1467 /// - Completed -> Aborted
1468#[derive(#[automatically_derived]
impl ::core::fmt::Debug for CodegenState {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
CodegenState::Ongoing => "Ongoing",
CodegenState::Completed => "Completed",
CodegenState::Aborted => "Aborted",
})
}
}Debug, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for CodegenState { }
#[automatically_derived]
impl ::core::cmp::PartialEq for CodegenState {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other)
}
}PartialEq)]
1469enum CodegenState {
1470 Ongoing,
1471 Completed,
1472 Aborted,
1473 }
1474use CodegenState::*;
1475let mut codegen_state = Ongoing;
14761477// This is the queue of LLVM work items that still need processing.
1478let mut work_items = Vec::<(WorkItem<B>, u64)>::new();
14791480// This are the Jobserver Tokens we currently hold. Does not include
1481 // the implicit Token the compiler process owns no matter what.
1482let mut tokens = Vec::new();
14831484let mut main_thread_state = MainThreadState::Idle;
14851486// How many LLVM worker threads are running while holding a Token. This
1487 // *excludes* any that the main thread is lending a Token to.
1488let mut running_with_own_token = 0;
14891490// How many LLVM worker threads are running in total. This *includes*
1491 // any that the main thread is lending a Token to.
1492let running_with_any_token = |main_thread_state, running_with_own_token| {
1493running_with_own_token1494 + if main_thread_state == MainThreadState::Lending { 1 } else { 0 }
1495 };
14961497let mut llvm_start_time: Option<VerboseTimingGuard<'_>> = None;
14981499if let Some(allocator_module) = &mut allocator_module {
1500 B::optimize(&cgcx, &prof, &shared_emitter, allocator_module, &allocator_config);
1501 }
15021503// Run the message loop while there's still anything that needs message
1504 // processing. Note that as soon as codegen is aborted we simply want to
1505 // wait for all existing work to finish, so many of the conditions here
1506 // only apply if codegen hasn't been aborted as they represent pending
1507 // work to be done.
1508loop {
1509// While there are still CGUs to be codegened, the coordinator has
1510 // to decide how to utilize the compiler processes implicit Token:
1511 // For codegenning more CGU or for running them through LLVM.
1512if codegen_state == Ongoing {
1513if main_thread_state == MainThreadState::Idle {
1514// Compute the number of workers that will be running once we've taken as many
1515 // items from the work queue as we can, plus one for the main thread. It's not
1516 // critically important that we use this instead of just
1517 // `running_with_own_token`, but it prevents the `queue_full_enough` heuristic
1518 // from fluctuating just because a worker finished up and we decreased the
1519 // `running_with_own_token` count, even though we're just going to increase it
1520 // right after this when we put a new worker to work.
1521let extra_tokens = tokens.len().checked_sub(running_with_own_token).unwrap();
1522let additional_running = std::cmp::min(extra_tokens, work_items.len());
1523let anticipated_running = running_with_own_token + additional_running + 1;
15241525if !queue_full_enough(work_items.len(), anticipated_running) {
1526// The queue is not full enough, process more codegen units:
1527if codegen_worker_send.send(CguMessage).is_err() {
1528{
::core::panicking::panic_fmt(format_args!("Could not send CguMessage to main thread"));
}panic!("Could not send CguMessage to main thread")1529 }
1530main_thread_state = MainThreadState::Codegenning;
1531 } else {
1532// The queue is full enough to not let the worker
1533 // threads starve. Use the implicit Token to do some
1534 // LLVM work too.
1535let (item, _) =
1536work_items.pop().expect("queue empty - queue_full_enough() broken?");
1537main_thread_state = MainThreadState::Lending;
1538spawn_work(
1539&cgcx,
1540&prof,
1541shared_emitter.clone(),
1542coordinator_send.clone(),
1543&mut llvm_start_time,
1544item,
1545 );
1546 }
1547 }
1548 } else if codegen_state == Completed {
1549if running_with_any_token(main_thread_state, running_with_own_token) == 0
1550&& work_items.is_empty()
1551 {
1552// All codegen work is done.
1553break;
1554 }
15551556// In this branch, we know that everything has been codegened,
1557 // so it's just a matter of determining whether the implicit
1558 // Token is free to use for LLVM work.
1559match main_thread_state {
1560 MainThreadState::Idle => {
1561if let Some((item, _)) = work_items.pop() {
1562main_thread_state = MainThreadState::Lending;
1563spawn_work(
1564&cgcx,
1565&prof,
1566shared_emitter.clone(),
1567coordinator_send.clone(),
1568&mut llvm_start_time,
1569item,
1570 );
1571 } else {
1572// There is no unstarted work, so let the main thread
1573 // take over for a running worker. Otherwise the
1574 // implicit token would just go to waste.
1575 // We reduce the `running` counter by one. The
1576 // `tokens.truncate()` below will take care of
1577 // giving the Token back.
1578if !(running_with_own_token > 0) {
::core::panicking::panic("assertion failed: running_with_own_token > 0")
};assert!(running_with_own_token > 0);
1579running_with_own_token -= 1;
1580main_thread_state = MainThreadState::Lending;
1581 }
1582 }
1583 MainThreadState::Codegenning => ::rustc_span::macros::bug_impl(None,
format_args!("codegen worker should not be codegenning after codegen was already completed"),
Location::caller())bug!(
1584"codegen worker should not be codegenning after \
1585 codegen was already completed"
1586),
1587 MainThreadState::Lending => {
1588// Already making good use of that token
1589}
1590 }
1591 } else {
1592// Don't queue up any more work if codegen was aborted, we're
1593 // just waiting for our existing children to finish.
1594if !(codegen_state == Aborted) {
::core::panicking::panic("assertion failed: codegen_state == Aborted")
};assert!(codegen_state == Aborted);
1595if running_with_any_token(main_thread_state, running_with_own_token) == 0 {
1596break;
1597 }
1598 }
15991600// Spin up what work we can, only doing this while we've got available
1601 // parallelism slots and work left to spawn.
1602if codegen_state != Aborted {
1603while running_with_own_token < tokens.len()
1604 && let Some((item, _)) = work_items.pop()
1605 {
1606 spawn_work(
1607&cgcx,
1608&prof,
1609 shared_emitter.clone(),
1610 coordinator_send.clone(),
1611&mut llvm_start_time,
1612 item,
1613 );
1614 running_with_own_token += 1;
1615 }
1616 }
16171618// Relinquish accidentally acquired extra tokens.
1619tokens.truncate(running_with_own_token);
16201621match coordinator_receive.recv().unwrap() {
1622// Save the token locally and the next turn of the loop will use
1623 // this to spawn a new unit of work, or it may get dropped
1624 // immediately if we have no more work to spawn.
1625Message::Token(token) => {
1626match token {
1627Ok(token) => {
1628tokens.push(token);
16291630if main_thread_state == MainThreadState::Lending {
1631// If the main thread token is used for LLVM work
1632 // at the moment, we turn that thread into a regular
1633 // LLVM worker thread, so the main thread is free
1634 // to react to codegen demand.
1635main_thread_state = MainThreadState::Idle;
1636running_with_own_token += 1;
1637 }
1638 }
1639Err(e) => {
1640let msg = &::alloc::__export::must_use({
::alloc::fmt::format(format_args!("failed to acquire jobserver token: {0}",
e))
})format!("failed to acquire jobserver token: {e}");
1641shared_emitter.fatal(msg);
1642codegen_state = Aborted;
1643 }
1644 }
1645 }
16461647 Message::CodegenDone { llvm_work_item, cost } => {
1648// We keep the queue sorted by estimated processing cost,
1649 // so that more expensive items are processed earlier. This
1650 // is good for throughput as it gives the main thread more
1651 // time to fill up the queue and it avoids scheduling
1652 // expensive items to the end.
1653 // Note, however, that this is not ideal for memory
1654 // consumption, as LLVM module sizes are not evenly
1655 // distributed.
1656let insertion_index = work_items.binary_search_by_key(&cost, |&(_, cost)| cost);
1657let insertion_index = match insertion_index {
1658Ok(idx) | Err(idx) => idx,
1659 };
1660work_items.insert(insertion_index, (llvm_work_item, cost));
16611662if let Some(helper) = &jobserver_helper1663 && running_with_any_token(main_thread_state, running_with_own_token)
1664 < cgcx.parallel.unwrap().get()
1665 {
1666helper.request_token();
1667 }
1668{
match (&main_thread_state, &MainThreadState::Codegenning) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(main_thread_state, MainThreadState::Codegenning);
1669main_thread_state = MainThreadState::Idle;
1670 }
16711672 Message::CodegenComplete => {
1673if codegen_state != Aborted {
1674codegen_state = Completed;
1675 }
1676{
match (&main_thread_state, &MainThreadState::Codegenning) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(main_thread_state, MainThreadState::Codegenning);
1677main_thread_state = MainThreadState::Idle;
1678 }
16791680// If codegen is aborted that means translation was aborted due
1681 // to some normal-ish compiler error. In this situation we want
1682 // to exit as soon as possible, but we want to make sure all
1683 // existing work has finished. Flag codegen as being done, and
1684 // then conditions above will ensure no more work is spawned but
1685 // we'll keep executing this loop until `running_with_own_token`
1686 // hits 0.
1687Message::CodegenAborted => {
1688codegen_state = Aborted;
1689 }
16901691 Message::WorkItem { result } => {
1692// If a thread exits successfully then we drop a token associated
1693 // with that worker and update our `running_with_own_token` count.
1694 // We may later re-acquire a token to continue running more work.
1695 // We may also not actually drop a token here if the worker was
1696 // running with an "ephemeral token".
1697if main_thread_state == MainThreadState::Lending {
1698main_thread_state = MainThreadState::Idle;
1699 } else {
1700running_with_own_token -= 1;
1701 }
17021703match result {
1704Ok(WorkItemResult::Finished(compiled_module)) => {
1705compiled_modules.push(compiled_module);
1706 }
1707Ok(WorkItemResult::NeedsFatLto(fat_lto_input)) => {
1708if !needs_thin_lto.is_empty() {
::core::panicking::panic("assertion failed: needs_thin_lto.is_empty()")
};assert!(needs_thin_lto.is_empty());
1709needs_fat_lto.push(fat_lto_input);
1710 }
1711Ok(WorkItemResult::NeedsThinLto(name, thin_buffer)) => {
1712if !needs_fat_lto.is_empty() {
::core::panicking::panic("assertion failed: needs_fat_lto.is_empty()")
};assert!(needs_fat_lto.is_empty());
1713needs_thin_lto.push(ThinLtoInput::Red {
1714name,
1715 buffer: SerializedModule::Local(thin_buffer),
1716 });
1717 }
1718Err(Some(WorkerFatalError)) => {
1719// Like `CodegenAborted`, wait for remaining work to finish.
1720codegen_state = Aborted;
1721 }
1722Err(None) => {
1723// If the thread failed that means it panicked, so
1724 // we abort immediately.
1725::rustc_span::macros::bug_impl(None, format_args!("worker thread panicked"),
Location::caller());bug!("worker thread panicked");
1726 }
1727 }
1728 }
17291730 Message::AddImportOnlyModule { bitcode_path, work_product } => {
1731{
match (&codegen_state, &Ongoing) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(codegen_state, Ongoing);
1732{
match (&main_thread_state, &MainThreadState::Codegenning) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(main_thread_state, MainThreadState::Codegenning);
1733lto_import_only_modules.push((bitcode_path, work_product));
1734main_thread_state = MainThreadState::Idle;
1735 }
1736 }
1737 }
17381739// Drop to print timings
1740drop(llvm_start_time);
17411742if codegen_state == Aborted {
1743return Err(());
1744 }
17451746drop(codegen_state);
1747drop(tokens);
1748drop(jobserver_helper);
1749if !work_items.is_empty() {
::core::panicking::panic("assertion failed: work_items.is_empty()")
};assert!(work_items.is_empty());
17501751if !needs_fat_lto.is_empty() {
1752if !compiled_modules.is_empty() {
::core::panicking::panic("assertion failed: compiled_modules.is_empty()")
};assert!(compiled_modules.is_empty());
1753if !needs_thin_lto.is_empty() {
::core::panicking::panic("assertion failed: needs_thin_lto.is_empty()")
};assert!(needs_thin_lto.is_empty());
17541755if let Some(allocator_module) = allocator_module.take() {
1756needs_fat_lto.push(FatLtoInput::InMemory(allocator_module));
1757 }
17581759for (bitcode_path, wp) in lto_import_only_modules {
1760 needs_fat_lto.push(FatLtoInput::Serialized { name: wp.cgu_name, bitcode_path })
1761 }
17621763return Ok(MaybeLtoModules::FatLto { cgcx, needs_fat_lto });
1764 } else if !needs_thin_lto.is_empty() || !lto_import_only_modules.is_empty() {
1765if !compiled_modules.is_empty() {
::core::panicking::panic("assertion failed: compiled_modules.is_empty()")
};assert!(compiled_modules.is_empty());
1766if !needs_fat_lto.is_empty() {
::core::panicking::panic("assertion failed: needs_fat_lto.is_empty()")
};assert!(needs_fat_lto.is_empty());
17671768for (bitcode_path, wp) in lto_import_only_modules {
1769 needs_thin_lto.push(ThinLtoInput::Green { wp, bitcode_path })
1770 }
17711772if cgcx.lto == Lto::ThinLocal {
1773compiled_modules.extend(do_thin_lto::<B>(
1774&cgcx,
1775&prof,
1776shared_emitter.clone(),
1777tm_factory,
1778&exported_symbols_for_lto,
1779&[],
1780needs_thin_lto,
1781 ));
1782 } else {
1783if let Some(allocator_module) = allocator_module.take() {
1784let thin_buffer = B::serialize_module(allocator_module.module_llvm, true);
1785needs_thin_lto.push(ThinLtoInput::Red {
1786 name: allocator_module.name,
1787 buffer: SerializedModule::Local(thin_buffer),
1788 });
1789 }
17901791return Ok(MaybeLtoModules::ThinLto { cgcx, needs_thin_lto });
1792 }
1793 }
17941795Ok(MaybeLtoModules::NoLto(CompiledModules {
1796 modules: compiled_modules,
1797 allocator_module: allocator_module.map(|allocator_module| {
1798 B::codegen(&cgcx, &prof, &shared_emitter, allocator_module, &allocator_config)
1799 }),
1800 }))
1801 };
1802return std::thread::Builder::new()
1803 .name("coordinator".to_owned())
1804 .spawn(f)
1805 .expect("failed to spawn coordinator thread");
18061807// A heuristic that determines if we have enough LLVM WorkItems in the
1808 // queue so that the main thread can do LLVM work instead of codegen
1809fn queue_full_enough(items_in_queue: usize, workers_running: usize) -> bool {
1810// This heuristic scales ahead-of-time codegen according to available
1811 // concurrency, as measured by `workers_running`. The idea is that the
1812 // more concurrency we have available, the more demand there will be for
1813 // work items, and the fuller the queue should be kept to meet demand.
1814 // An important property of this approach is that we codegen ahead of
1815 // time only as much as necessary, so as to keep fewer LLVM modules in
1816 // memory at once, thereby reducing memory consumption.
1817 //
1818 // When the number of workers running is less than the max concurrency
1819 // available to us, this heuristic can cause us to instruct the main
1820 // thread to work on an LLVM item (that is, tell it to "LLVM") instead
1821 // of codegen, even though it seems like it *should* be codegenning so
1822 // that we can create more work items and spawn more LLVM workers.
1823 //
1824 // But this is not a problem. When the main thread is told to LLVM,
1825 // according to this heuristic and how work is scheduled, there is
1826 // always at least one item in the queue, and therefore at least one
1827 // pending jobserver token request. If there *is* more concurrency
1828 // available, we will immediately receive a token, which will upgrade
1829 // the main thread's LLVM worker to a real one (conceptually), and free
1830 // up the main thread to codegen if necessary. On the other hand, if
1831 // there isn't more concurrency, then the main thread working on an LLVM
1832 // item is appropriate, as long as the queue is full enough for demand.
1833 //
1834 // Speaking of which, how full should we keep the queue? Probably less
1835 // full than you'd think. A lot has to go wrong for the queue not to be
1836 // full enough and for that to have a negative effect on compile times.
1837 //
1838 // Workers are unlikely to finish at exactly the same time, so when one
1839 // finishes and takes another work item off the queue, we often have
1840 // ample time to codegen at that point before the next worker finishes.
1841 // But suppose that codegen takes so long that the workers exhaust the
1842 // queue, and we have one or more workers that have nothing to work on.
1843 // Well, it might not be so bad. Of all the LLVM modules we create and
1844 // optimize, one has to finish last. It's not necessarily the case that
1845 // by losing some concurrency for a moment, we delay the point at which
1846 // that last LLVM module is finished and the rest of compilation can
1847 // proceed. Also, when we can't take advantage of some concurrency, we
1848 // give tokens back to the job server. That enables some other rustc to
1849 // potentially make use of the available concurrency. That could even
1850 // *decrease* overall compile time if we're lucky. But yes, if no other
1851 // rustc can make use of the concurrency, then we've squandered it.
1852 //
1853 // However, keeping the queue full is also beneficial when we have a
1854 // surge in available concurrency. Then items can be taken from the
1855 // queue immediately, without having to wait for codegen.
1856 //
1857 // So, the heuristic below tries to keep one item in the queue for every
1858 // four running workers. Based on limited benchmarking, this appears to
1859 // be more than sufficient to avoid increasing compilation times.
1860let quarter_of_workers = workers_running - 3 * workers_running / 4;
1861items_in_queue > 0 && items_in_queue >= quarter_of_workers1862 }
1863}
18641865/// `FatalError` is explicitly not `Send`.
1866#[must_use]
1867pub(crate) struct WorkerFatalError;
18681869fn spawn_work<'a, B: WriteBackendMethods>(
1870 cgcx: &CodegenContext,
1871 prof: &'a SelfProfilerRef,
1872 shared_emitter: SharedEmitter,
1873 coordinator_send: Sender<Message<B>>,
1874 llvm_start_time: &mut Option<VerboseTimingGuard<'a>>,
1875 work: WorkItem<B>,
1876) {
1877if llvm_start_time.is_none() {
1878*llvm_start_time = Some(prof.verbose_generic_activity("LLVM_passes"));
1879 }
18801881let cgcx = cgcx.clone();
1882let prof = prof.clone();
18831884let name = work.short_description();
1885let f = move || {
1886let _profiler = if cgcx.time_trace { B::thread_profiler() } else { Box::new(()) };
18871888let result = std::panic::catch_unwind(AssertUnwindSafe(|| match work {
1889 WorkItem::Optimize(m) => execute_optimize_work_item(&cgcx, &prof, shared_emitter, m),
1890 WorkItem::CopyPostLtoArtifacts(m) => WorkItemResult::Finished(
1891execute_copy_from_cache_work_item(&cgcx, &prof, shared_emitter, m),
1892 ),
1893 }));
18941895let msg = match result {
1896Ok(result) => Message::WorkItem::<B> { result: Ok(result) },
18971898// We ignore any `FatalError` coming out of `execute_work_item`, as a
1899 // diagnostic was already sent off to the main thread - just surface
1900 // that there was an error in this worker.
1901Err(err) if err.is::<FatalErrorMarker>() => {
1902 Message::WorkItem::<B> { result: Err(Some(WorkerFatalError)) }
1903 }
19041905Err(_) => Message::WorkItem::<B> { result: Err(None) },
1906 };
1907drop(coordinator_send.send(msg));
1908 };
1909 std::thread::Builder::new().name(name).spawn(f).expect("failed to spawn work thread");
1910}
19111912fn spawn_thin_lto_work<B: WriteBackendMethods>(
1913 cgcx: &CodegenContext,
1914 prof: &SelfProfilerRef,
1915 shared_emitter: SharedEmitter,
1916 tm_factory: TargetMachineFactoryFn<B>,
1917 coordinator_send: Sender<ThinLtoMessage>,
1918 work: ThinLtoWorkItem<B>,
1919) {
1920let cgcx = cgcx.clone();
1921let prof = prof.clone();
19221923let name = work.short_description();
1924let f = move || {
1925let _profiler = if cgcx.time_trace { B::thread_profiler() } else { Box::new(()) };
19261927let result = std::panic::catch_unwind(AssertUnwindSafe(|| match work {
1928 ThinLtoWorkItem::CopyPostLtoArtifacts(m) => {
1929execute_copy_from_cache_work_item(&cgcx, &prof, shared_emitter, m)
1930 }
1931 ThinLtoWorkItem::ThinLto(m) => {
1932let _timer = prof.generic_activity_with_arg("codegen_module_perform_lto", m.name());
1933 B::optimize_and_codegen_thin(&cgcx, &prof, &shared_emitter, tm_factory, m)
1934 }
1935 }));
19361937let msg = match result {
1938Ok(result) => ThinLtoMessage::WorkItem { result: Ok(result) },
19391940// We ignore any `FatalError` coming out of `execute_work_item`, as a
1941 // diagnostic was already sent off to the main thread - just surface
1942 // that there was an error in this worker.
1943Err(err) if err.is::<FatalErrorMarker>() => {
1944 ThinLtoMessage::WorkItem { result: Err(Some(WorkerFatalError)) }
1945 }
19461947Err(_) => ThinLtoMessage::WorkItem { result: Err(None) },
1948 };
1949drop(coordinator_send.send(msg));
1950 };
1951 std::thread::Builder::new().name(name).spawn(f).expect("failed to spawn work thread");
1952}
19531954enum SharedEmitterMessage {
1955 Diagnostic(Diagnostic),
1956 InlineAsmError(InlineAsmError),
1957 Fatal(String),
1958}
19591960pub struct InlineAsmError {
1961pub span: SpanData,
1962pub msg: String,
1963pub level: Level,
1964pub source: Option<(String, Vec<InnerSpan>)>,
1965}
19661967#[derive(#[automatically_derived]
impl ::core::clone::Clone for SharedEmitter {
#[inline]
fn clone(&self) -> Self {
Self { sender: ::core::clone::Clone::clone(&self.sender) }
}
}Clone)]
1968pub struct SharedEmitter {
1969 sender: Sender<SharedEmitterMessage>,
1970}
19711972pub struct SharedEmitterMain {
1973 receiver: Receiver<SharedEmitterMessage>,
1974}
19751976impl SharedEmitter {
1977fn new() -> (SharedEmitter, SharedEmitterMain) {
1978let (sender, receiver) = channel();
19791980 (SharedEmitter { sender }, SharedEmitterMain { receiver })
1981 }
19821983pub fn inline_asm_error(&self, err: InlineAsmError) {
1984drop(self.sender.send(SharedEmitterMessage::InlineAsmError(err)));
1985 }
19861987fn fatal(&self, msg: &str) {
1988drop(self.sender.send(SharedEmitterMessage::Fatal(msg.to_string())));
1989 }
1990}
19911992impl Emitterfor SharedEmitter {
1993fn emit_diagnostic(&mut self, mut diag: rustc_errors::DiagInner) {
1994// Check that we aren't missing anything interesting when converting to
1995 // the cut-down local `DiagInner`.
1996if !!diag.span.has_span_labels() {
::core::panicking::panic("assertion failed: !diag.span.has_span_labels()")
};assert!(!diag.span.has_span_labels());
1997{
match (&diag.suggestions, &Suggestions::Enabled(::alloc::vec::Vec::new()))
{
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(diag.suggestions, Suggestions::Enabled(vec![]));
1998{
match (&diag.is_lint, &None) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(diag.is_lint, None);
1999// No sensible check for `diag.emitted_at`.
20002001let args = mem::take(&mut diag.args);
2002drop(
2003self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
2004 span: diag.span.primary_spans().iter().map(|span| span.data()).collect::<Vec<_>>(),
2005 level: diag.level(),
2006 messages: diag.messages,
2007 code: diag.code,
2008 children: diag2009 .children
2010 .into_iter()
2011 .map(|child| Subdiagnostic { level: child.level, messages: child.messages })
2012 .collect(),
2013args,
2014 })),
2015 );
2016 }
20172018fn source_map(&self) -> Option<&SourceMap> {
2019None2020 }
2021}
20222023impl SharedEmitterMain {
2024fn check(&self, sess: &Session, blocking: bool) {
2025loop {
2026let message = if blocking {
2027match self.receiver.recv() {
2028Ok(message) => Ok(message),
2029Err(_) => Err(()),
2030 }
2031 } else {
2032match self.receiver.try_recv() {
2033Ok(message) => Ok(message),
2034Err(_) => Err(()),
2035 }
2036 };
20372038match message {
2039Ok(SharedEmitterMessage::Diagnostic(diag)) => {
2040// The diagnostic has been received on the main thread.
2041 // Convert it back to a full `Diagnostic` and emit.
2042let dcx = sess.dcx();
2043let mut d =
2044 rustc_errors::DiagInner::new_with_messages(diag.level, diag.messages);
2045d.span = MultiSpan::from_spans(
2046diag.span.into_iter().map(|span| span.span()).collect(),
2047 );
2048d.code = diag.code; // may be `None`, that's ok
2049d.children = diag2050 .children
2051 .into_iter()
2052 .map(|sub| rustc_errors::Subdiag {
2053 level: sub.level,
2054 messages: sub.messages,
2055 span: MultiSpan::new(),
2056 })
2057 .collect();
2058d.args = diag.args;
2059dcx.emit_diagnostic(d);
2060sess.dcx().abort_if_errors();
2061 }
2062Ok(SharedEmitterMessage::InlineAsmError(inner)) => {
2063{
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);
2064let mut err = Diag::new(sess.dcx(), inner.level, inner.msg);
2065if !inner.span.is_dummy() {
2066err.span(inner.span.span());
2067 }
20682069// Point to the generated assembly if it is available.
2070if let Some((buffer, spans)) = inner.source {
2071let source = sess2072 .source_map()
2073 .new_source_file(FileName::inline_asm_source_code(&buffer), buffer);
2074let spans: Vec<_> = spans2075 .iter()
2076 .map(|sp| {
2077Span::with_root_ctxt(
2078source.normalized_byte_pos(sp.start as u32),
2079source.normalized_byte_pos(sp.end as u32),
2080 )
2081 })
2082 .collect();
2083err.span_note(spans, "instantiated into assembly here");
2084 }
20852086err.emit();
2087 }
2088Ok(SharedEmitterMessage::Fatal(msg)) => {
2089sess.dcx().fatal(msg);
2090 }
2091Err(_) => {
2092break;
2093 }
2094 }
2095 }
2096 }
2097}
20982099pub struct Coordinator<B: WriteBackendMethods> {
2100 sender: Sender<Message<B>>,
2101 future: Option<thread::JoinHandle<Result<MaybeLtoModules<B>, ()>>>,
2102// Only used for the Message type.
2103phantom: PhantomData<B>,
2104}
21052106impl<B: WriteBackendMethods> Coordinator<B> {
2107fn join(mut self) -> std::thread::Result<Result<MaybeLtoModules<B>, ()>> {
2108self.future.take().unwrap().join()
2109 }
2110}
21112112impl<B: WriteBackendMethods> Dropfor Coordinator<B> {
2113fn drop(&mut self) {
2114if let Some(future) = self.future.take() {
2115// If we haven't joined yet, signal to the coordinator that it should spawn no more
2116 // work, and wait for worker threads to finish.
2117drop(self.sender.send(Message::CodegenAborted::<B>));
2118drop(future.join());
2119 }
2120 }
2121}
21222123pub struct OngoingCodegen<B: WriteBackendMethods> {
2124 backend: B,
2125 output_filenames: Arc<OutputFilenames>,
2126// Field order below is intended to terminate the coordinator thread before two fields below
2127 // drop and prematurely close channels used by coordinator thread. See `Coordinator`'s
2128 // `Drop` implementation for more info.
2129pub(crate) coordinator: Coordinator<B>,
2130 codegen_worker_receive: Receiver<CguMessage>,
2131 shared_emitter_main: SharedEmitterMain,
2132}
21332134impl<B: WriteBackendMethods> OngoingCodegen<B> {
2135pub fn join(
2136self,
2137 sess: &Session,
2138 incr_comp_session: Option<&IncrCompSession>,
2139 crate_info: &CrateInfo,
2140 ) -> (CompiledModules, WorkProductMap) {
2141self.shared_emitter_main.check(sess, true);
21422143let maybe_lto_modules = sess.time("join_worker_thread", || match self.coordinator.join() {
2144Ok(Ok(maybe_lto_modules)) => maybe_lto_modules,
2145Ok(Err(())) => {
2146sess.dcx().abort_if_errors();
2147{
::core::panicking::panic_fmt(format_args!("expected abort due to worker thread errors"));
}panic!("expected abort due to worker thread errors")2148 }
2149Err(_) => {
2150::rustc_span::macros::bug_impl(None,
format_args!("panic during codegen/LLVM phase"), Location::caller());bug!("panic during codegen/LLVM phase");
2151 }
2152 });
21532154sess.dcx().abort_if_errors();
21552156let (shared_emitter, shared_emitter_main) = SharedEmitter::new();
21572158// Catch fatal errors to ensure shared_emitter_main.check() can emit the actual diagnostics
2159let compiled_modules = catch_fatal_errors(|| match maybe_lto_modules {
2160 MaybeLtoModules::NoLto(compiled_modules) => {
2161drop(shared_emitter);
2162compiled_modules2163 }
2164 MaybeLtoModules::FatLto { cgcx, needs_fat_lto } => {
2165let tm_factory = self.backend.target_machine_factory(sess, cgcx.opt_level);
21662167CompiledModules {
2168 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(
2169 sess,
2170&cgcx,
2171 shared_emitter,
2172 tm_factory,
2173&crate_info.exported_symbols_for_lto,
2174&crate_info.each_linked_rlib_file_for_lto,
2175 needs_fat_lto,
2176 )],
2177 allocator_module: None,
2178 }
2179 }
2180 MaybeLtoModules::ThinLto { cgcx, needs_thin_lto } => {
2181let tm_factory = self.backend.target_machine_factory(sess, cgcx.opt_level);
21822183CompiledModules {
2184 modules: do_thin_lto::<B>(
2185&cgcx,
2186&sess.prof,
2187shared_emitter,
2188tm_factory,
2189&crate_info.exported_symbols_for_lto,
2190&crate_info.each_linked_rlib_file_for_lto,
2191needs_thin_lto,
2192 ),
2193 allocator_module: None,
2194 }
2195 }
2196 });
21972198shared_emitter_main.check(sess, true);
21992200sess.dcx().abort_if_errors();
22012202let mut compiled_modules =
2203compiled_modules.expect("fatal error emitted but not sent to SharedEmitter");
22042205// Regardless of what order these modules completed in, report them to
2206 // the backend in the same order every time to ensure that we're handing
2207 // out deterministic results.
2208compiled_modules.modules.sort_by(|a, b| a.name.cmp(&b.name));
22092210let work_products = copy_all_cgu_workproducts_to_incr_comp_cache_dir(
2211sess,
2212incr_comp_session,
2213&compiled_modules,
2214 );
2215produce_final_output_artifacts(sess, &compiled_modules, &self.output_filenames);
22162217 (compiled_modules, work_products)
2218 }
22192220pub(crate) fn codegen_finished(&self, tcx: TyCtxt<'_>) {
2221self.wait_for_signal_to_codegen_item();
2222self.check_for_errors(tcx.sess);
2223drop(self.coordinator.sender.send(Message::CodegenComplete::<B>));
2224 }
22252226pub(crate) fn check_for_errors(&self, sess: &Session) {
2227self.shared_emitter_main.check(sess, false);
2228 }
22292230pub(crate) fn wait_for_signal_to_codegen_item(&self) {
2231match self.codegen_worker_receive.recv() {
2232Ok(CguMessage) => {
2233// Ok to proceed.
2234}
2235Err(_) => {
2236// One of the LLVM threads must have panicked, fall through so
2237 // error handling can be reached.
2238}
2239 }
2240 }
2241}
22422243pub(crate) fn submit_codegened_module_to_llvm<B: WriteBackendMethods>(
2244 coordinator: &Coordinator<B>,
2245 module: ModuleCodegen<B::Module>,
2246 cost: u64,
2247) {
2248let llvm_work_item = WorkItem::Optimize(module);
2249drop(coordinator.sender.send(Message::CodegenDone::<B> { llvm_work_item, cost }));
2250}
22512252pub(crate) fn submit_post_lto_module_to_llvm<B: WriteBackendMethods>(
2253 coordinator: &Coordinator<B>,
2254 module: CachedModuleCodegen,
2255) {
2256let llvm_work_item = WorkItem::CopyPostLtoArtifacts(module);
2257drop(coordinator.sender.send(Message::CodegenDone::<B> { llvm_work_item, cost: 0 }));
2258}
22592260pub(crate) fn submit_pre_lto_module_to_llvm<B: WriteBackendMethods>(
2261 tcx: TyCtxt<'_>,
2262 coordinator: &Coordinator<B>,
2263 module: CachedModuleCodegen,
2264) {
2265let filename = pre_lto_bitcode_filename(&module.name);
2266let old_bitcode_path =
2267in_old_incr_comp_dir_sess(tcx.incr_comp_session.unwrap(), &filename).unwrap();
2268let bitcode_path = in_incr_comp_dir_sess(tcx.incr_comp_session.unwrap(), &filename);
22692270match link_or_copy(&old_bitcode_path, &bitcode_path) {
2271Ok(_) => {}
2272Err(error) => {
2273tcx.sess.dcx().emit_err(diagnostics::CopyPathBuf {
2274 source_file: old_bitcode_path,
2275 output_path: bitcode_path,
2276error,
2277 });
2278return;
2279 }
2280 }
22812282// Schedule the module to be loaded
2283drop(
2284coordinator2285 .sender
2286 .send(Message::AddImportOnlyModule::<B> { bitcode_path, work_product: module.source }),
2287 );
2288}
22892290fn pre_lto_bitcode_filename(module_name: &str) -> String {
2291::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}.{1}", module_name,
PRE_LTO_BC_EXT))
})format!("{module_name}.{PRE_LTO_BC_EXT}")2292}
22932294fn msvc_imps_needed(tcx: TyCtxt<'_>) -> bool {
2295// This should never be true (because it's not supported). If it is true,
2296 // something is wrong with commandline arg validation.
2297if !!(tcx.sess.opts.cg.linker_plugin_lto.enabled() &&
tcx.sess.target.is_like_windows &&
tcx.sess.opts.cg.prefer_dynamic) {
::core::panicking::panic("assertion failed: !(tcx.sess.opts.cg.linker_plugin_lto.enabled() &&\n tcx.sess.target.is_like_windows &&\n tcx.sess.opts.cg.prefer_dynamic)")
};assert!(
2298 !(tcx.sess.opts.cg.linker_plugin_lto.enabled()
2299 && tcx.sess.target.is_like_windows
2300 && tcx.sess.opts.cg.prefer_dynamic)
2301 );
23022303// We need to generate _imp__ symbol if we are generating an rlib or we include one
2304 // indirectly from ThinLTO. In theory these are not needed as ThinLTO could resolve
2305 // these, but it currently does not do so.
2306let can_have_static_objects =
2307tcx.sess.lto() == Lto::Thin || tcx.crate_types().contains(&CrateType::Rlib);
23082309tcx.sess.target.is_like_windows &&
2310can_have_static_objects &&
2311// ThinLTO can't handle this workaround in all cases, so we don't
2312 // emit the `__imp_` symbols. Instead we make them unnecessary by disallowing
2313 // dynamic linking when linker plugin LTO is enabled.
2314!tcx.sess.opts.cg.linker_plugin_lto.enabled()
2315}