1use std::marker::PhantomData;
2use std::panic::AssertUnwindSafe;
3use std::path::{Path, PathBuf};
4use std::sync::Arc;
5use std::sync::mpsc::{Receiver, Sender, channel};
6use std::{assert_matches, fs, io, mem, str, thread};
78use rustc_abi::Size;
9use rustc_data_structures::jobserver::{self, Acquired};
10use rustc_data_structures::profiling::{SelfProfilerRef, VerboseTimingGuard};
11use rustc_errors::emitter::Emitter;
12use rustc_errors::{
13Diag, DiagArgMap, DiagCtxt, DiagCtxtHandle, DiagMessage, ErrCode, FatalError, FatalErrorMarker,
14Level, MultiSpan, Style, Suggestions, catch_fatal_errors,
15};
16use rustc_fs_util::link_or_copy;
17use rustc_hir::find_attr;
18use rustc_incremental::{copy_cgu_workproduct_to_incr_comp_cache_dir, in_incr_comp_dir_sess};
19use rustc_macros::{Decodable, Encodable};
20use rustc_metadata::fs::copy_to_stdout;
21use rustc_middle::bug;
22use rustc_middle::dep_graph::{WorkProduct, WorkProductMap};
23use rustc_middle::ty::TyCtxt;
24use rustc_session::Session;
25use rustc_session::config::{
26self, CrateType, Lto, OptLevel, OutFileName, OutputFilenames, OutputType, Passes,
27SwitchWithOptPath,
28};
29use rustc_span::source_map::SourceMap;
30use rustc_span::{FileName, InnerSpan, Span, SpanData};
31use rustc_target::spec::{MergeFunctions, SanitizerSet};
32use tracing::debug;
3334use crate::back::link::ensure_removed;
35use crate::back::lto::{self, SerializedModule, check_lto_allowed};
36use crate::errors::ErrorCreatingRemarkDir;
37use crate::traits::*;
38use crate::{
39CachedModuleCodegen, CompiledModule, CompiledModules, CrateInfo, ModuleCodegen, ModuleKind,
40errors,
41};
4243const PRE_LTO_BC_EXT: &str = "pre-lto.bc";
4445/// What kind of object file to emit.
46#[derive(#[automatically_derived]
impl ::core::clone::Clone for EmitObj {
#[inline]
fn clone(&self) -> EmitObj {
let _: ::core::clone::AssertParamIsClone<BitcodeSection>;
*self
}
}Clone, #[automatically_derived]
impl ::core::marker::Copy for EmitObj { }Copy, #[automatically_derived]
impl ::core::cmp::PartialEq for EmitObj {
#[inline]
fn eq(&self, other: &EmitObj) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr &&
match (self, other) {
(EmitObj::ObjectCode(__self_0), EmitObj::ObjectCode(__arg1_0))
=> __self_0 == __arg1_0,
_ => true,
}
}
}PartialEq, const _: () =
{
impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
for EmitObj {
fn encode(&self, __encoder: &mut __E) {
let disc =
match *self {
EmitObj::None => { 0usize }
EmitObj::Bitcode => { 1usize }
EmitObj::ObjectCode(ref __binding_0) => { 2usize }
};
::rustc_serialize::Encoder::emit_u8(__encoder, disc as u8);
match *self {
EmitObj::None => {}
EmitObj::Bitcode => {}
EmitObj::ObjectCode(ref __binding_0) => {
::rustc_serialize::Encodable::<__E>::encode(__binding_0,
__encoder);
}
}
}
}
};Encodable, const _: () =
{
impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
for EmitObj {
fn decode(__decoder: &mut __D) -> Self {
match ::rustc_serialize::Decoder::read_u8(__decoder) as usize
{
0usize => { EmitObj::None }
1usize => { EmitObj::Bitcode }
2usize => {
EmitObj::ObjectCode(::rustc_serialize::Decodable::decode(__decoder))
}
n => {
::core::panicking::panic_fmt(format_args!("invalid enum variant tag while decoding `EmitObj`, expected 0..3, actual {0}",
n));
}
}
}
}
};Decodable)]
47pub enum EmitObj {
48// No object file.
49None,
5051// Just uncompressed llvm bitcode. Provides easy compatibility with
52 // emscripten's ecc compiler, when used as the linker.
53Bitcode,
5455// Object code, possibly augmented with a bitcode section.
56ObjectCode(BitcodeSection),
57}
5859/// What kind of llvm bitcode section to embed in an object file.
60#[derive(#[automatically_derived]
impl ::core::clone::Clone for BitcodeSection {
#[inline]
fn clone(&self) -> BitcodeSection { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for BitcodeSection { }Copy, #[automatically_derived]
impl ::core::cmp::PartialEq for BitcodeSection {
#[inline]
fn eq(&self, other: &BitcodeSection) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq, const _: () =
{
impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
for BitcodeSection {
fn encode(&self, __encoder: &mut __E) {
let disc =
match *self {
BitcodeSection::None => { 0usize }
BitcodeSection::Full => { 1usize }
};
::rustc_serialize::Encoder::emit_u8(__encoder, disc as u8);
match *self {
BitcodeSection::None => {}
BitcodeSection::Full => {}
}
}
}
};Encodable, const _: () =
{
impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
for BitcodeSection {
fn decode(__decoder: &mut __D) -> Self {
match ::rustc_serialize::Decoder::read_u8(__decoder) as usize
{
0usize => { BitcodeSection::None }
1usize => { BitcodeSection::Full }
n => {
::core::panicking::panic_fmt(format_args!("invalid enum variant tag while decoding `BitcodeSection`, expected 0..2, actual {0}",
n));
}
}
}
}
};Decodable)]
61pub enum BitcodeSection {
62// No bitcode section.
63None,
6465// A full, uncompressed bitcode section.
66Full,
67}
6869/// Module-specific configuration for `optimize_and_codegen`.
70#[derive(const _: () =
{
impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
for ModuleConfig {
fn encode(&self, __encoder: &mut __E) {
match *self {
ModuleConfig {
passes: ref __binding_0,
opt_level: ref __binding_1,
pgo_gen: ref __binding_2,
pgo_use: ref __binding_3,
pgo_sample_use: ref __binding_4,
debug_info_for_profiling: ref __binding_5,
instrument_coverage: ref __binding_6,
sanitizer: ref __binding_7,
sanitizer_recover: ref __binding_8,
sanitizer_dataflow_abilist: ref __binding_9,
sanitizer_memory_track_origins: ref __binding_10,
emit_pre_lto_bc: ref __binding_11,
emit_bc: ref __binding_12,
emit_ir: ref __binding_13,
emit_asm: ref __binding_14,
emit_obj: ref __binding_15,
emit_thin_lto_summary: ref __binding_16,
verify_llvm_ir: ref __binding_17,
lint_llvm_ir: ref __binding_18,
no_prepopulate_passes: ref __binding_19,
no_builtins: ref __binding_20,
vectorize_loop: ref __binding_21,
vectorize_slp: ref __binding_22,
merge_functions: ref __binding_23,
emit_lifetime_markers: ref __binding_24,
llvm_plugins: ref __binding_25,
autodiff: ref __binding_26,
autodiff_post_passes: ref __binding_27,
offload: ref __binding_28 } => {
::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);
}
}
}
}
};Encodable, const _: () =
{
impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
for ModuleConfig {
fn decode(__decoder: &mut __D) -> Self {
ModuleConfig {
passes: ::rustc_serialize::Decodable::decode(__decoder),
opt_level: ::rustc_serialize::Decodable::decode(__decoder),
pgo_gen: ::rustc_serialize::Decodable::decode(__decoder),
pgo_use: ::rustc_serialize::Decodable::decode(__decoder),
pgo_sample_use: ::rustc_serialize::Decodable::decode(__decoder),
debug_info_for_profiling: ::rustc_serialize::Decodable::decode(__decoder),
instrument_coverage: ::rustc_serialize::Decodable::decode(__decoder),
sanitizer: ::rustc_serialize::Decodable::decode(__decoder),
sanitizer_recover: ::rustc_serialize::Decodable::decode(__decoder),
sanitizer_dataflow_abilist: ::rustc_serialize::Decodable::decode(__decoder),
sanitizer_memory_track_origins: ::rustc_serialize::Decodable::decode(__decoder),
emit_pre_lto_bc: ::rustc_serialize::Decodable::decode(__decoder),
emit_bc: ::rustc_serialize::Decodable::decode(__decoder),
emit_ir: ::rustc_serialize::Decodable::decode(__decoder),
emit_asm: ::rustc_serialize::Decodable::decode(__decoder),
emit_obj: ::rustc_serialize::Decodable::decode(__decoder),
emit_thin_lto_summary: ::rustc_serialize::Decodable::decode(__decoder),
verify_llvm_ir: ::rustc_serialize::Decodable::decode(__decoder),
lint_llvm_ir: ::rustc_serialize::Decodable::decode(__decoder),
no_prepopulate_passes: ::rustc_serialize::Decodable::decode(__decoder),
no_builtins: ::rustc_serialize::Decodable::decode(__decoder),
vectorize_loop: ::rustc_serialize::Decodable::decode(__decoder),
vectorize_slp: ::rustc_serialize::Decodable::decode(__decoder),
merge_functions: ::rustc_serialize::Decodable::decode(__decoder),
emit_lifetime_markers: ::rustc_serialize::Decodable::decode(__decoder),
llvm_plugins: ::rustc_serialize::Decodable::decode(__decoder),
autodiff: ::rustc_serialize::Decodable::decode(__decoder),
autodiff_post_passes: ::rustc_serialize::Decodable::decode(__decoder),
offload: ::rustc_serialize::Decodable::decode(__decoder),
}
}
}
};Decodable)]
71pub struct ModuleConfig {
72/// Names of additional optimization passes to run.
73pub passes: Vec<String>,
74/// Some(level) to optimize at a certain level, or None to run
75 /// absolutely no optimizations (used for the allocator module).
76pub opt_level: Option<config::OptLevel>,
7778pub pgo_gen: SwitchWithOptPath,
79pub pgo_use: Option<PathBuf>,
80pub pgo_sample_use: Option<PathBuf>,
81pub debug_info_for_profiling: bool,
82pub instrument_coverage: bool,
8384pub sanitizer: SanitizerSet,
85pub sanitizer_recover: SanitizerSet,
86pub sanitizer_dataflow_abilist: Vec<String>,
87pub sanitizer_memory_track_origins: usize,
8889// Flags indicating which outputs to produce.
90pub emit_pre_lto_bc: bool,
91pub emit_bc: bool,
92pub emit_ir: bool,
93pub emit_asm: bool,
94pub emit_obj: EmitObj,
95pub emit_thin_lto_summary: bool,
9697// Miscellaneous flags. These are mostly copied from command-line
98 // options.
99pub verify_llvm_ir: bool,
100pub lint_llvm_ir: bool,
101pub no_prepopulate_passes: bool,
102pub no_builtins: bool,
103pub vectorize_loop: bool,
104pub vectorize_slp: bool,
105pub merge_functions: bool,
106pub emit_lifetime_markers: bool,
107pub llvm_plugins: Vec<String>,
108pub autodiff: Vec<config::AutoDiff>,
109pub autodiff_post_passes: Option<String>,
110pub offload: Vec<config::Offload>,
111}
112113impl ModuleConfig {
114fn new(kind: ModuleKind, tcx: TyCtxt<'_>, no_builtins: bool) -> ModuleConfig {
115// If it's a regular module, use `$regular`, otherwise use `$other`.
116 // `$regular` and `$other` are evaluated lazily.
117macro_rules! if_regular {
118 ($regular: expr, $other: expr) => {
119if let ModuleKind::Regular = kind { $regular } else { $other }
120 };
121 }
122123let sess = tcx.sess;
124let opt_level_and_size = if let ModuleKind::Regular = kind { Some(sess.opts.optimize) } else { None }if_regular!(Some(sess.opts.optimize), None);
125126let save_temps = sess.opts.cg.save_temps;
127128let should_emit_obj = sess.opts.output_types.contains_key(&OutputType::Exe)
129 || match kind {
130 ModuleKind::Regular => sess.opts.output_types.contains_key(&OutputType::Object),
131 ModuleKind::Allocator => false,
132 };
133134let emit_obj = if !should_emit_obj {
135 EmitObj::None136 } else if sess.target.obj_is_bitcode
137 || (sess.opts.cg.linker_plugin_lto.enabled()
138 && (!no_builtins || tcx.sess.is_sanitizer_cfi_enabled()))
139 {
140// This case is selected if the target uses objects as bitcode, or
141 // if linker plugin LTO is enabled. In the linker plugin LTO case
142 // the assumption is that the final link-step will read the bitcode
143 // and convert it to object code. This may be done by either the
144 // native linker or rustc itself.
145 //
146 // By default this branch is skipped for `#![no_builtins]` crates so
147 // they emit native object files (machine code), not LLVM bitcode
148 // objects for the linker (see rust-lang/rust#146133).
149 //
150 // However, when LLVM CFI is enabled (`-Zsanitizer=cfi`), this
151 // breaks LLVM's expected pipeline: LLVM emits `llvm.type.test`
152 // intrinsics and related metadata that must be lowered by LLVM's
153 // `LowerTypeTests` pass before instruction selection during
154 // link-time LTO. Otherwise, `llvm.type.test` intrinsics and related
155 // metadata are not lowered by LLVM's `LowerTypeTests` pass before
156 // reaching the target backend, and LLVM may abort during codegen
157 // (for example in SelectionDAG type legalization) (see
158 // rust-lang/rust#142284).
159 //
160 // Therefore, with `-Clinker-plugin-lto` and `-Zsanitizer=cfi`, a
161 // `#![no_builtins]` crate must still use rustc's `EmitObj::Bitcode`
162 // path (and emit LLVM bitcode in the `.o` for linker-based LTO).
163EmitObj::Bitcode164 } else if need_bitcode_in_object(tcx) || sess.target.requires_lto {
165 EmitObj::ObjectCode(BitcodeSection::Full)
166 } else {
167 EmitObj::ObjectCode(BitcodeSection::None)
168 };
169170ModuleConfig {
171 passes: if let ModuleKind::Regular = kind {
sess.opts.cg.passes.clone()
} else { ::alloc::vec::Vec::new() }if_regular!(sess.opts.cg.passes.clone(), vec![]),
172173 opt_level: opt_level_and_size,
174175 pgo_gen: if let ModuleKind::Regular = kind {
sess.opts.cg.profile_generate.clone()
} else { SwitchWithOptPath::Disabled }if_regular!(
176 sess.opts.cg.profile_generate.clone(),
177 SwitchWithOptPath::Disabled
178 ),
179 pgo_use: if let ModuleKind::Regular = kind {
sess.opts.cg.profile_use.clone()
} else { None }if_regular!(sess.opts.cg.profile_use.clone(), None),
180 pgo_sample_use: if let ModuleKind::Regular = kind {
sess.opts.unstable_opts.profile_sample_use.clone()
} else { None }if_regular!(sess.opts.unstable_opts.profile_sample_use.clone(), None),
181 debug_info_for_profiling: sess.opts.unstable_opts.debuginfo_for_profiling,
182 instrument_coverage: if let ModuleKind::Regular = kind {
sess.instrument_coverage()
} else { false }if_regular!(sess.instrument_coverage(), false),
183184 sanitizer: if let ModuleKind::Regular = kind {
sess.sanitizers()
} else { SanitizerSet::empty() }if_regular!(sess.sanitizers(), SanitizerSet::empty()),
185 sanitizer_dataflow_abilist: if let ModuleKind::Regular = kind {
sess.opts.unstable_opts.sanitizer_dataflow_abilist.clone()
} else { Vec::new() }if_regular!(
186 sess.opts.unstable_opts.sanitizer_dataflow_abilist.clone(),
187 Vec::new()
188 ),
189 sanitizer_recover: if let ModuleKind::Regular = kind {
sess.opts.unstable_opts.sanitizer_recover
} else { SanitizerSet::empty() }if_regular!(
190 sess.opts.unstable_opts.sanitizer_recover,
191 SanitizerSet::empty()
192 ),
193 sanitizer_memory_track_origins: if let ModuleKind::Regular = kind {
sess.opts.unstable_opts.sanitizer_memory_track_origins
} else { 0 }if_regular!(
194 sess.opts.unstable_opts.sanitizer_memory_track_origins,
1950
196),
197198 emit_pre_lto_bc: if let ModuleKind::Regular = kind {
save_temps || need_pre_lto_bitcode_for_incr_comp(sess)
} else { false }if_regular!(
199 save_temps || need_pre_lto_bitcode_for_incr_comp(sess),
200false
201),
202 emit_bc: if let ModuleKind::Regular = kind {
save_temps || sess.opts.output_types.contains_key(&OutputType::Bitcode)
} else { save_temps }if_regular!(
203 save_temps || sess.opts.output_types.contains_key(&OutputType::Bitcode),
204 save_temps
205 ),
206 emit_ir: if let ModuleKind::Regular = kind {
sess.opts.output_types.contains_key(&OutputType::LlvmAssembly)
} else { false }if_regular!(
207 sess.opts.output_types.contains_key(&OutputType::LlvmAssembly),
208false
209),
210 emit_asm: if let ModuleKind::Regular = kind {
sess.opts.output_types.contains_key(&OutputType::Assembly)
} else { false }if_regular!(
211 sess.opts.output_types.contains_key(&OutputType::Assembly),
212false
213),
214emit_obj,
215 emit_thin_lto_summary: if let ModuleKind::Regular = kind {
sess.opts.output_types.contains_key(&OutputType::ThinLinkBitcode)
} else { false }if_regular!(
216 sess.opts.output_types.contains_key(&OutputType::ThinLinkBitcode),
217false
218),
219220 verify_llvm_ir: sess.verify_llvm_ir(),
221 lint_llvm_ir: sess.opts.unstable_opts.lint_llvm_ir,
222 no_prepopulate_passes: sess.opts.cg.no_prepopulate_passes,
223 no_builtins: no_builtins || sess.target.no_builtins,
224225// Copy what clang does by turning on loop vectorization at O2 and
226 // slp vectorization at O3.
227vectorize_loop: !sess.opts.cg.no_vectorize_loops
228 && (sess.opts.optimize == config::OptLevel::More229 || sess.opts.optimize == config::OptLevel::Aggressive),
230 vectorize_slp: !sess.opts.cg.no_vectorize_slp
231 && sess.opts.optimize == config::OptLevel::Aggressive,
232233// Some targets (namely, NVPTX) interact badly with the
234 // MergeFunctions pass. This is because MergeFunctions can generate
235 // new function calls which may interfere with the target calling
236 // convention; e.g. for the NVPTX target, PTX kernels should not
237 // call other PTX kernels. MergeFunctions can also be configured to
238 // generate aliases instead, but aliases are not supported by some
239 // backends (again, NVPTX). Therefore, allow targets to opt out of
240 // the MergeFunctions pass, but otherwise keep the pass enabled (at
241 // O2 and O3) since it can be useful for reducing code size.
242merge_functions: match sess243 .opts
244 .unstable_opts
245 .merge_functions
246 .unwrap_or(sess.target.merge_functions)
247 {
248 MergeFunctions::Disabled => false,
249 MergeFunctions::Trampolines | MergeFunctions::Aliases => {
250use config::OptLevel::*;
251match sess.opts.optimize {
252Aggressive | More | SizeMin | Size => true,
253Less | No => false,
254 }
255 }
256 },
257258 emit_lifetime_markers: sess.emit_lifetime_markers(),
259 llvm_plugins: if let ModuleKind::Regular = kind {
sess.opts.unstable_opts.llvm_plugins.clone()
} else { ::alloc::vec::Vec::new() }if_regular!(sess.opts.unstable_opts.llvm_plugins.clone(), vec![]),
260 autodiff: if let ModuleKind::Regular = kind {
sess.opts.unstable_opts.autodiff.clone()
} else { ::alloc::vec::Vec::new() }if_regular!(sess.opts.unstable_opts.autodiff.clone(), vec![]),
261 autodiff_post_passes: if let ModuleKind::Regular = kind {
sess.opts.unstable_opts.autodiff_post_passes.clone()
} else { None }if_regular!(
262 sess.opts.unstable_opts.autodiff_post_passes.clone(),
263None
264),
265 offload: if let ModuleKind::Regular = kind {
sess.opts.unstable_opts.offload.clone()
} else { ::alloc::vec::Vec::new() }if_regular!(sess.opts.unstable_opts.offload.clone(), vec![]),
266 }
267 }
268269pub fn bitcode_needed(&self) -> bool {
270self.emit_bc
271 || self.emit_thin_lto_summary
272 || self.emit_obj == EmitObj::Bitcode273 || self.emit_obj == EmitObj::ObjectCode(BitcodeSection::Full)
274 }
275276pub fn embed_bitcode(&self) -> bool {
277self.emit_obj == EmitObj::ObjectCode(BitcodeSection::Full)
278 }
279}
280281/// Configuration passed to the function returned by the `target_machine_factory`.
282pub struct TargetMachineFactoryConfig {
283/// Split DWARF is enabled in LLVM by checking that `TM.MCOptions.SplitDwarfFile` isn't empty,
284 /// so the path to the dwarf object has to be provided when we create the target machine.
285 /// This can be ignored by backends which do not need it for their Split DWARF support.
286pub split_dwarf_file: Option<PathBuf>,
287288/// The name of the output object file. Used for setting OutputFilenames in target options
289 /// so that LLVM can emit the CodeView S_OBJNAME record in pdb files
290pub output_obj_file: Option<PathBuf>,
291}
292293impl TargetMachineFactoryConfig {
294pub fn new(cgcx: &CodegenContext, module_name: &str) -> TargetMachineFactoryConfig {
295let split_dwarf_file = if cgcx.target_can_use_split_dwarf {
296cgcx.output_filenames.split_dwarf_path(
297cgcx.split_debuginfo,
298cgcx.split_dwarf_kind,
299module_name,
300 )
301 } else {
302None303 };
304305let output_obj_file =
306Some(cgcx.output_filenames.temp_path_for_cgu(OutputType::Object, module_name));
307TargetMachineFactoryConfig { split_dwarf_file, output_obj_file }
308 }
309}
310311pub type TargetMachineFactoryFn<B> = Arc<
312dyn Fn(
313DiagCtxtHandle<'_>,
314TargetMachineFactoryConfig,
315 ) -> <B as WriteBackendMethods>::TargetMachine316 + Send317 + Sync,
318>;
319320/// Additional resources used by optimize_and_codegen (not module specific)
321#[derive(#[automatically_derived]
impl ::core::clone::Clone for CodegenContext {
#[inline]
fn clone(&self) -> CodegenContext {
CodegenContext {
lto: ::core::clone::Clone::clone(&self.lto),
use_linker_plugin_lto: ::core::clone::Clone::clone(&self.use_linker_plugin_lto),
dylib_lto: ::core::clone::Clone::clone(&self.dylib_lto),
prefer_dynamic: ::core::clone::Clone::clone(&self.prefer_dynamic),
save_temps: ::core::clone::Clone::clone(&self.save_temps),
fewer_names: ::core::clone::Clone::clone(&self.fewer_names),
time_trace: ::core::clone::Clone::clone(&self.time_trace),
crate_types: ::core::clone::Clone::clone(&self.crate_types),
output_filenames: ::core::clone::Clone::clone(&self.output_filenames),
module_config: ::core::clone::Clone::clone(&self.module_config),
opt_level: ::core::clone::Clone::clone(&self.opt_level),
backend_features: ::core::clone::Clone::clone(&self.backend_features),
msvc_imps_needed: ::core::clone::Clone::clone(&self.msvc_imps_needed),
is_pe_coff: ::core::clone::Clone::clone(&self.is_pe_coff),
target_can_use_split_dwarf: ::core::clone::Clone::clone(&self.target_can_use_split_dwarf),
target_arch: ::core::clone::Clone::clone(&self.target_arch),
target_is_like_darwin: ::core::clone::Clone::clone(&self.target_is_like_darwin),
target_is_like_aix: ::core::clone::Clone::clone(&self.target_is_like_aix),
target_is_like_gpu: ::core::clone::Clone::clone(&self.target_is_like_gpu),
split_debuginfo: ::core::clone::Clone::clone(&self.split_debuginfo),
split_dwarf_kind: ::core::clone::Clone::clone(&self.split_dwarf_kind),
pointer_size: ::core::clone::Clone::clone(&self.pointer_size),
remark: ::core::clone::Clone::clone(&self.remark),
remark_dir: ::core::clone::Clone::clone(&self.remark_dir),
incr_comp_session_dir: ::core::clone::Clone::clone(&self.incr_comp_session_dir),
parallel: ::core::clone::Clone::clone(&self.parallel),
}
}
}Clone, const _: () =
{
impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
for CodegenContext {
fn encode(&self, __encoder: &mut __E) {
match *self {
CodegenContext {
lto: ref __binding_0,
use_linker_plugin_lto: ref __binding_1,
dylib_lto: ref __binding_2,
prefer_dynamic: ref __binding_3,
save_temps: ref __binding_4,
fewer_names: ref __binding_5,
time_trace: ref __binding_6,
crate_types: ref __binding_7,
output_filenames: ref __binding_8,
module_config: ref __binding_9,
opt_level: ref __binding_10,
backend_features: ref __binding_11,
msvc_imps_needed: ref __binding_12,
is_pe_coff: ref __binding_13,
target_can_use_split_dwarf: ref __binding_14,
target_arch: ref __binding_15,
target_is_like_darwin: ref __binding_16,
target_is_like_aix: ref __binding_17,
target_is_like_gpu: ref __binding_18,
split_debuginfo: ref __binding_19,
split_dwarf_kind: ref __binding_20,
pointer_size: ref __binding_21,
remark: ref __binding_22,
remark_dir: ref __binding_23,
incr_comp_session_dir: ref __binding_24,
parallel: ref __binding_25 } => {
::rustc_serialize::Encodable::<__E>::encode(__binding_0,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_1,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_2,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_3,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_4,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_5,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_6,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_7,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_8,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_9,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_10,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_11,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_12,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_13,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_14,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_15,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_16,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_17,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_18,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_19,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_20,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_21,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_22,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_23,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_24,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_25,
__encoder);
}
}
}
}
};Encodable, const _: () =
{
impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
for CodegenContext {
fn decode(__decoder: &mut __D) -> Self {
CodegenContext {
lto: ::rustc_serialize::Decodable::decode(__decoder),
use_linker_plugin_lto: ::rustc_serialize::Decodable::decode(__decoder),
dylib_lto: ::rustc_serialize::Decodable::decode(__decoder),
prefer_dynamic: ::rustc_serialize::Decodable::decode(__decoder),
save_temps: ::rustc_serialize::Decodable::decode(__decoder),
fewer_names: ::rustc_serialize::Decodable::decode(__decoder),
time_trace: ::rustc_serialize::Decodable::decode(__decoder),
crate_types: ::rustc_serialize::Decodable::decode(__decoder),
output_filenames: ::rustc_serialize::Decodable::decode(__decoder),
module_config: ::rustc_serialize::Decodable::decode(__decoder),
opt_level: ::rustc_serialize::Decodable::decode(__decoder),
backend_features: ::rustc_serialize::Decodable::decode(__decoder),
msvc_imps_needed: ::rustc_serialize::Decodable::decode(__decoder),
is_pe_coff: ::rustc_serialize::Decodable::decode(__decoder),
target_can_use_split_dwarf: ::rustc_serialize::Decodable::decode(__decoder),
target_arch: ::rustc_serialize::Decodable::decode(__decoder),
target_is_like_darwin: ::rustc_serialize::Decodable::decode(__decoder),
target_is_like_aix: ::rustc_serialize::Decodable::decode(__decoder),
target_is_like_gpu: ::rustc_serialize::Decodable::decode(__decoder),
split_debuginfo: ::rustc_serialize::Decodable::decode(__decoder),
split_dwarf_kind: ::rustc_serialize::Decodable::decode(__decoder),
pointer_size: ::rustc_serialize::Decodable::decode(__decoder),
remark: ::rustc_serialize::Decodable::decode(__decoder),
remark_dir: ::rustc_serialize::Decodable::decode(__decoder),
incr_comp_session_dir: ::rustc_serialize::Decodable::decode(__decoder),
parallel: ::rustc_serialize::Decodable::decode(__decoder),
}
}
}
};Decodable)]
322pub struct CodegenContext {
323// Resources needed when running LTO
324pub lto: Lto,
325pub use_linker_plugin_lto: bool,
326pub dylib_lto: bool,
327pub prefer_dynamic: bool,
328pub save_temps: bool,
329pub fewer_names: bool,
330pub time_trace: bool,
331pub crate_types: Vec<CrateType>,
332pub output_filenames: Arc<OutputFilenames>,
333pub module_config: Arc<ModuleConfig>,
334pub opt_level: OptLevel,
335pub backend_features: Vec<String>,
336pub msvc_imps_needed: bool,
337pub is_pe_coff: bool,
338pub target_can_use_split_dwarf: bool,
339pub target_arch: String,
340pub target_is_like_darwin: bool,
341pub target_is_like_aix: bool,
342pub target_is_like_gpu: bool,
343pub split_debuginfo: rustc_target::spec::SplitDebuginfo,
344pub split_dwarf_kind: rustc_session::config::SplitDwarfKind,
345pub pointer_size: Size,
346347/// LLVM optimizations for which we want to print remarks.
348pub remark: Passes,
349/// Directory into which should the LLVM optimization remarks be written.
350 /// If `None`, they will be written to stderr.
351pub remark_dir: Option<PathBuf>,
352/// The incremental compilation session directory, or None if we are not
353 /// compiling incrementally
354pub incr_comp_session_dir: Option<PathBuf>,
355/// `true` if the codegen should be run in parallel.
356 ///
357 /// Depends on [`WriteBackendMethods::supports_parallel()`] and `-Zno_parallel_backend`.
358pub parallel: bool,
359}
360361fn generate_thin_lto_work<B: WriteBackendMethods>(
362 cgcx: &CodegenContext,
363 prof: &SelfProfilerRef,
364 dcx: DiagCtxtHandle<'_>,
365 exported_symbols_for_lto: &[String],
366 each_linked_rlib_for_lto: &[PathBuf],
367 needs_thin_lto: Vec<ThinLtoInput<B>>,
368) -> Vec<(ThinLtoWorkItem<B>, u64)> {
369let _prof_timer = prof.generic_activity("codegen_thin_generate_lto_work");
370371let (lto_modules, copy_jobs) = B::run_thin_lto(
372cgcx,
373prof,
374dcx,
375exported_symbols_for_lto,
376each_linked_rlib_for_lto,
377needs_thin_lto,
378 );
379lto_modules380 .into_iter()
381 .map(|module| {
382let cost = module.cost();
383 (ThinLtoWorkItem::ThinLto(module), cost)
384 })
385 .chain(copy_jobs.into_iter().map(|wp| {
386 (
387 ThinLtoWorkItem::CopyPostLtoArtifacts(CachedModuleCodegen {
388 name: wp.cgu_name.clone(),
389 source: wp,
390 }),
3910, // copying is very cheap
392)
393 }))
394 .collect()
395}
396397enum MaybeLtoModules<B: WriteBackendMethods> {
398 NoLto(CompiledModules),
399 FatLto { cgcx: CodegenContext, needs_fat_lto: Vec<FatLtoInput<B>> },
400 ThinLto { cgcx: CodegenContext, needs_thin_lto: Vec<ThinLtoInput<B>> },
401}
402403fn need_bitcode_in_object(tcx: TyCtxt<'_>) -> bool {
404let sess = tcx.sess;
405sess.opts.cg.embed_bitcode
406 && tcx.crate_types().contains(&CrateType::Rlib)
407 && sess.opts.output_types.contains_key(&OutputType::Exe)
408}
409410fn need_pre_lto_bitcode_for_incr_comp(sess: &Session) -> bool {
411if sess.opts.incremental.is_none() {
412return false;
413 }
414415match sess.lto() {
416 Lto::No => false,
417 Lto::Fat | Lto::Thin | Lto::ThinLocal => true,
418 }
419}
420421pub(crate) fn start_async_codegen<B: WriteBackendMethods>(
422 backend: B,
423 tcx: TyCtxt<'_>,
424 allocator_module: Option<ModuleCodegen<B::Module>>,
425) -> OngoingCodegen<B> {
426let (coordinator_send, coordinator_receive) = channel();
427428let no_builtins = {
'done:
{
for i in tcx.hir_krate_attrs() {
#[allow(unused_imports)]
use rustc_hir::attrs::AttributeKind::*;
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(NoBuiltins) => {
break 'done Some(());
}
rustc_hir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}.is_some()find_attr!(tcx, crate, NoBuiltins);
429430let regular_config = ModuleConfig::new(ModuleKind::Regular, tcx, no_builtins);
431let allocator_config = ModuleConfig::new(ModuleKind::Allocator, tcx, no_builtins);
432433let (shared_emitter, shared_emitter_main) = SharedEmitter::new();
434let (codegen_worker_send, codegen_worker_receive) = channel();
435436let coordinator_thread = start_executing_work(
437backend.clone(),
438tcx,
439shared_emitter,
440codegen_worker_send,
441coordinator_receive,
442Arc::new(regular_config),
443Arc::new(allocator_config),
444allocator_module,
445coordinator_send.clone(),
446 );
447448OngoingCodegen {
449backend,
450451codegen_worker_receive,
452shared_emitter_main,
453 coordinator: Coordinator {
454 sender: coordinator_send,
455 future: Some(coordinator_thread),
456 phantom: PhantomData,
457 },
458 output_filenames: Arc::clone(tcx.output_filenames(())),
459 }
460}
461462fn copy_all_cgu_workproducts_to_incr_comp_cache_dir(
463 sess: &Session,
464 compiled_modules: &CompiledModules,
465) -> WorkProductMap {
466let mut work_products = WorkProductMap::default();
467468if sess.opts.incremental.is_none() || sess.opts.unstable_opts.disable_incr_comp_backend_caching
469 {
470return work_products;
471 }
472473let _timer = sess.timer("copy_all_cgu_workproducts_to_incr_comp_cache_dir");
474475for module in compiled_modules.modules.iter().filter(|m| m.kind == ModuleKind::Regular) {
476let mut files = Vec::new();
477if let Some(object_file_path) = &module.object {
478 files.push((OutputType::Object.extension(), object_file_path.as_path()));
479 }
480if let Some(global_asm_object_file_path) = &module.global_asm_object {
481 files.push(("asm.o", global_asm_object_file_path.as_path()));
482 }
483if let Some(dwarf_object_file_path) = &module.dwarf_object {
484 files.push(("dwo", dwarf_object_file_path.as_path()));
485 }
486if let Some(path) = &module.assembly {
487 files.push((OutputType::Assembly.extension(), path.as_path()));
488 }
489if let Some(path) = &module.llvm_ir {
490 files.push((OutputType::LlvmAssembly.extension(), path.as_path()));
491 }
492if let Some(path) = &module.bytecode {
493 files.push((OutputType::Bitcode.extension(), path.as_path()));
494 }
495let (id, product) = copy_cgu_workproduct_to_incr_comp_cache_dir(
496 sess,
497&module.name,
498 files.as_slice(),
499&module.links_from_incr_cache,
500 );
501 work_products.insert(id, product);
502 }
503504work_products505}
506507pub fn produce_final_output_artifacts(
508 sess: &Session,
509 compiled_modules: &CompiledModules,
510 crate_output: &OutputFilenames,
511) {
512let mut user_wants_bitcode = false;
513let mut user_wants_objects = false;
514515// Produce final compile outputs.
516let copy_gracefully = |from: &Path, to: &OutFileName| match to {
517 OutFileName::Stdoutif let Err(e) = copy_to_stdout(from) => {
518sess.dcx().emit_err(errors::CopyPath::new(from, to.as_path(), e));
519 }
520 OutFileName::Real(path) if let Err(e) = fs::copy(from, path) => {
521sess.dcx().emit_err(errors::CopyPath::new(from, path, e));
522 }
523_ => {}
524 };
525526let copy_if_one_unit = |output_type: OutputType, keep_numbered: bool| {
527if let [module] = &compiled_modules.modules[..] {
528// 1) Only one codegen unit. In this case it's no difficulty
529 // to copy `foo.0.x` to `foo.x`.
530let path = crate_output.temp_path_for_cgu(output_type, &module.name);
531let output = crate_output.path(output_type);
532if !output_type.is_text_output() && output.is_tty() {
533sess.dcx()
534 .emit_err(errors::BinaryOutputToTty { shorthand: output_type.shorthand() });
535 } else {
536copy_gracefully(&path, &output);
537 }
538if !sess.opts.cg.save_temps && !keep_numbered {
539// The user just wants `foo.x`, not `foo.#module-name#.x`.
540ensure_removed(sess.dcx(), &path);
541 }
542 } else {
543if crate_output.outputs.contains_explicit_name(&output_type) {
544// 2) Multiple codegen units, with `--emit foo=some_name`. We have
545 // no good solution for this case, so warn the user.
546sess.dcx()
547 .emit_warn(errors::IgnoringEmitPath { extension: output_type.extension() });
548 } else if crate_output.single_output_file.is_some() {
549// 3) Multiple codegen units, with `-o some_name`. We have
550 // no good solution for this case, so warn the user.
551sess.dcx().emit_warn(errors::IgnoringOutput { extension: output_type.extension() });
552 } else {
553// 4) Multiple codegen units, but no explicit name. We
554 // just leave the `foo.0.x` files in place.
555 // (We don't have to do any work in this case.)
556}
557 }
558 };
559560// Flag to indicate whether the user explicitly requested bitcode.
561 // Otherwise, we produced it only as a temporary output, and will need
562 // to get rid of it.
563for output_type in crate_output.outputs.keys() {
564match *output_type {
565 OutputType::Bitcode => {
566 user_wants_bitcode = true;
567// Copy to .bc, but always keep the .0.bc. There is a later
568 // check to figure out if we should delete .0.bc files, or keep
569 // them for making an rlib.
570copy_if_one_unit(OutputType::Bitcode, true);
571 }
572 OutputType::ThinLinkBitcode => {
573 copy_if_one_unit(OutputType::ThinLinkBitcode, false);
574 }
575 OutputType::LlvmAssembly => {
576 copy_if_one_unit(OutputType::LlvmAssembly, false);
577 }
578 OutputType::Assembly => {
579 copy_if_one_unit(OutputType::Assembly, false);
580 }
581 OutputType::Object => {
582 user_wants_objects = true;
583 copy_if_one_unit(OutputType::Object, true);
584 }
585 OutputType::Mir | OutputType::Metadata | OutputType::Exe | OutputType::DepInfo => {}
586 }
587 }
588589// Clean up unwanted temporary files.
590591 // We create the following files by default:
592 // - #crate#.#module-name#.rcgu.bc
593 // - #crate#.#module-name#.rcgu.o
594 // - #crate#.o (linked from crate.##.rcgu.o)
595 // - #crate#.bc (copied from crate.##.rcgu.bc)
596 // We may create additional files if requested by the user (through
597 // `-C save-temps` or `--emit=` flags).
598599if !sess.opts.cg.save_temps {
600// Remove the temporary .#module-name#.rcgu.o objects. If the user didn't
601 // explicitly request bitcode (with --emit=bc), and the bitcode is not
602 // needed for building an rlib, then we must remove .#module-name#.bc as
603 // well.
604605 // Specific rules for keeping .#module-name#.rcgu.bc:
606 // - If the user requested bitcode (`user_wants_bitcode`), and
607 // codegen_units > 1, then keep it.
608 // - If the user requested bitcode but codegen_units == 1, then we
609 // can toss .#module-name#.rcgu.bc because we copied it to .bc earlier.
610 // - If we're not building an rlib and the user didn't request
611 // bitcode, then delete .#module-name#.rcgu.bc.
612 // If you change how this works, also update back::link::link_rlib,
613 // where .#module-name#.rcgu.bc files are (maybe) deleted after making an
614 // rlib.
615let needs_crate_object = crate_output.outputs.contains_key(&OutputType::Exe);
616617let keep_numbered_bitcode = user_wants_bitcode && sess.codegen_units().as_usize() > 1;
618619let keep_numbered_objects =
620needs_crate_object || (user_wants_objects && sess.codegen_units().as_usize() > 1);
621622for module in compiled_modules.modules.iter() {
623if !keep_numbered_objects {
624if let Some(ref path) = module.object {
625 ensure_removed(sess.dcx(), path);
626 }
627628if let Some(ref path) = module.global_asm_object {
629 ensure_removed(sess.dcx(), path);
630 }
631632if let Some(ref path) = module.dwarf_object {
633 ensure_removed(sess.dcx(), path);
634 }
635 }
636637if let Some(ref path) = module.bytecode {
638if !keep_numbered_bitcode {
639 ensure_removed(sess.dcx(), path);
640 }
641 }
642 }
643644if !user_wants_bitcode645 && let Some(ref allocator_module) = compiled_modules.allocator_module
646 && let Some(ref path) = allocator_module.bytecode
647 {
648ensure_removed(sess.dcx(), path);
649 }
650 }
651652if sess.opts.json_artifact_notifications {
653if let [module] = &compiled_modules.modules[..] {
654module.for_each_output(|_path, ty| {
655if sess.opts.output_types.contains_key(&ty) {
656let descr = ty.shorthand();
657// for single cgu file is renamed to drop cgu specific suffix
658 // so we regenerate it the same way
659let path = crate_output.path(ty);
660sess.dcx().emit_artifact_notification(path.as_path(), descr);
661 }
662 });
663 } else {
664for module in &compiled_modules.modules {
665 module.for_each_output(|path, ty| {
666if sess.opts.output_types.contains_key(&ty) {
667let descr = ty.shorthand();
668 sess.dcx().emit_artifact_notification(&path, descr);
669 }
670 });
671 }
672 }
673 }
674675// We leave the following files around by default:
676 // - #crate#.o
677 // - #crate#.bc
678 // These are used in linking steps and will be cleaned up afterward.
679}
680681pub(crate) enum WorkItem<B: WriteBackendMethods> {
682/// Optimize a newly codegened, totally unoptimized module.
683Optimize(ModuleCodegen<B::Module>),
684/// Copy the post-LTO artifacts from the incremental cache to the output
685 /// directory.
686CopyPostLtoArtifacts(CachedModuleCodegen),
687}
688689enum ThinLtoWorkItem<B: WriteBackendMethods> {
690/// Copy the post-LTO artifacts from the incremental cache to the output
691 /// directory.
692CopyPostLtoArtifacts(CachedModuleCodegen),
693/// Performs thin-LTO on the given module.
694ThinLto(lto::ThinModule<B>),
695}
696697// `pthread_setname()` on *nix ignores anything beyond the first 15
698// bytes. Use short descriptions to maximize the space available for
699// the module name.
700#[cfg(not(windows))]
701fn desc(short: &str, _long: &str, name: &str) -> String {
702// The short label is three bytes, and is followed by a space. That
703 // leaves 11 bytes for the CGU name. How we obtain those 11 bytes
704 // depends on the CGU name form.
705 //
706 // - Non-incremental, e.g. `regex.f10ba03eb5ec7975-cgu.0`: the part
707 // before the `-cgu.0` is the same for every CGU, so use the
708 // `cgu.0` part. The number suffix will be different for each
709 // CGU.
710 //
711 // - Incremental (normal), e.g. `2i52vvl2hco29us0`: use the whole
712 // name because each CGU will have a unique ASCII hash, and the
713 // first 11 bytes will be enough to identify it.
714 //
715 // - Incremental (with `-Zhuman-readable-cgu-names`), e.g.
716 // `regex.f10ba03eb5ec7975-re_builder.volatile`: use the whole
717 // name. The first 11 bytes won't be enough to uniquely identify
718 // it, but no obvious substring will, and this is a rarely used
719 // option so it doesn't matter much.
720 //
721{
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);
722let name = if let Some(index) = name.find("-cgu.") {
723&name[index + 1..] // +1 skips the leading '-'.
724} else {
725name726 };
727::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} {1}", short, name))
})format!("{short} {name}")728}
729730// Windows has no thread name length limit, so use more descriptive names.
731#[cfg(windows)]
732fn desc(_short: &str, long: &str, name: &str) -> String {
733format!("{long} {name}")
734}
735736impl<B: WriteBackendMethods> WorkItem<B> {
737/// Generate a short description of this work item suitable for use as a thread name.
738fn short_description(&self) -> String {
739match self {
740 WorkItem::Optimize(m) => desc("opt", "optimize module", &m.name),
741 WorkItem::CopyPostLtoArtifacts(m) => desc("cpy", "copy LTO artifacts for", &m.name),
742 }
743 }
744}
745746impl<B: WriteBackendMethods> ThinLtoWorkItem<B> {
747/// Generate a short description of this work item suitable for use as a thread name.
748fn short_description(&self) -> String {
749match self {
750 ThinLtoWorkItem::CopyPostLtoArtifacts(m) => {
751desc("cpy", "copy LTO artifacts for", &m.name)
752 }
753 ThinLtoWorkItem::ThinLto(m) => desc("lto", "thin-LTO module", m.name()),
754 }
755 }
756}
757758/// A result produced by the backend.
759pub(crate) enum WorkItemResult<B: WriteBackendMethods> {
760/// The backend has finished compiling a CGU, nothing more required.
761Finished(CompiledModule),
762763/// The backend has finished compiling a CGU, which now needs to go through
764 /// fat LTO.
765NeedsFatLto(FatLtoInput<B>),
766767/// The backend has finished compiling a CGU, which now needs to go through
768 /// thin LTO.
769NeedsThinLto(String, B::ModuleBuffer),
770}
771772pub enum FatLtoInput<B: WriteBackendMethods> {
773 Serialized { name: String, bitcode_path: PathBuf },
774 InMemory(ModuleCodegen<B::Module>),
775}
776777pub enum ThinLtoInput<B: WriteBackendMethods> {
778 Red { name: String, buffer: SerializedModule<B::ModuleBuffer> },
779 Green { wp: WorkProduct, bitcode_path: PathBuf },
780}
781782/// Actual LTO type we end up choosing based on multiple factors.
783pub(crate) enum ComputedLtoType {
784 No,
785 Thin,
786 Fat,
787}
788789pub(crate) fn compute_per_cgu_lto_type(
790 sess_lto: &Lto,
791 linker_does_lto: bool,
792 sess_crate_types: &[CrateType],
793) -> ComputedLtoType {
794// If the linker does LTO, we don't have to do it. Note that we
795 // keep doing full LTO, if it is requested, as not to break the
796 // assumption that the output will be a single module.
797798 // We ignore a request for full crate graph LTO if the crate type
799 // is only an rlib, as there is no full crate graph to process,
800 // that'll happen later.
801 //
802 // This use case currently comes up primarily for targets that
803 // require LTO so the request for LTO is always unconditionally
804 // passed down to the backend, but we don't actually want to do
805 // anything about it yet until we've got a final product.
806let is_rlib = #[allow(non_exhaustive_omitted_patterns)] match sess_crate_types {
[CrateType::Rlib] => true,
_ => false,
}matches!(sess_crate_types, [CrateType::Rlib]);
807808match sess_lto {
809 Lto::ThinLocalif !linker_does_lto => ComputedLtoType::Thin,
810 Lto::Thinif !linker_does_lto && !is_rlib => ComputedLtoType::Thin,
811 Lto::Fatif !is_rlib => ComputedLtoType::Fat,
812_ => ComputedLtoType::No,
813 }
814}
815816fn execute_optimize_work_item<B: WriteBackendMethods>(
817 cgcx: &CodegenContext,
818 prof: &SelfProfilerRef,
819 shared_emitter: SharedEmitter,
820mut module: ModuleCodegen<B::Module>,
821) -> WorkItemResult<B> {
822let _timer = prof.generic_activity_with_arg("codegen_module_optimize", &*module.name);
823824 B::optimize(cgcx, prof, &shared_emitter, &mut module, &cgcx.module_config);
825826// After we've done the initial round of optimizations we need to
827 // decide whether to synchronously codegen this module or ship it
828 // back to the coordinator thread for further LTO processing (which
829 // has to wait for all the initial modules to be optimized).
830831let lto_type =
832compute_per_cgu_lto_type(&cgcx.lto, cgcx.use_linker_plugin_lto, &cgcx.crate_types);
833834// If we're doing some form of incremental LTO then we need to be sure to
835 // save our module to disk first.
836let bitcode = if cgcx.module_config.emit_pre_lto_bc {
837let filename = pre_lto_bitcode_filename(&module.name);
838cgcx.incr_comp_session_dir.as_ref().map(|path| path.join(&filename))
839 } else {
840None841 };
842843match lto_type {
844 ComputedLtoType::No => {
845let module = B::codegen(cgcx, &prof, &shared_emitter, module, &cgcx.module_config);
846 WorkItemResult::Finished(module)
847 }
848 ComputedLtoType::Thin => {
849let thin_buffer = B::serialize_module(module.module_llvm, true);
850if let Some(path) = bitcode {
851 fs::write(&path, thin_buffer.data()).unwrap_or_else(|e| {
852{
::core::panicking::panic_fmt(format_args!("Error writing pre-lto-bitcode file `{0}`: {1}",
path.display(), e));
};panic!("Error writing pre-lto-bitcode file `{}`: {}", path.display(), e);
853 });
854 }
855 WorkItemResult::NeedsThinLto(module.name, thin_buffer)
856 }
857 ComputedLtoType::Fat => match bitcode {
858Some(path) => {
859let buffer = B::serialize_module(module.module_llvm, false);
860 fs::write(&path, buffer.data()).unwrap_or_else(|e| {
861{
::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);
862 });
863 WorkItemResult::NeedsFatLto(FatLtoInput::Serialized {
864 name: module.name,
865 bitcode_path: path,
866 })
867 }
868None => WorkItemResult::NeedsFatLto(FatLtoInput::InMemory(module)),
869 },
870 }
871}
872873fn execute_copy_from_cache_work_item(
874 cgcx: &CodegenContext,
875 prof: &SelfProfilerRef,
876 shared_emitter: SharedEmitter,
877 module: CachedModuleCodegen,
878) -> CompiledModule {
879let _timer =
880prof.generic_activity_with_arg("codegen_copy_artifacts_from_incr_cache", &*module.name);
881882let dcx = DiagCtxt::new(Box::new(shared_emitter));
883let dcx = dcx.handle();
884885let incr_comp_session_dir = cgcx.incr_comp_session_dir.as_ref().unwrap();
886887let mut links_from_incr_cache = Vec::new();
888889let mut load_from_incr_comp_dir = |output_path: PathBuf, saved_path: &str| {
890let source_file_in_incr_comp_dir = incr_comp_session_dir.join(saved_path);
891{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/back/write.rs:891",
"rustc_codegen_ssa::back::write", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/back/write.rs"),
::tracing_core::__macro_support::Option::Some(891u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::write"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("copying preexisting module `{0}` from {1:?} to {2}",
module.name, source_file_in_incr_comp_dir,
output_path.display()) as &dyn Value))])
});
} else { ; }
};debug!(
892"copying preexisting module `{}` from {:?} to {}",
893 module.name,
894 source_file_in_incr_comp_dir,
895 output_path.display()
896 );
897match link_or_copy(&source_file_in_incr_comp_dir, &output_path) {
898Ok(_) => {
899links_from_incr_cache.push(source_file_in_incr_comp_dir);
900Some(output_path)
901 }
902Err(error) => {
903dcx.emit_err(errors::CopyPathBuf {
904 source_file: source_file_in_incr_comp_dir,
905output_path,
906error,
907 });
908None909 }
910 }
911 };
912913let dwarf_object =
914module.source.saved_files.get("dwo").as_ref().and_then(|saved_dwarf_object_file| {
915let dwarf_obj_out = cgcx916 .output_filenames
917 .split_dwarf_path(cgcx.split_debuginfo, cgcx.split_dwarf_kind, &module.name)
918 .expect(
919"saved dwarf object in work product but `split_dwarf_path` returned `None`",
920 );
921load_from_incr_comp_dir(dwarf_obj_out, saved_dwarf_object_file)
922 });
923924let mut load_from_incr_cache = |perform, output_type: OutputType| {
925if perform {
926let saved_file = module.source.saved_files.get(output_type.extension())?;
927let output_path = cgcx.output_filenames.temp_path_for_cgu(output_type, &module.name);
928load_from_incr_comp_dir(output_path, &saved_file)
929 } else {
930None931 }
932 };
933934let module_config = &cgcx.module_config;
935let should_emit_obj = module_config.emit_obj != EmitObj::None;
936let assembly = load_from_incr_cache(module_config.emit_asm, OutputType::Assembly);
937let llvm_ir = load_from_incr_cache(module_config.emit_ir, OutputType::LlvmAssembly);
938let bytecode = load_from_incr_cache(module_config.emit_bc, OutputType::Bitcode);
939let object = load_from_incr_cache(should_emit_obj, OutputType::Object);
940let global_asm_object =
941if should_emit_obj && let Some(saved_file) = module.source.saved_files.get("asm.o") {
942let output_path = cgcx.output_filenames.temp_path_ext_for_cgu("asm.o", &module.name);
943load_from_incr_comp_dir(output_path, &saved_file)
944 } else {
945None946 };
947if should_emit_obj && object.is_none() {
948dcx.emit_fatal(errors::NoSavedObjectFile { cgu_name: &module.name })
949 }
950951CompiledModule {
952links_from_incr_cache,
953 kind: ModuleKind::Regular,
954 name: module.name,
955object,
956global_asm_object,
957dwarf_object,
958bytecode,
959assembly,
960llvm_ir,
961 }
962}
963964fn do_fat_lto<B: WriteBackendMethods>(
965 sess: &Session,
966 cgcx: &CodegenContext,
967 shared_emitter: SharedEmitter,
968 tm_factory: TargetMachineFactoryFn<B>,
969 exported_symbols_for_lto: &[String],
970 each_linked_rlib_for_lto: &[PathBuf],
971 needs_fat_lto: Vec<FatLtoInput<B>>,
972) -> CompiledModule {
973let _timer = sess.prof.verbose_generic_activity("LLVM_fatlto");
974975let dcx = DiagCtxt::new(Box::new(shared_emitter.clone()));
976let dcx = dcx.handle();
977978check_lto_allowed(&cgcx, dcx);
979980 B::optimize_and_codegen_fat_lto(
981sess,
982cgcx,
983&shared_emitter,
984tm_factory,
985exported_symbols_for_lto,
986each_linked_rlib_for_lto,
987needs_fat_lto,
988 )
989}
990991fn do_thin_lto<B: WriteBackendMethods>(
992 cgcx: &CodegenContext,
993 prof: &SelfProfilerRef,
994 shared_emitter: SharedEmitter,
995 tm_factory: TargetMachineFactoryFn<B>,
996 exported_symbols_for_lto: &[String],
997 each_linked_rlib_for_lto: &[PathBuf],
998 needs_thin_lto: Vec<ThinLtoInput<B>>,
999) -> Vec<CompiledModule> {
1000let _timer = prof.verbose_generic_activity("LLVM_thinlto");
10011002let dcx = DiagCtxt::new(Box::new(shared_emitter.clone()));
1003let dcx = dcx.handle();
10041005check_lto_allowed(&cgcx, dcx);
10061007let (coordinator_send, coordinator_receive) = channel();
10081009// First up, convert our jobserver into a helper thread so we can use normal
1010 // mpsc channels to manage our messages and such.
1011 // After we've requested tokens then we'll, when we can,
1012 // get tokens on `coordinator_receive` which will
1013 // get managed in the main loop below.
1014let coordinator_send2 = coordinator_send.clone();
1015let helper = jobserver::client()
1016 .into_helper_thread(move |token| {
1017drop(coordinator_send2.send(ThinLtoMessage::Token(token)));
1018 })
1019 .expect("failed to spawn helper thread");
10201021let mut work_items = ::alloc::vec::Vec::new()vec![];
10221023// We have LTO work to do. Perform the serial work here of
1024 // figuring out what we're going to LTO and then push a
1025 // bunch of work items onto our queue to do LTO. This all
1026 // happens on the coordinator thread but it's very quick so
1027 // we don't worry about tokens.
1028for (work, cost) in generate_thin_lto_work::<B>(
1029 cgcx,
1030 prof,
1031 dcx,
1032&exported_symbols_for_lto,
1033&each_linked_rlib_for_lto,
1034 needs_thin_lto,
1035 ) {
1036let insertion_index =
1037 work_items.binary_search_by_key(&cost, |&(_, cost)| cost).unwrap_or_else(|e| e);
1038 work_items.insert(insertion_index, (work, cost));
1039if cgcx.parallel {
1040 helper.request_token();
1041 }
1042 }
10431044let mut codegen_aborted = None;
10451046// These are the Jobserver Tokens we currently hold. Does not include
1047 // the implicit Token the compiler process owns no matter what.
1048let mut tokens = ::alloc::vec::Vec::new()vec![];
10491050// Amount of tokens that are used (including the implicit token).
1051let mut used_token_count = 0;
10521053let mut compiled_modules = ::alloc::vec::Vec::new()vec![];
10541055// Run the message loop while there's still anything that needs message
1056 // processing. Note that as soon as codegen is aborted we simply want to
1057 // wait for all existing work to finish, so many of the conditions here
1058 // only apply if codegen hasn't been aborted as they represent pending
1059 // work to be done.
1060loop {
1061if codegen_aborted.is_none() {
1062if used_token_count == 0 && work_items.is_empty() {
1063// All codegen work is done.
1064break;
1065 }
10661067// Spin up what work we can, only doing this while we've got available
1068 // parallelism slots and work left to spawn.
1069while used_token_count < tokens.len() + 1
1070&& let Some((item, _)) = work_items.pop()
1071 {
1072 spawn_thin_lto_work(
1073&cgcx,
1074 prof,
1075 shared_emitter.clone(),
1076 Arc::clone(&tm_factory),
1077 coordinator_send.clone(),
1078 item,
1079 );
1080 used_token_count += 1;
1081 }
1082 } else {
1083// Don't queue up any more work if codegen was aborted, we're
1084 // just waiting for our existing children to finish.
1085if used_token_count == 0 {
1086break;
1087 }
1088 }
10891090// Relinquish accidentally acquired extra tokens. Subtract 1 for the implicit token.
1091tokens.truncate(used_token_count.saturating_sub(1));
10921093match coordinator_receive.recv().unwrap() {
1094// Save the token locally and the next turn of the loop will use
1095 // this to spawn a new unit of work, or it may get dropped
1096 // immediately if we have no more work to spawn.
1097ThinLtoMessage::Token(token) => match token {
1098Ok(token) => {
1099tokens.push(token);
1100 }
1101Err(e) => {
1102let msg = &::alloc::__export::must_use({
::alloc::fmt::format(format_args!("failed to acquire jobserver token: {0}",
e))
})format!("failed to acquire jobserver token: {e}");
1103shared_emitter.fatal(msg);
1104codegen_aborted = Some(FatalError);
1105 }
1106 },
11071108 ThinLtoMessage::WorkItem { result } => {
1109// If a thread exits successfully then we drop a token associated
1110 // with that worker and update our `used_token_count` count.
1111 // We may later re-acquire a token to continue running more work.
1112 // We may also not actually drop a token here if the worker was
1113 // running with an "ephemeral token".
1114used_token_count -= 1;
11151116match result {
1117Ok(compiled_module) => compiled_modules.push(compiled_module),
1118Err(Some(WorkerFatalError)) => {
1119// Like `CodegenAborted`, wait for remaining work to finish.
1120codegen_aborted = Some(FatalError);
1121 }
1122Err(None) => {
1123// If the thread failed that means it panicked, so
1124 // we abort immediately.
1125::rustc_middle::util::bug::bug_fmt(format_args!("worker thread panicked"));bug!("worker thread panicked");
1126 }
1127 }
1128 }
1129 }
1130 }
11311132if let Some(codegen_aborted) = codegen_aborted {
1133codegen_aborted.raise();
1134 }
11351136compiled_modules1137}
11381139/// Messages sent to the coordinator.
1140pub(crate) enum Message<B: WriteBackendMethods> {
1141/// A jobserver token has become available. Sent from the jobserver helper
1142 /// thread.
1143Token(io::Result<Acquired>),
11441145/// The backend has finished processing a work item for a codegen unit.
1146 /// Sent from a backend worker thread.
1147WorkItem { result: Result<WorkItemResult<B>, Option<WorkerFatalError>> },
11481149/// The frontend has finished generating something (backend IR or a
1150 /// post-LTO artifact) for a codegen unit, and it should be passed to the
1151 /// backend. Sent from the main thread.
1152CodegenDone { llvm_work_item: WorkItem<B>, cost: u64 },
11531154/// Similar to `CodegenDone`, but for reusing a pre-LTO artifact
1155 /// Sent from the main thread.
1156AddImportOnlyModule { bitcode_path: PathBuf, work_product: WorkProduct },
11571158/// The frontend has finished generating everything for all codegen units.
1159 /// Sent from the main thread.
1160CodegenComplete,
11611162/// Some normal-ish compiler error occurred, and codegen should be wound
1163 /// down. Sent from the main thread.
1164CodegenAborted,
1165}
11661167/// Messages sent to the coordinator.
1168pub(crate) enum ThinLtoMessage {
1169/// A jobserver token has become available. Sent from the jobserver helper
1170 /// thread.
1171Token(io::Result<Acquired>),
11721173/// The backend has finished processing a work item for a codegen unit.
1174 /// Sent from a backend worker thread.
1175WorkItem { result: Result<CompiledModule, Option<WorkerFatalError>> },
1176}
11771178/// A message sent from the coordinator thread to the main thread telling it to
1179/// process another codegen unit.
1180pub struct CguMessage;
11811182// A cut-down version of `rustc_errors::DiagInner` that impls `Send`, which
1183// can be used to send diagnostics from codegen threads to the main thread.
1184// It's missing the following fields from `rustc_errors::DiagInner`.
1185// - `span`: it doesn't impl `Send`.
1186// - `suggestions`: it doesn't impl `Send`, and isn't used for codegen
1187// diagnostics.
1188// - `sort_span`: it doesn't impl `Send`.
1189// - `is_lint`: lints aren't relevant during codegen.
1190// - `emitted_at`: not used for codegen diagnostics.
1191struct Diagnostic {
1192 span: Vec<SpanData>,
1193 level: Level,
1194 messages: Vec<(DiagMessage, Style)>,
1195 code: Option<ErrCode>,
1196 children: Vec<Subdiagnostic>,
1197 args: DiagArgMap,
1198}
11991200// A cut-down version of `rustc_errors::Subdiag` that impls `Send`. It's
1201// missing the following fields from `rustc_errors::Subdiag`.
1202// - `span`: it doesn't impl `Send`.
1203struct Subdiagnostic {
1204 level: Level,
1205 messages: Vec<(DiagMessage, Style)>,
1206}
12071208#[derive(#[automatically_derived]
impl ::core::cmp::PartialEq for MainThreadState {
#[inline]
fn eq(&self, other: &MainThreadState) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq, #[automatically_derived]
impl ::core::clone::Clone for MainThreadState {
#[inline]
fn clone(&self) -> MainThreadState { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for MainThreadState { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for MainThreadState {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
MainThreadState::Idle => "Idle",
MainThreadState::Codegenning => "Codegenning",
MainThreadState::Lending => "Lending",
})
}
}Debug)]
1209enum MainThreadState {
1210/// Doing nothing.
1211Idle,
12121213/// Doing codegen, i.e. MIR-to-LLVM-IR conversion.
1214Codegenning,
12151216/// Idle, but lending the compiler process's Token to an LLVM thread so it can do useful work.
1217Lending,
1218}
12191220fn start_executing_work<B: WriteBackendMethods>(
1221 backend: B,
1222 tcx: TyCtxt<'_>,
1223 shared_emitter: SharedEmitter,
1224 codegen_worker_send: Sender<CguMessage>,
1225 coordinator_receive: Receiver<Message<B>>,
1226 regular_config: Arc<ModuleConfig>,
1227 allocator_config: Arc<ModuleConfig>,
1228mut allocator_module: Option<ModuleCodegen<B::Module>>,
1229 coordinator_send: Sender<Message<B>>,
1230) -> thread::JoinHandle<Result<MaybeLtoModules<B>, ()>> {
1231let sess = tcx.sess;
1232let prof = sess.prof.clone();
12331234// Compute the set of symbols we need to retain when doing thin local LTO (if we need to)
1235let exported_symbols_for_lto =
1236if sess.lto() == Lto::ThinLocal { lto::exported_symbols_for_lto(tcx, &[]) } else { ::alloc::vec::Vec::new()vec![] };
12371238// First up, convert our jobserver into a helper thread so we can use normal
1239 // mpsc channels to manage our messages and such.
1240 // After we've requested tokens then we'll, when we can,
1241 // get tokens on `coordinator_receive` which will
1242 // get managed in the main loop below.
1243let coordinator_send2 = coordinator_send.clone();
1244let helper = jobserver::client()
1245 .into_helper_thread(move |token| {
1246drop(coordinator_send2.send(Message::Token::<B>(token)));
1247 })
1248 .expect("failed to spawn helper thread");
12491250let opt_level = tcx.backend_optimization_level(());
1251let backend_features = tcx.global_backend_features(()).clone();
1252let tm_factory = backend.target_machine_factory(tcx.sess, opt_level, &backend_features);
12531254let remark_dir = if let Some(ref dir) = sess.opts.unstable_opts.remark_dir {
1255let result = fs::create_dir_all(dir).and_then(|_| dir.canonicalize());
1256match result {
1257Ok(dir) => Some(dir),
1258Err(error) => sess.dcx().emit_fatal(ErrorCreatingRemarkDir { error }),
1259 }
1260 } else {
1261None1262 };
12631264let cgcx = CodegenContext {
1265 crate_types: tcx.crate_types().to_vec(),
1266 lto: sess.lto(),
1267 use_linker_plugin_lto: sess.opts.cg.linker_plugin_lto.enabled(),
1268 dylib_lto: sess.opts.unstable_opts.dylib_lto,
1269 prefer_dynamic: sess.opts.cg.prefer_dynamic,
1270 fewer_names: sess.fewer_names(),
1271 save_temps: sess.opts.cg.save_temps,
1272 time_trace: sess.opts.unstable_opts.llvm_time_trace,
1273 remark: sess.opts.cg.remark.clone(),
1274remark_dir,
1275 incr_comp_session_dir: sess.incr_comp_session_dir_opt().map(|r| r.clone()),
1276 output_filenames: Arc::clone(tcx.output_filenames(())),
1277 module_config: regular_config,
1278opt_level,
1279backend_features,
1280 msvc_imps_needed: msvc_imps_needed(tcx),
1281 is_pe_coff: tcx.sess.target.is_like_windows,
1282 target_can_use_split_dwarf: tcx.sess.target_can_use_split_dwarf(),
1283 target_arch: tcx.sess.target.arch.to_string(),
1284 target_is_like_darwin: tcx.sess.target.is_like_darwin,
1285 target_is_like_aix: tcx.sess.target.is_like_aix,
1286 target_is_like_gpu: tcx.sess.target.is_like_gpu,
1287 split_debuginfo: tcx.sess.split_debuginfo(),
1288 split_dwarf_kind: tcx.sess.opts.unstable_opts.split_dwarf_kind,
1289 parallel: backend.supports_parallel() && !sess.opts.unstable_opts.no_parallel_backend,
1290 pointer_size: tcx.data_layout.pointer_size(),
1291 };
12921293// This is the "main loop" of parallel work happening for parallel codegen.
1294 // It's here that we manage parallelism, schedule work, and work with
1295 // messages coming from clients.
1296 //
1297 // There are a few environmental pre-conditions that shape how the system
1298 // is set up:
1299 //
1300 // - Error reporting can only happen on the main thread because that's the
1301 // only place where we have access to the compiler `Session`.
1302 // - LLVM work can be done on any thread.
1303 // - Codegen can only happen on the main thread.
1304 // - Each thread doing substantial work must be in possession of a `Token`
1305 // from the `Jobserver`.
1306 // - The compiler process always holds one `Token`. Any additional `Tokens`
1307 // have to be requested from the `Jobserver`.
1308 //
1309 // Error Reporting
1310 // ===============
1311 // The error reporting restriction is handled separately from the rest: We
1312 // set up a `SharedEmitter` that holds an open channel to the main thread.
1313 // When an error occurs on any thread, the shared emitter will send the
1314 // error message to the receiver main thread (`SharedEmitterMain`). The
1315 // main thread will periodically query this error message queue and emit
1316 // any error messages it has received. It might even abort compilation if
1317 // it has received a fatal error. In this case we rely on all other threads
1318 // being torn down automatically with the main thread.
1319 // Since the main thread will often be busy doing codegen work, error
1320 // reporting will be somewhat delayed, since the message queue can only be
1321 // checked in between two work packages.
1322 //
1323 // Work Processing Infrastructure
1324 // ==============================
1325 // The work processing infrastructure knows three major actors:
1326 //
1327 // - the coordinator thread,
1328 // - the main thread, and
1329 // - LLVM worker threads
1330 //
1331 // The coordinator thread is running a message loop. It instructs the main
1332 // thread about what work to do when, and it will spawn off LLVM worker
1333 // threads as open LLVM WorkItems become available.
1334 //
1335 // The job of the main thread is to codegen CGUs into LLVM work packages
1336 // (since the main thread is the only thread that can do this). The main
1337 // thread will block until it receives a message from the coordinator, upon
1338 // which it will codegen one CGU, send it to the coordinator and block
1339 // again. This way the coordinator can control what the main thread is
1340 // doing.
1341 //
1342 // The coordinator keeps a queue of LLVM WorkItems, and when a `Token` is
1343 // available, it will spawn off a new LLVM worker thread and let it process
1344 // a WorkItem. When a LLVM worker thread is done with its WorkItem,
1345 // it will just shut down, which also frees all resources associated with
1346 // the given LLVM module, and sends a message to the coordinator that the
1347 // WorkItem has been completed.
1348 //
1349 // Work Scheduling
1350 // ===============
1351 // The scheduler's goal is to minimize the time it takes to complete all
1352 // work there is, however, we also want to keep memory consumption low
1353 // if possible. These two goals are at odds with each other: If memory
1354 // consumption were not an issue, we could just let the main thread produce
1355 // LLVM WorkItems at full speed, assuring maximal utilization of
1356 // Tokens/LLVM worker threads. However, since codegen is usually faster
1357 // than LLVM processing, the queue of LLVM WorkItems would fill up and each
1358 // WorkItem potentially holds on to a substantial amount of memory.
1359 //
1360 // So the actual goal is to always produce just enough LLVM WorkItems as
1361 // not to starve our LLVM worker threads. That means, once we have enough
1362 // WorkItems in our queue, we can block the main thread, so it does not
1363 // produce more until we need them.
1364 //
1365 // Doing LLVM Work on the Main Thread
1366 // ----------------------------------
1367 // Since the main thread owns the compiler process's implicit `Token`, it is
1368 // wasteful to keep it blocked without doing any work. Therefore, what we do
1369 // in this case is: We spawn off an additional LLVM worker thread that helps
1370 // reduce the queue. The work it is doing corresponds to the implicit
1371 // `Token`. The coordinator will mark the main thread as being busy with
1372 // LLVM work. (The actual work happens on another OS thread but we just care
1373 // about `Tokens`, not actual threads).
1374 //
1375 // When any LLVM worker thread finishes while the main thread is marked as
1376 // "busy with LLVM work", we can do a little switcheroo: We give the Token
1377 // of the just finished thread to the LLVM worker thread that is working on
1378 // behalf of the main thread's implicit Token, thus freeing up the main
1379 // thread again. The coordinator can then again decide what the main thread
1380 // should do. This allows the coordinator to make decisions at more points
1381 // in time.
1382 //
1383 // Striking a Balance between Throughput and Memory Consumption
1384 // ------------------------------------------------------------
1385 // Since our two goals, (1) use as many Tokens as possible and (2) keep
1386 // memory consumption as low as possible, are in conflict with each other,
1387 // we have to find a trade off between them. Right now, the goal is to keep
1388 // all workers busy, which means that no worker should find the queue empty
1389 // when it is ready to start.
1390 // How do we do achieve this? Good question :) We actually never know how
1391 // many `Tokens` are potentially available so it's hard to say how much to
1392 // fill up the queue before switching the main thread to LLVM work. Also we
1393 // currently don't have a means to estimate how long a running LLVM worker
1394 // will still be busy with it's current WorkItem. However, we know the
1395 // maximal count of available Tokens that makes sense (=the number of CPU
1396 // cores), so we can take a conservative guess. The heuristic we use here
1397 // is implemented in the `queue_full_enough()` function.
1398 //
1399 // Some Background on Jobservers
1400 // -----------------------------
1401 // It's worth also touching on the management of parallelism here. We don't
1402 // want to just spawn a thread per work item because while that's optimal
1403 // parallelism it may overload a system with too many threads or violate our
1404 // configuration for the maximum amount of cpu to use for this process. To
1405 // manage this we use the `jobserver` crate.
1406 //
1407 // Job servers are an artifact of GNU make and are used to manage
1408 // parallelism between processes. A jobserver is a glorified IPC semaphore
1409 // basically. Whenever we want to run some work we acquire the semaphore,
1410 // and whenever we're done with that work we release the semaphore. In this
1411 // manner we can ensure that the maximum number of parallel workers is
1412 // capped at any one point in time.
1413 //
1414 // LTO and the coordinator thread
1415 // ------------------------------
1416 //
1417 // The final job the coordinator thread is responsible for is managing LTO
1418 // and how that works. When LTO is requested what we'll do is collect all
1419 // optimized LLVM modules into a local vector on the coordinator. Once all
1420 // modules have been codegened and optimized we hand this to the `lto`
1421 // module for further optimization. The `lto` module will return back a list
1422 // of more modules to work on, which the coordinator will continue to spawn
1423 // work for.
1424 //
1425 // Each LLVM module is automatically sent back to the coordinator for LTO if
1426 // necessary. There's already optimizations in place to avoid sending work
1427 // back to the coordinator if LTO isn't requested.
1428let f = move || {
1429let _profiler = if cgcx.time_trace { B::thread_profiler() } else { Box::new(()) };
14301431// This is where we collect codegen units that have gone all the way
1432 // through codegen and LLVM.
1433let mut compiled_modules = ::alloc::vec::Vec::new()vec![];
1434let mut needs_fat_lto = Vec::new();
1435let mut needs_thin_lto = Vec::new();
1436let mut lto_import_only_modules = Vec::new();
14371438/// Possible state transitions:
1439 /// - Ongoing -> Completed
1440 /// - Ongoing -> Aborted
1441 /// - Completed -> Aborted
1442#[derive(#[automatically_derived]
impl ::core::fmt::Debug for CodegenState {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
CodegenState::Ongoing => "Ongoing",
CodegenState::Completed => "Completed",
CodegenState::Aborted => "Aborted",
})
}
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for CodegenState {
#[inline]
fn eq(&self, other: &CodegenState) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq)]
1443enum CodegenState {
1444 Ongoing,
1445 Completed,
1446 Aborted,
1447 }
1448use CodegenState::*;
1449let mut codegen_state = Ongoing;
14501451// This is the queue of LLVM work items that still need processing.
1452let mut work_items = Vec::<(WorkItem<B>, u64)>::new();
14531454// This are the Jobserver Tokens we currently hold. Does not include
1455 // the implicit Token the compiler process owns no matter what.
1456let mut tokens = Vec::new();
14571458let mut main_thread_state = MainThreadState::Idle;
14591460// How many LLVM worker threads are running while holding a Token. This
1461 // *excludes* any that the main thread is lending a Token to.
1462let mut running_with_own_token = 0;
14631464// How many LLVM worker threads are running in total. This *includes*
1465 // any that the main thread is lending a Token to.
1466let running_with_any_token = |main_thread_state, running_with_own_token| {
1467running_with_own_token1468 + if main_thread_state == MainThreadState::Lending { 1 } else { 0 }
1469 };
14701471let mut llvm_start_time: Option<VerboseTimingGuard<'_>> = None;
14721473if let Some(allocator_module) = &mut allocator_module {
1474 B::optimize(&cgcx, &prof, &shared_emitter, allocator_module, &allocator_config);
1475 }
14761477// Run the message loop while there's still anything that needs message
1478 // processing. Note that as soon as codegen is aborted we simply want to
1479 // wait for all existing work to finish, so many of the conditions here
1480 // only apply if codegen hasn't been aborted as they represent pending
1481 // work to be done.
1482loop {
1483// While there are still CGUs to be codegened, the coordinator has
1484 // to decide how to utilize the compiler processes implicit Token:
1485 // For codegenning more CGU or for running them through LLVM.
1486if codegen_state == Ongoing {
1487if main_thread_state == MainThreadState::Idle {
1488// Compute the number of workers that will be running once we've taken as many
1489 // items from the work queue as we can, plus one for the main thread. It's not
1490 // critically important that we use this instead of just
1491 // `running_with_own_token`, but it prevents the `queue_full_enough` heuristic
1492 // from fluctuating just because a worker finished up and we decreased the
1493 // `running_with_own_token` count, even though we're just going to increase it
1494 // right after this when we put a new worker to work.
1495let extra_tokens = tokens.len().checked_sub(running_with_own_token).unwrap();
1496let additional_running = std::cmp::min(extra_tokens, work_items.len());
1497let anticipated_running = running_with_own_token + additional_running + 1;
14981499if !queue_full_enough(work_items.len(), anticipated_running) {
1500// The queue is not full enough, process more codegen units:
1501if codegen_worker_send.send(CguMessage).is_err() {
1502{
::core::panicking::panic_fmt(format_args!("Could not send CguMessage to main thread"));
}panic!("Could not send CguMessage to main thread")1503 }
1504main_thread_state = MainThreadState::Codegenning;
1505 } else {
1506// The queue is full enough to not let the worker
1507 // threads starve. Use the implicit Token to do some
1508 // LLVM work too.
1509let (item, _) =
1510work_items.pop().expect("queue empty - queue_full_enough() broken?");
1511main_thread_state = MainThreadState::Lending;
1512spawn_work(
1513&cgcx,
1514&prof,
1515shared_emitter.clone(),
1516coordinator_send.clone(),
1517&mut llvm_start_time,
1518item,
1519 );
1520 }
1521 }
1522 } else if codegen_state == Completed {
1523if running_with_any_token(main_thread_state, running_with_own_token) == 0
1524&& work_items.is_empty()
1525 {
1526// All codegen work is done.
1527break;
1528 }
15291530// In this branch, we know that everything has been codegened,
1531 // so it's just a matter of determining whether the implicit
1532 // Token is free to use for LLVM work.
1533match main_thread_state {
1534 MainThreadState::Idle => {
1535if let Some((item, _)) = work_items.pop() {
1536main_thread_state = MainThreadState::Lending;
1537spawn_work(
1538&cgcx,
1539&prof,
1540shared_emitter.clone(),
1541coordinator_send.clone(),
1542&mut llvm_start_time,
1543item,
1544 );
1545 } else {
1546// There is no unstarted work, so let the main thread
1547 // take over for a running worker. Otherwise the
1548 // implicit token would just go to waste.
1549 // We reduce the `running` counter by one. The
1550 // `tokens.truncate()` below will take care of
1551 // giving the Token back.
1552if !(running_with_own_token > 0) {
::core::panicking::panic("assertion failed: running_with_own_token > 0")
};assert!(running_with_own_token > 0);
1553running_with_own_token -= 1;
1554main_thread_state = MainThreadState::Lending;
1555 }
1556 }
1557 MainThreadState::Codegenning => ::rustc_middle::util::bug::bug_fmt(format_args!("codegen worker should not be codegenning after codegen was already completed"))bug!(
1558"codegen worker should not be codegenning after \
1559 codegen was already completed"
1560),
1561 MainThreadState::Lending => {
1562// Already making good use of that token
1563}
1564 }
1565 } else {
1566// Don't queue up any more work if codegen was aborted, we're
1567 // just waiting for our existing children to finish.
1568if !(codegen_state == Aborted) {
::core::panicking::panic("assertion failed: codegen_state == Aborted")
};assert!(codegen_state == Aborted);
1569if running_with_any_token(main_thread_state, running_with_own_token) == 0 {
1570break;
1571 }
1572 }
15731574// Spin up what work we can, only doing this while we've got available
1575 // parallelism slots and work left to spawn.
1576if codegen_state != Aborted {
1577while running_with_own_token < tokens.len()
1578 && let Some((item, _)) = work_items.pop()
1579 {
1580 spawn_work(
1581&cgcx,
1582&prof,
1583 shared_emitter.clone(),
1584 coordinator_send.clone(),
1585&mut llvm_start_time,
1586 item,
1587 );
1588 running_with_own_token += 1;
1589 }
1590 }
15911592// Relinquish accidentally acquired extra tokens.
1593tokens.truncate(running_with_own_token);
15941595match coordinator_receive.recv().unwrap() {
1596// Save the token locally and the next turn of the loop will use
1597 // this to spawn a new unit of work, or it may get dropped
1598 // immediately if we have no more work to spawn.
1599Message::Token(token) => {
1600match token {
1601Ok(token) => {
1602tokens.push(token);
16031604if main_thread_state == MainThreadState::Lending {
1605// If the main thread token is used for LLVM work
1606 // at the moment, we turn that thread into a regular
1607 // LLVM worker thread, so the main thread is free
1608 // to react to codegen demand.
1609main_thread_state = MainThreadState::Idle;
1610running_with_own_token += 1;
1611 }
1612 }
1613Err(e) => {
1614let msg = &::alloc::__export::must_use({
::alloc::fmt::format(format_args!("failed to acquire jobserver token: {0}",
e))
})format!("failed to acquire jobserver token: {e}");
1615shared_emitter.fatal(msg);
1616codegen_state = Aborted;
1617 }
1618 }
1619 }
16201621 Message::CodegenDone { llvm_work_item, cost } => {
1622// We keep the queue sorted by estimated processing cost,
1623 // so that more expensive items are processed earlier. This
1624 // is good for throughput as it gives the main thread more
1625 // time to fill up the queue and it avoids scheduling
1626 // expensive items to the end.
1627 // Note, however, that this is not ideal for memory
1628 // consumption, as LLVM module sizes are not evenly
1629 // distributed.
1630let insertion_index = work_items.binary_search_by_key(&cost, |&(_, cost)| cost);
1631let insertion_index = match insertion_index {
1632Ok(idx) | Err(idx) => idx,
1633 };
1634work_items.insert(insertion_index, (llvm_work_item, cost));
16351636if cgcx.parallel {
1637helper.request_token();
1638 }
1639{
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);
1640main_thread_state = MainThreadState::Idle;
1641 }
16421643 Message::CodegenComplete => {
1644if codegen_state != Aborted {
1645codegen_state = Completed;
1646 }
1647{
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);
1648main_thread_state = MainThreadState::Idle;
1649 }
16501651// If codegen is aborted that means translation was aborted due
1652 // to some normal-ish compiler error. In this situation we want
1653 // to exit as soon as possible, but we want to make sure all
1654 // existing work has finished. Flag codegen as being done, and
1655 // then conditions above will ensure no more work is spawned but
1656 // we'll keep executing this loop until `running_with_own_token`
1657 // hits 0.
1658Message::CodegenAborted => {
1659codegen_state = Aborted;
1660 }
16611662 Message::WorkItem { result } => {
1663// If a thread exits successfully then we drop a token associated
1664 // with that worker and update our `running_with_own_token` count.
1665 // We may later re-acquire a token to continue running more work.
1666 // We may also not actually drop a token here if the worker was
1667 // running with an "ephemeral token".
1668if main_thread_state == MainThreadState::Lending {
1669main_thread_state = MainThreadState::Idle;
1670 } else {
1671running_with_own_token -= 1;
1672 }
16731674match result {
1675Ok(WorkItemResult::Finished(compiled_module)) => {
1676compiled_modules.push(compiled_module);
1677 }
1678Ok(WorkItemResult::NeedsFatLto(fat_lto_input)) => {
1679if !needs_thin_lto.is_empty() {
::core::panicking::panic("assertion failed: needs_thin_lto.is_empty()")
};assert!(needs_thin_lto.is_empty());
1680needs_fat_lto.push(fat_lto_input);
1681 }
1682Ok(WorkItemResult::NeedsThinLto(name, thin_buffer)) => {
1683if !needs_fat_lto.is_empty() {
::core::panicking::panic("assertion failed: needs_fat_lto.is_empty()")
};assert!(needs_fat_lto.is_empty());
1684needs_thin_lto.push(ThinLtoInput::Red {
1685name,
1686 buffer: SerializedModule::Local(thin_buffer),
1687 });
1688 }
1689Err(Some(WorkerFatalError)) => {
1690// Like `CodegenAborted`, wait for remaining work to finish.
1691codegen_state = Aborted;
1692 }
1693Err(None) => {
1694// If the thread failed that means it panicked, so
1695 // we abort immediately.
1696::rustc_middle::util::bug::bug_fmt(format_args!("worker thread panicked"));bug!("worker thread panicked");
1697 }
1698 }
1699 }
17001701 Message::AddImportOnlyModule { bitcode_path, work_product } => {
1702{
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);
1703{
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);
1704lto_import_only_modules.push((bitcode_path, work_product));
1705main_thread_state = MainThreadState::Idle;
1706 }
1707 }
1708 }
17091710// Drop to print timings
1711drop(llvm_start_time);
17121713if codegen_state == Aborted {
1714return Err(());
1715 }
17161717drop(codegen_state);
1718drop(tokens);
1719drop(helper);
1720if !work_items.is_empty() {
::core::panicking::panic("assertion failed: work_items.is_empty()")
};assert!(work_items.is_empty());
17211722if !needs_fat_lto.is_empty() {
1723if !compiled_modules.is_empty() {
::core::panicking::panic("assertion failed: compiled_modules.is_empty()")
};assert!(compiled_modules.is_empty());
1724if !needs_thin_lto.is_empty() {
::core::panicking::panic("assertion failed: needs_thin_lto.is_empty()")
};assert!(needs_thin_lto.is_empty());
17251726if let Some(allocator_module) = allocator_module.take() {
1727needs_fat_lto.push(FatLtoInput::InMemory(allocator_module));
1728 }
17291730for (bitcode_path, wp) in lto_import_only_modules {
1731 needs_fat_lto.push(FatLtoInput::Serialized { name: wp.cgu_name, bitcode_path })
1732 }
17331734return Ok(MaybeLtoModules::FatLto { cgcx, needs_fat_lto });
1735 } else if !needs_thin_lto.is_empty() || !lto_import_only_modules.is_empty() {
1736if !compiled_modules.is_empty() {
::core::panicking::panic("assertion failed: compiled_modules.is_empty()")
};assert!(compiled_modules.is_empty());
1737if !needs_fat_lto.is_empty() {
::core::panicking::panic("assertion failed: needs_fat_lto.is_empty()")
};assert!(needs_fat_lto.is_empty());
17381739for (bitcode_path, wp) in lto_import_only_modules {
1740 needs_thin_lto.push(ThinLtoInput::Green { wp, bitcode_path })
1741 }
17421743if cgcx.lto == Lto::ThinLocal {
1744compiled_modules.extend(do_thin_lto::<B>(
1745&cgcx,
1746&prof,
1747shared_emitter.clone(),
1748tm_factory,
1749&exported_symbols_for_lto,
1750&[],
1751needs_thin_lto,
1752 ));
1753 } else {
1754if let Some(allocator_module) = allocator_module.take() {
1755let thin_buffer = B::serialize_module(allocator_module.module_llvm, true);
1756needs_thin_lto.push(ThinLtoInput::Red {
1757 name: allocator_module.name,
1758 buffer: SerializedModule::Local(thin_buffer),
1759 });
1760 }
17611762return Ok(MaybeLtoModules::ThinLto { cgcx, needs_thin_lto });
1763 }
1764 }
17651766Ok(MaybeLtoModules::NoLto(CompiledModules {
1767 modules: compiled_modules,
1768 allocator_module: allocator_module.map(|allocator_module| {
1769 B::codegen(&cgcx, &prof, &shared_emitter, allocator_module, &allocator_config)
1770 }),
1771 }))
1772 };
1773return std::thread::Builder::new()
1774 .name("coordinator".to_owned())
1775 .spawn(f)
1776 .expect("failed to spawn coordinator thread");
17771778// A heuristic that determines if we have enough LLVM WorkItems in the
1779 // queue so that the main thread can do LLVM work instead of codegen
1780fn queue_full_enough(items_in_queue: usize, workers_running: usize) -> bool {
1781// This heuristic scales ahead-of-time codegen according to available
1782 // concurrency, as measured by `workers_running`. The idea is that the
1783 // more concurrency we have available, the more demand there will be for
1784 // work items, and the fuller the queue should be kept to meet demand.
1785 // An important property of this approach is that we codegen ahead of
1786 // time only as much as necessary, so as to keep fewer LLVM modules in
1787 // memory at once, thereby reducing memory consumption.
1788 //
1789 // When the number of workers running is less than the max concurrency
1790 // available to us, this heuristic can cause us to instruct the main
1791 // thread to work on an LLVM item (that is, tell it to "LLVM") instead
1792 // of codegen, even though it seems like it *should* be codegenning so
1793 // that we can create more work items and spawn more LLVM workers.
1794 //
1795 // But this is not a problem. When the main thread is told to LLVM,
1796 // according to this heuristic and how work is scheduled, there is
1797 // always at least one item in the queue, and therefore at least one
1798 // pending jobserver token request. If there *is* more concurrency
1799 // available, we will immediately receive a token, which will upgrade
1800 // the main thread's LLVM worker to a real one (conceptually), and free
1801 // up the main thread to codegen if necessary. On the other hand, if
1802 // there isn't more concurrency, then the main thread working on an LLVM
1803 // item is appropriate, as long as the queue is full enough for demand.
1804 //
1805 // Speaking of which, how full should we keep the queue? Probably less
1806 // full than you'd think. A lot has to go wrong for the queue not to be
1807 // full enough and for that to have a negative effect on compile times.
1808 //
1809 // Workers are unlikely to finish at exactly the same time, so when one
1810 // finishes and takes another work item off the queue, we often have
1811 // ample time to codegen at that point before the next worker finishes.
1812 // But suppose that codegen takes so long that the workers exhaust the
1813 // queue, and we have one or more workers that have nothing to work on.
1814 // Well, it might not be so bad. Of all the LLVM modules we create and
1815 // optimize, one has to finish last. It's not necessarily the case that
1816 // by losing some concurrency for a moment, we delay the point at which
1817 // that last LLVM module is finished and the rest of compilation can
1818 // proceed. Also, when we can't take advantage of some concurrency, we
1819 // give tokens back to the job server. That enables some other rustc to
1820 // potentially make use of the available concurrency. That could even
1821 // *decrease* overall compile time if we're lucky. But yes, if no other
1822 // rustc can make use of the concurrency, then we've squandered it.
1823 //
1824 // However, keeping the queue full is also beneficial when we have a
1825 // surge in available concurrency. Then items can be taken from the
1826 // queue immediately, without having to wait for codegen.
1827 //
1828 // So, the heuristic below tries to keep one item in the queue for every
1829 // four running workers. Based on limited benchmarking, this appears to
1830 // be more than sufficient to avoid increasing compilation times.
1831let quarter_of_workers = workers_running - 3 * workers_running / 4;
1832items_in_queue > 0 && items_in_queue >= quarter_of_workers1833 }
1834}
18351836/// `FatalError` is explicitly not `Send`.
1837#[must_use]
1838pub(crate) struct WorkerFatalError;
18391840fn spawn_work<'a, B: WriteBackendMethods>(
1841 cgcx: &CodegenContext,
1842 prof: &'a SelfProfilerRef,
1843 shared_emitter: SharedEmitter,
1844 coordinator_send: Sender<Message<B>>,
1845 llvm_start_time: &mut Option<VerboseTimingGuard<'a>>,
1846 work: WorkItem<B>,
1847) {
1848if llvm_start_time.is_none() {
1849*llvm_start_time = Some(prof.verbose_generic_activity("LLVM_passes"));
1850 }
18511852let cgcx = cgcx.clone();
1853let prof = prof.clone();
18541855let name = work.short_description();
1856let f = move || {
1857let _profiler = if cgcx.time_trace { B::thread_profiler() } else { Box::new(()) };
18581859let result = std::panic::catch_unwind(AssertUnwindSafe(|| match work {
1860 WorkItem::Optimize(m) => execute_optimize_work_item(&cgcx, &prof, shared_emitter, m),
1861 WorkItem::CopyPostLtoArtifacts(m) => WorkItemResult::Finished(
1862execute_copy_from_cache_work_item(&cgcx, &prof, shared_emitter, m),
1863 ),
1864 }));
18651866let msg = match result {
1867Ok(result) => Message::WorkItem::<B> { result: Ok(result) },
18681869// We ignore any `FatalError` coming out of `execute_work_item`, as a
1870 // diagnostic was already sent off to the main thread - just surface
1871 // that there was an error in this worker.
1872Err(err) if err.is::<FatalErrorMarker>() => {
1873 Message::WorkItem::<B> { result: Err(Some(WorkerFatalError)) }
1874 }
18751876Err(_) => Message::WorkItem::<B> { result: Err(None) },
1877 };
1878drop(coordinator_send.send(msg));
1879 };
1880 std::thread::Builder::new().name(name).spawn(f).expect("failed to spawn work thread");
1881}
18821883fn spawn_thin_lto_work<B: WriteBackendMethods>(
1884 cgcx: &CodegenContext,
1885 prof: &SelfProfilerRef,
1886 shared_emitter: SharedEmitter,
1887 tm_factory: TargetMachineFactoryFn<B>,
1888 coordinator_send: Sender<ThinLtoMessage>,
1889 work: ThinLtoWorkItem<B>,
1890) {
1891let cgcx = cgcx.clone();
1892let prof = prof.clone();
18931894let name = work.short_description();
1895let f = move || {
1896let _profiler = if cgcx.time_trace { B::thread_profiler() } else { Box::new(()) };
18971898let result = std::panic::catch_unwind(AssertUnwindSafe(|| match work {
1899 ThinLtoWorkItem::CopyPostLtoArtifacts(m) => {
1900execute_copy_from_cache_work_item(&cgcx, &prof, shared_emitter, m)
1901 }
1902 ThinLtoWorkItem::ThinLto(m) => {
1903let _timer = prof.generic_activity_with_arg("codegen_module_perform_lto", m.name());
1904 B::optimize_and_codegen_thin(&cgcx, &prof, &shared_emitter, tm_factory, m)
1905 }
1906 }));
19071908let msg = match result {
1909Ok(result) => ThinLtoMessage::WorkItem { result: Ok(result) },
19101911// We ignore any `FatalError` coming out of `execute_work_item`, as a
1912 // diagnostic was already sent off to the main thread - just surface
1913 // that there was an error in this worker.
1914Err(err) if err.is::<FatalErrorMarker>() => {
1915 ThinLtoMessage::WorkItem { result: Err(Some(WorkerFatalError)) }
1916 }
19171918Err(_) => ThinLtoMessage::WorkItem { result: Err(None) },
1919 };
1920drop(coordinator_send.send(msg));
1921 };
1922 std::thread::Builder::new().name(name).spawn(f).expect("failed to spawn work thread");
1923}
19241925enum SharedEmitterMessage {
1926 Diagnostic(Diagnostic),
1927 InlineAsmError(InlineAsmError),
1928 Fatal(String),
1929}
19301931pub struct InlineAsmError {
1932pub span: SpanData,
1933pub msg: String,
1934pub level: Level,
1935pub source: Option<(String, Vec<InnerSpan>)>,
1936}
19371938#[derive(#[automatically_derived]
impl ::core::clone::Clone for SharedEmitter {
#[inline]
fn clone(&self) -> SharedEmitter {
SharedEmitter { sender: ::core::clone::Clone::clone(&self.sender) }
}
}Clone)]
1939pub struct SharedEmitter {
1940 sender: Sender<SharedEmitterMessage>,
1941}
19421943pub struct SharedEmitterMain {
1944 receiver: Receiver<SharedEmitterMessage>,
1945}
19461947impl SharedEmitter {
1948fn new() -> (SharedEmitter, SharedEmitterMain) {
1949let (sender, receiver) = channel();
19501951 (SharedEmitter { sender }, SharedEmitterMain { receiver })
1952 }
19531954pub fn inline_asm_error(&self, err: InlineAsmError) {
1955drop(self.sender.send(SharedEmitterMessage::InlineAsmError(err)));
1956 }
19571958fn fatal(&self, msg: &str) {
1959drop(self.sender.send(SharedEmitterMessage::Fatal(msg.to_string())));
1960 }
1961}
19621963impl Emitterfor SharedEmitter {
1964fn emit_diagnostic(&mut self, mut diag: rustc_errors::DiagInner) {
1965// Check that we aren't missing anything interesting when converting to
1966 // the cut-down local `DiagInner`.
1967if !!diag.span.has_span_labels() {
::core::panicking::panic("assertion failed: !diag.span.has_span_labels()")
};assert!(!diag.span.has_span_labels());
1968{
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![]));
1969{
match (&diag.sort_span, &rustc_span::DUMMY_SP) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(diag.sort_span, rustc_span::DUMMY_SP);
1970{
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);
1971// No sensible check for `diag.emitted_at`.
19721973let args = mem::take(&mut diag.args);
1974drop(
1975self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
1976 span: diag.span.primary_spans().iter().map(|span| span.data()).collect::<Vec<_>>(),
1977 level: diag.level(),
1978 messages: diag.messages,
1979 code: diag.code,
1980 children: diag1981 .children
1982 .into_iter()
1983 .map(|child| Subdiagnostic { level: child.level, messages: child.messages })
1984 .collect(),
1985args,
1986 })),
1987 );
1988 }
19891990fn source_map(&self) -> Option<&SourceMap> {
1991None1992 }
1993}
19941995impl SharedEmitterMain {
1996fn check(&self, sess: &Session, blocking: bool) {
1997loop {
1998let message = if blocking {
1999match self.receiver.recv() {
2000Ok(message) => Ok(message),
2001Err(_) => Err(()),
2002 }
2003 } else {
2004match self.receiver.try_recv() {
2005Ok(message) => Ok(message),
2006Err(_) => Err(()),
2007 }
2008 };
20092010match message {
2011Ok(SharedEmitterMessage::Diagnostic(diag)) => {
2012// The diagnostic has been received on the main thread.
2013 // Convert it back to a full `Diagnostic` and emit.
2014let dcx = sess.dcx();
2015let mut d =
2016 rustc_errors::DiagInner::new_with_messages(diag.level, diag.messages);
2017d.span = MultiSpan::from_spans(
2018diag.span.into_iter().map(|span| span.span()).collect(),
2019 );
2020d.code = diag.code; // may be `None`, that's ok
2021d.children = diag2022 .children
2023 .into_iter()
2024 .map(|sub| rustc_errors::Subdiag {
2025 level: sub.level,
2026 messages: sub.messages,
2027 span: MultiSpan::new(),
2028 })
2029 .collect();
2030d.args = diag.args;
2031dcx.emit_diagnostic(d);
2032sess.dcx().abort_if_errors();
2033 }
2034Ok(SharedEmitterMessage::InlineAsmError(inner)) => {
2035{
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);
2036let mut err = Diag::<()>::new(sess.dcx(), inner.level, inner.msg);
2037if !inner.span.is_dummy() {
2038err.span(inner.span.span());
2039 }
20402041// Point to the generated assembly if it is available.
2042if let Some((buffer, spans)) = inner.source {
2043let source = sess2044 .source_map()
2045 .new_source_file(FileName::inline_asm_source_code(&buffer), buffer);
2046let spans: Vec<_> = spans2047 .iter()
2048 .map(|sp| {
2049Span::with_root_ctxt(
2050source.normalized_byte_pos(sp.start as u32),
2051source.normalized_byte_pos(sp.end as u32),
2052 )
2053 })
2054 .collect();
2055err.span_note(spans, "instantiated into assembly here");
2056 }
20572058err.emit();
2059 }
2060Ok(SharedEmitterMessage::Fatal(msg)) => {
2061sess.dcx().fatal(msg);
2062 }
2063Err(_) => {
2064break;
2065 }
2066 }
2067 }
2068 }
2069}
20702071pub struct Coordinator<B: WriteBackendMethods> {
2072 sender: Sender<Message<B>>,
2073 future: Option<thread::JoinHandle<Result<MaybeLtoModules<B>, ()>>>,
2074// Only used for the Message type.
2075phantom: PhantomData<B>,
2076}
20772078impl<B: WriteBackendMethods> Coordinator<B> {
2079fn join(mut self) -> std::thread::Result<Result<MaybeLtoModules<B>, ()>> {
2080self.future.take().unwrap().join()
2081 }
2082}
20832084impl<B: WriteBackendMethods> Dropfor Coordinator<B> {
2085fn drop(&mut self) {
2086if let Some(future) = self.future.take() {
2087// If we haven't joined yet, signal to the coordinator that it should spawn no more
2088 // work, and wait for worker threads to finish.
2089drop(self.sender.send(Message::CodegenAborted::<B>));
2090drop(future.join());
2091 }
2092 }
2093}
20942095pub struct OngoingCodegen<B: WriteBackendMethods> {
2096 backend: B,
2097 output_filenames: Arc<OutputFilenames>,
2098// Field order below is intended to terminate the coordinator thread before two fields below
2099 // drop and prematurely close channels used by coordinator thread. See `Coordinator`'s
2100 // `Drop` implementation for more info.
2101pub(crate) coordinator: Coordinator<B>,
2102 codegen_worker_receive: Receiver<CguMessage>,
2103 shared_emitter_main: SharedEmitterMain,
2104}
21052106impl<B: WriteBackendMethods> OngoingCodegen<B> {
2107pub fn join(self, sess: &Session, crate_info: &CrateInfo) -> (CompiledModules, WorkProductMap) {
2108self.shared_emitter_main.check(sess, true);
21092110let maybe_lto_modules = sess.time("join_worker_thread", || match self.coordinator.join() {
2111Ok(Ok(maybe_lto_modules)) => maybe_lto_modules,
2112Ok(Err(())) => {
2113sess.dcx().abort_if_errors();
2114{
::core::panicking::panic_fmt(format_args!("expected abort due to worker thread errors"));
}panic!("expected abort due to worker thread errors")2115 }
2116Err(_) => {
2117::rustc_middle::util::bug::bug_fmt(format_args!("panic during codegen/LLVM phase"));bug!("panic during codegen/LLVM phase");
2118 }
2119 });
21202121sess.dcx().abort_if_errors();
21222123let (shared_emitter, shared_emitter_main) = SharedEmitter::new();
21242125// Catch fatal errors to ensure shared_emitter_main.check() can emit the actual diagnostics
2126let compiled_modules = catch_fatal_errors(|| match maybe_lto_modules {
2127 MaybeLtoModules::NoLto(compiled_modules) => {
2128drop(shared_emitter);
2129compiled_modules2130 }
2131 MaybeLtoModules::FatLto { cgcx, needs_fat_lto } => {
2132let tm_factory = self.backend.target_machine_factory(
2133sess,
2134cgcx.opt_level,
2135&cgcx.backend_features,
2136 );
21372138CompiledModules {
2139 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(
2140 sess,
2141&cgcx,
2142 shared_emitter,
2143 tm_factory,
2144&crate_info.exported_symbols_for_lto,
2145&crate_info.each_linked_rlib_file_for_lto,
2146 needs_fat_lto,
2147 )],
2148 allocator_module: None,
2149 }
2150 }
2151 MaybeLtoModules::ThinLto { cgcx, needs_thin_lto } => {
2152let tm_factory = self.backend.target_machine_factory(
2153sess,
2154cgcx.opt_level,
2155&cgcx.backend_features,
2156 );
21572158CompiledModules {
2159 modules: do_thin_lto::<B>(
2160&cgcx,
2161&sess.prof,
2162shared_emitter,
2163tm_factory,
2164&crate_info.exported_symbols_for_lto,
2165&crate_info.each_linked_rlib_file_for_lto,
2166needs_thin_lto,
2167 ),
2168 allocator_module: None,
2169 }
2170 }
2171 });
21722173shared_emitter_main.check(sess, true);
21742175sess.dcx().abort_if_errors();
21762177let mut compiled_modules =
2178compiled_modules.expect("fatal error emitted but not sent to SharedEmitter");
21792180// Regardless of what order these modules completed in, report them to
2181 // the backend in the same order every time to ensure that we're handing
2182 // out deterministic results.
2183compiled_modules.modules.sort_by(|a, b| a.name.cmp(&b.name));
21842185let work_products =
2186copy_all_cgu_workproducts_to_incr_comp_cache_dir(sess, &compiled_modules);
2187produce_final_output_artifacts(sess, &compiled_modules, &self.output_filenames);
21882189 (compiled_modules, work_products)
2190 }
21912192pub(crate) fn codegen_finished(&self, tcx: TyCtxt<'_>) {
2193self.wait_for_signal_to_codegen_item();
2194self.check_for_errors(tcx.sess);
2195drop(self.coordinator.sender.send(Message::CodegenComplete::<B>));
2196 }
21972198pub(crate) fn check_for_errors(&self, sess: &Session) {
2199self.shared_emitter_main.check(sess, false);
2200 }
22012202pub(crate) fn wait_for_signal_to_codegen_item(&self) {
2203match self.codegen_worker_receive.recv() {
2204Ok(CguMessage) => {
2205// Ok to proceed.
2206}
2207Err(_) => {
2208// One of the LLVM threads must have panicked, fall through so
2209 // error handling can be reached.
2210}
2211 }
2212 }
2213}
22142215pub(crate) fn submit_codegened_module_to_llvm<B: WriteBackendMethods>(
2216 coordinator: &Coordinator<B>,
2217 module: ModuleCodegen<B::Module>,
2218 cost: u64,
2219) {
2220let llvm_work_item = WorkItem::Optimize(module);
2221drop(coordinator.sender.send(Message::CodegenDone::<B> { llvm_work_item, cost }));
2222}
22232224pub(crate) fn submit_post_lto_module_to_llvm<B: WriteBackendMethods>(
2225 coordinator: &Coordinator<B>,
2226 module: CachedModuleCodegen,
2227) {
2228let llvm_work_item = WorkItem::CopyPostLtoArtifacts(module);
2229drop(coordinator.sender.send(Message::CodegenDone::<B> { llvm_work_item, cost: 0 }));
2230}
22312232pub(crate) fn submit_pre_lto_module_to_llvm<B: WriteBackendMethods>(
2233 tcx: TyCtxt<'_>,
2234 coordinator: &Coordinator<B>,
2235 module: CachedModuleCodegen,
2236) {
2237let filename = pre_lto_bitcode_filename(&module.name);
2238let bitcode_path = in_incr_comp_dir_sess(tcx.sess, &filename);
2239// Schedule the module to be loaded
2240drop(
2241coordinator2242 .sender
2243 .send(Message::AddImportOnlyModule::<B> { bitcode_path, work_product: module.source }),
2244 );
2245}
22462247fn pre_lto_bitcode_filename(module_name: &str) -> String {
2248::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}.{1}", module_name,
PRE_LTO_BC_EXT))
})format!("{module_name}.{PRE_LTO_BC_EXT}")2249}
22502251fn msvc_imps_needed(tcx: TyCtxt<'_>) -> bool {
2252// This should never be true (because it's not supported). If it is true,
2253 // something is wrong with commandline arg validation.
2254if !!(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!(
2255 !(tcx.sess.opts.cg.linker_plugin_lto.enabled()
2256 && tcx.sess.target.is_like_windows
2257 && tcx.sess.opts.cg.prefer_dynamic)
2258 );
22592260// We need to generate _imp__ symbol if we are generating an rlib or we include one
2261 // indirectly from ThinLTO. In theory these are not needed as ThinLTO could resolve
2262 // these, but it currently does not do so.
2263let can_have_static_objects =
2264tcx.sess.lto() == Lto::Thin || tcx.crate_types().contains(&CrateType::Rlib);
22652266tcx.sess.target.is_like_windows &&
2267can_have_static_objects &&
2268// ThinLTO can't handle this workaround in all cases, so we don't
2269 // emit the `__imp_` symbols. Instead we make them unnecessary by disallowing
2270 // dynamic linking when linker plugin LTO is enabled.
2271!tcx.sess.opts.cg.linker_plugin_lto.enabled()
2272}