]> git.proxmox.com Git - rustc.git/blame - compiler/rustc_codegen_ssa/src/back/write.rs
New upstream version 1.49.0+dfsg1
[rustc.git] / compiler / rustc_codegen_ssa / src / back / write.rs
CommitLineData
ba9703b0 1use super::link::{self, remove};
a1dfa0c6
XL
2use super::linker::LinkerInfo;
3use super::lto::{self, SerializedModule};
dfeec247
XL
4use super::symbol_export::symbol_name_for_instance_in_crate;
5
6use crate::{
7 CachedModuleCodegen, CodegenResults, CompiledModule, CrateInfo, ModuleCodegen, ModuleKind,
dfeec247 8};
a1dfa0c6 9
9fa01778 10use crate::traits::*;
dfeec247 11use jobserver::{Acquired, Client};
dfeec247 12use rustc_data_structures::fx::FxHashMap;
60c5eb7d 13use rustc_data_structures::profiling::SelfProfilerRef;
74b04a01 14use rustc_data_structures::profiling::TimingGuard;
dfeec247 15use rustc_data_structures::profiling::VerboseTimingGuard;
e74abb32 16use rustc_data_structures::sync::Lrc;
dfeec247
XL
17use rustc_errors::emitter::Emitter;
18use rustc_errors::{DiagnosticId, FatalError, Handler, Level};
19use rustc_fs_util::link_or_copy;
20use rustc_hir::def_id::{CrateNum, LOCAL_CRATE};
21use rustc_incremental::{
f9f354fc 22 copy_cgu_workproduct_to_incr_comp_cache_dir, in_incr_comp_dir, in_incr_comp_dir_sess,
dfeec247 23};
f9f354fc 24use rustc_middle::dep_graph::{WorkProduct, WorkProductId};
ba9703b0
XL
25use rustc_middle::middle::cstore::EncodedMetadata;
26use rustc_middle::middle::exported_symbols::SymbolExportLevel;
27use rustc_middle::ty::TyCtxt;
dfeec247 28use rustc_session::cgu_reuse_tracker::CguReuseTracker;
f9f354fc 29use rustc_session::config::{self, CrateType, Lto, OutputFilenames, OutputType};
f035d41b 30use rustc_session::config::{Passes, SanitizerSet, SwitchWithOptPath};
ba9703b0 31use rustc_session::Session;
dfeec247
XL
32use rustc_span::source_map::SourceMap;
33use rustc_span::symbol::{sym, Symbol};
f9f354fc
XL
34use rustc_span::{BytePos, FileName, InnerSpan, Pos, Span};
35use rustc_target::spec::{MergeFunctions, PanicStrategy};
a1dfa0c6
XL
36
37use std::any::Any;
38use std::fs;
39use std::io;
40use std::mem;
41use std::path::{Path, PathBuf};
42use std::str;
dfeec247 43use std::sync::mpsc::{channel, Receiver, Sender};
a1dfa0c6 44use std::sync::Arc;
a1dfa0c6
XL
45use std::thread;
46
9fa01778 47const PRE_LTO_BC_EXT: &str = "pre-lto.bc";
a1dfa0c6 48
ba9703b0
XL
49/// What kind of object file to emit.
50#[derive(Clone, Copy, PartialEq)]
51pub enum EmitObj {
52 // No object file.
53 None,
54
55 // Just uncompressed llvm bitcode. Provides easy compatibility with
56 // emscripten's ecc compiler, when used as the linker.
57 Bitcode,
58
59 // Object code, possibly augmented with a bitcode section.
60 ObjectCode(BitcodeSection),
61}
62
63/// What kind of llvm bitcode section to embed in an object file.
64#[derive(Clone, Copy, PartialEq)]
65pub enum BitcodeSection {
66 // No bitcode section.
67 None,
68
ba9703b0
XL
69 // A full, uncompressed bitcode section.
70 Full,
71}
72
a1dfa0c6
XL
73/// Module-specific configuration for `optimize_and_codegen`.
74pub struct ModuleConfig {
75 /// Names of additional optimization passes to run.
76 pub passes: Vec<String>,
77 /// Some(level) to optimize at a certain level, or None to run
78 /// absolutely no optimizations (used for the metadata module).
79 pub opt_level: Option<config::OptLevel>,
80
81 /// Some(level) to optimize binary size, or None to not affect program size.
82 pub opt_size: Option<config::OptLevel>,
83
dc9dc135
XL
84 pub pgo_gen: SwitchWithOptPath,
85 pub pgo_use: Option<PathBuf>,
a1dfa0c6 86
f035d41b
XL
87 pub sanitizer: SanitizerSet,
88 pub sanitizer_recover: SanitizerSet,
60c5eb7d
XL
89 pub sanitizer_memory_track_origins: usize,
90
a1dfa0c6 91 // Flags indicating which outputs to produce.
9fa01778 92 pub emit_pre_lto_bc: bool,
a1dfa0c6
XL
93 pub emit_no_opt_bc: bool,
94 pub emit_bc: bool,
a1dfa0c6
XL
95 pub emit_ir: bool,
96 pub emit_asm: bool,
ba9703b0 97 pub emit_obj: EmitObj,
f9f354fc 98 pub bc_cmdline: String,
ba9703b0 99
a1dfa0c6
XL
100 // Miscellaneous flags. These are mostly copied from command-line
101 // options.
102 pub verify_llvm_ir: bool,
103 pub no_prepopulate_passes: bool,
104 pub no_builtins: bool,
dfeec247 105 pub time_module: bool,
a1dfa0c6
XL
106 pub vectorize_loop: bool,
107 pub vectorize_slp: bool,
108 pub merge_functions: bool,
109 pub inline_threshold: Option<usize>,
ba9703b0 110 pub new_llvm_pass_manager: bool,
f9f354fc 111 pub emit_lifetime_markers: bool,
a1dfa0c6
XL
112}
113
114impl ModuleConfig {
f9f354fc
XL
115 fn new(
116 kind: ModuleKind,
117 sess: &Session,
118 no_builtins: bool,
119 is_compiler_builtins: bool,
120 ) -> ModuleConfig {
ba9703b0
XL
121 // If it's a regular module, use `$regular`, otherwise use `$other`.
122 // `$regular` and `$other` are evaluated lazily.
123 macro_rules! if_regular {
124 ($regular: expr, $other: expr) => {
125 if let ModuleKind::Regular = kind { $regular } else { $other }
126 };
a1dfa0c6 127 }
a1dfa0c6 128
ba9703b0
XL
129 let opt_level_and_size = if_regular!(Some(sess.opts.optimize), None);
130
131 let save_temps = sess.opts.cg.save_temps;
132
133 let should_emit_obj = sess.opts.output_types.contains_key(&OutputType::Exe)
134 || match kind {
135 ModuleKind::Regular => sess.opts.output_types.contains_key(&OutputType::Object),
136 ModuleKind::Allocator => false,
137 ModuleKind::Metadata => sess.opts.output_types.contains_key(&OutputType::Metadata),
138 };
139
140 let emit_obj = if !should_emit_obj {
141 EmitObj::None
29967ef6 142 } else if sess.target.obj_is_bitcode
f9f354fc 143 || (sess.opts.cg.linker_plugin_lto.enabled() && !no_builtins)
ba9703b0 144 {
f9f354fc
XL
145 // This case is selected if the target uses objects as bitcode, or
146 // if linker plugin LTO is enabled. In the linker plugin LTO case
147 // the assumption is that the final link-step will read the bitcode
148 // and convert it to object code. This may be done by either the
149 // native linker or rustc itself.
150 //
151 // Note, however, that the linker-plugin-lto requested here is
152 // explicitly ignored for `#![no_builtins]` crates. These crates are
153 // specifically ignored by rustc's LTO passes and wouldn't work if
154 // loaded into the linker. These crates define symbols that LLVM
155 // lowers intrinsics to, and these symbol dependencies aren't known
156 // until after codegen. As a result any crate marked
157 // `#![no_builtins]` is assumed to not participate in LTO and
158 // instead goes on to generate object code.
ba9703b0 159 EmitObj::Bitcode
f9f354fc
XL
160 } else if need_bitcode_in_object(sess) {
161 EmitObj::ObjectCode(BitcodeSection::Full)
ba9703b0
XL
162 } else {
163 EmitObj::ObjectCode(BitcodeSection::None)
9fa01778 164 };
ba9703b0
XL
165
166 ModuleConfig {
167 passes: if_regular!(
168 {
169 let mut passes = sess.opts.cg.passes.clone();
f9f354fc
XL
170 // compiler_builtins overrides the codegen-units settings,
171 // which is incompatible with -Zprofile which requires that
172 // only a single codegen unit is used per crate.
173 if sess.opts.debugging_opts.profile && !is_compiler_builtins {
ba9703b0
XL
174 passes.push("insert-gcov-profiling".to_owned());
175 }
f035d41b
XL
176
177 // The rustc option `-Zinstrument_coverage` injects intrinsic calls to
178 // `llvm.instrprof.increment()`, which requires the LLVM `instrprof` pass.
179 if sess.opts.debugging_opts.instrument_coverage {
180 passes.push("instrprof".to_owned());
181 }
ba9703b0
XL
182 passes
183 },
184 vec![]
185 ),
186
187 opt_level: opt_level_and_size,
188 opt_size: opt_level_and_size,
189
190 pgo_gen: if_regular!(
191 sess.opts.cg.profile_generate.clone(),
192 SwitchWithOptPath::Disabled
193 ),
194 pgo_use: if_regular!(sess.opts.cg.profile_use.clone(), None),
195
f035d41b 196 sanitizer: if_regular!(sess.opts.debugging_opts.sanitizer, SanitizerSet::empty()),
ba9703b0 197 sanitizer_recover: if_regular!(
f035d41b
XL
198 sess.opts.debugging_opts.sanitizer_recover,
199 SanitizerSet::empty()
ba9703b0
XL
200 ),
201 sanitizer_memory_track_origins: if_regular!(
202 sess.opts.debugging_opts.sanitizer_memory_track_origins,
203 0
204 ),
205
206 emit_pre_lto_bc: if_regular!(
207 save_temps || need_pre_lto_bitcode_for_incr_comp(sess),
208 false
209 ),
210 emit_no_opt_bc: if_regular!(save_temps, false),
211 emit_bc: if_regular!(
212 save_temps || sess.opts.output_types.contains_key(&OutputType::Bitcode),
213 save_temps
214 ),
ba9703b0
XL
215 emit_ir: if_regular!(
216 sess.opts.output_types.contains_key(&OutputType::LlvmAssembly),
217 false
218 ),
219 emit_asm: if_regular!(
220 sess.opts.output_types.contains_key(&OutputType::Assembly),
221 false
222 ),
223 emit_obj,
29967ef6 224 bc_cmdline: sess.target.bitcode_llvm_cmdline.clone(),
ba9703b0
XL
225
226 verify_llvm_ir: sess.verify_llvm_ir(),
227 no_prepopulate_passes: sess.opts.cg.no_prepopulate_passes,
29967ef6 228 no_builtins: no_builtins || sess.target.no_builtins,
ba9703b0
XL
229
230 // Exclude metadata and allocator modules from time_passes output,
231 // since they throw off the "LLVM passes" measurement.
232 time_module: if_regular!(true, false),
233
234 // Copy what clang does by turning on loop vectorization at O2 and
235 // slp vectorization at O3.
236 vectorize_loop: !sess.opts.cg.no_vectorize_loops
237 && (sess.opts.optimize == config::OptLevel::Default
238 || sess.opts.optimize == config::OptLevel::Aggressive),
239 vectorize_slp: !sess.opts.cg.no_vectorize_slp
240 && sess.opts.optimize == config::OptLevel::Aggressive,
241
242 // Some targets (namely, NVPTX) interact badly with the
243 // MergeFunctions pass. This is because MergeFunctions can generate
244 // new function calls which may interfere with the target calling
245 // convention; e.g. for the NVPTX target, PTX kernels should not
246 // call other PTX kernels. MergeFunctions can also be configured to
247 // generate aliases instead, but aliases are not supported by some
248 // backends (again, NVPTX). Therefore, allow targets to opt out of
249 // the MergeFunctions pass, but otherwise keep the pass enabled (at
250 // O2 and O3) since it can be useful for reducing code size.
251 merge_functions: match sess
252 .opts
253 .debugging_opts
254 .merge_functions
29967ef6 255 .unwrap_or(sess.target.merge_functions)
ba9703b0
XL
256 {
257 MergeFunctions::Disabled => false,
258 MergeFunctions::Trampolines | MergeFunctions::Aliases => {
259 sess.opts.optimize == config::OptLevel::Default
260 || sess.opts.optimize == config::OptLevel::Aggressive
261 }
262 },
263
264 inline_threshold: sess.opts.cg.inline_threshold,
265 new_llvm_pass_manager: sess.opts.debugging_opts.new_llvm_pass_manager,
f9f354fc 266 emit_lifetime_markers: sess.emit_lifetime_markers(),
ba9703b0 267 }
a1dfa0c6
XL
268 }
269
270 pub fn bitcode_needed(&self) -> bool {
ba9703b0 271 self.emit_bc
ba9703b0
XL
272 || self.emit_obj == EmitObj::Bitcode
273 || self.emit_obj == EmitObj::ObjectCode(BitcodeSection::Full)
a1dfa0c6
XL
274 }
275}
276
a1dfa0c6
XL
277// HACK(eddyb) work around `#[derive]` producing wrong bounds for `Clone`.
278pub struct TargetMachineFactory<B: WriteBackendMethods>(
279 pub Arc<dyn Fn() -> Result<B::TargetMachine, String> + Send + Sync>,
280);
281
282impl<B: WriteBackendMethods> Clone for TargetMachineFactory<B> {
283 fn clone(&self) -> Self {
284 TargetMachineFactory(self.0.clone())
285 }
286}
287
dfeec247
XL
288pub type ExportedSymbols = FxHashMap<CrateNum, Arc<Vec<(String, SymbolExportLevel)>>>;
289
a1dfa0c6
XL
290/// Additional resources used by optimize_and_codegen (not module specific)
291#[derive(Clone)]
292pub struct CodegenContext<B: WriteBackendMethods> {
293 // Resources needed when running LTO
294 pub backend: B,
e74abb32 295 pub prof: SelfProfilerRef,
a1dfa0c6
XL
296 pub lto: Lto,
297 pub no_landing_pads: bool,
298 pub save_temps: bool,
299 pub fewer_names: bool,
300 pub exported_symbols: Option<Arc<ExportedSymbols>>,
301 pub opts: Arc<config::Options>,
f9f354fc 302 pub crate_types: Vec<CrateType>,
a1dfa0c6
XL
303 pub each_linked_rlib_for_lto: Vec<(CrateNum, PathBuf)>,
304 pub output_filenames: Arc<OutputFilenames>,
305 pub regular_module_config: Arc<ModuleConfig>,
306 pub metadata_module_config: Arc<ModuleConfig>,
307 pub allocator_module_config: Arc<ModuleConfig>,
308 pub tm_factory: TargetMachineFactory<B>,
309 pub msvc_imps_needed: bool,
29967ef6 310 pub target_pointer_width: u32,
48663c56 311 pub target_arch: String,
a1dfa0c6
XL
312 pub debuginfo: config::DebugInfo,
313
314 // Number of cgus excluding the allocator/metadata modules
315 pub total_cgus: usize,
316 // Handler to use for diagnostics produced during codegen.
317 pub diag_emitter: SharedEmitter,
a1dfa0c6
XL
318 // LLVM optimizations for which we want to print remarks.
319 pub remark: Passes,
320 // Worker thread number
321 pub worker: usize,
322 // The incremental compilation session directory, or None if we are not
323 // compiling incrementally
324 pub incr_comp_session_dir: Option<PathBuf>,
325 // Used to update CGU re-use information during the thinlto phase.
326 pub cgu_reuse_tracker: CguReuseTracker,
327 // Channel back to the main control thread to send messages to
328 pub coordinator_send: Sender<Box<dyn Any + Send>>,
a1dfa0c6
XL
329}
330
331impl<B: WriteBackendMethods> CodegenContext<B> {
332 pub fn create_diag_handler(&self) -> Handler {
532ac7d7 333 Handler::with_emitter(true, None, Box::new(self.diag_emitter.clone()))
a1dfa0c6
XL
334 }
335
336 pub fn config(&self, kind: ModuleKind) -> &ModuleConfig {
337 match kind {
338 ModuleKind::Regular => &self.regular_module_config,
339 ModuleKind::Metadata => &self.metadata_module_config,
340 ModuleKind::Allocator => &self.allocator_module_config,
341 }
342 }
343}
344
345fn generate_lto_work<B: ExtraBackendMethods>(
346 cgcx: &CodegenContext<B>,
9fa01778 347 needs_fat_lto: Vec<FatLTOInput<B>>,
0731742a 348 needs_thin_lto: Vec<(String, B::ThinBuffer)>,
dfeec247 349 import_only_modules: Vec<(SerializedModule<B::ModuleBuffer>, WorkProduct)>,
a1dfa0c6 350) -> Vec<(WorkItem<B>, u64)> {
e74abb32 351 let _prof_timer = cgcx.prof.generic_activity("codegen_generate_lto_work");
a1dfa0c6 352
0731742a
XL
353 let (lto_modules, copy_jobs) = if !needs_fat_lto.is_empty() {
354 assert!(needs_thin_lto.is_empty());
dfeec247
XL
355 let lto_module =
356 B::run_fat_lto(cgcx, needs_fat_lto, import_only_modules).unwrap_or_else(|e| e.raise());
0731742a
XL
357 (vec![lto_module], vec![])
358 } else {
359 assert!(needs_fat_lto.is_empty());
dfeec247 360 B::run_thin_lto(cgcx, needs_thin_lto, import_only_modules).unwrap_or_else(|e| e.raise())
0731742a
XL
361 };
362
ba9703b0 363 lto_modules
dfeec247
XL
364 .into_iter()
365 .map(|module| {
366 let cost = module.cost();
367 (WorkItem::LTO(module), cost)
368 })
369 .chain(copy_jobs.into_iter().map(|wp| {
370 (
371 WorkItem::CopyPostLtoArtifacts(CachedModuleCodegen {
372 name: wp.cgu_name.clone(),
373 source: wp,
374 }),
375 0,
376 )
377 }))
ba9703b0 378 .collect()
a1dfa0c6
XL
379}
380
381pub struct CompiledModules {
382 pub modules: Vec<CompiledModule>,
48663c56 383 pub metadata_module: Option<CompiledModule>,
a1dfa0c6
XL
384 pub allocator_module: Option<CompiledModule>,
385}
386
f9f354fc
XL
387fn need_bitcode_in_object(sess: &Session) -> bool {
388 let requested_for_rlib = sess.opts.cg.embed_bitcode
389 && sess.crate_types().contains(&CrateType::Rlib)
390 && sess.opts.output_types.contains_key(&OutputType::Exe);
29967ef6 391 let forced_by_target = sess.target.forces_embed_bitcode;
f9f354fc 392 requested_for_rlib || forced_by_target
a1dfa0c6
XL
393}
394
9fa01778 395fn need_pre_lto_bitcode_for_incr_comp(sess: &Session) -> bool {
a1dfa0c6 396 if sess.opts.incremental.is_none() {
dfeec247 397 return false;
a1dfa0c6
XL
398 }
399
400 match sess.lto() {
a1dfa0c6 401 Lto::No => false,
dfeec247 402 Lto::Fat | Lto::Thin | Lto::ThinLocal => true,
a1dfa0c6
XL
403 }
404}
405
406pub fn start_async_codegen<B: ExtraBackendMethods>(
407 backend: B,
dc9dc135 408 tcx: TyCtxt<'_>,
a1dfa0c6 409 metadata: EncodedMetadata,
dc9dc135 410 total_cgus: usize,
a1dfa0c6 411) -> OngoingCodegen<B> {
e74abb32 412 let (coordinator_send, coordinator_receive) = channel();
a1dfa0c6 413 let sess = tcx.sess;
e74abb32 414
a1dfa0c6 415 let crate_name = tcx.crate_name(LOCAL_CRATE);
3dfed10e 416 let no_builtins = tcx.sess.contains_name(&tcx.hir().krate().item.attrs, sym::no_builtins);
f9f354fc 417 let is_compiler_builtins =
3dfed10e
XL
418 tcx.sess.contains_name(&tcx.hir().krate().item.attrs, sym::compiler_builtins);
419 let subsystem = tcx
420 .sess
421 .first_attr_value_str_by_name(&tcx.hir().krate().item.attrs, sym::windows_subsystem);
a1dfa0c6 422 let windows_subsystem = subsystem.map(|subsystem| {
48663c56 423 if subsystem != sym::windows && subsystem != sym::console {
dfeec247
XL
424 tcx.sess.fatal(&format!(
425 "invalid windows subsystem `{}`, only \
a1dfa0c6 426 `windows` and `console` are allowed",
dfeec247
XL
427 subsystem
428 ));
a1dfa0c6
XL
429 }
430 subsystem.to_string()
431 });
432
433 let linker_info = LinkerInfo::new(tcx);
434 let crate_info = CrateInfo::new(tcx);
435
f9f354fc
XL
436 let regular_config =
437 ModuleConfig::new(ModuleKind::Regular, sess, no_builtins, is_compiler_builtins);
438 let metadata_config =
439 ModuleConfig::new(ModuleKind::Metadata, sess, no_builtins, is_compiler_builtins);
440 let allocator_config =
441 ModuleConfig::new(ModuleKind::Allocator, sess, no_builtins, is_compiler_builtins);
a1dfa0c6
XL
442
443 let (shared_emitter, shared_emitter_main) = SharedEmitter::new();
444 let (codegen_worker_send, codegen_worker_receive) = channel();
445
dfeec247
XL
446 let coordinator_thread = start_executing_work(
447 backend.clone(),
448 tcx,
449 &crate_info,
450 shared_emitter,
451 codegen_worker_send,
452 coordinator_receive,
453 total_cgus,
454 sess.jobserver.clone(),
ba9703b0 455 Arc::new(regular_config),
dfeec247
XL
456 Arc::new(metadata_config),
457 Arc::new(allocator_config),
458 coordinator_send.clone(),
459 );
a1dfa0c6
XL
460
461 OngoingCodegen {
462 backend,
463 crate_name,
a1dfa0c6
XL
464 metadata,
465 windows_subsystem,
466 linker_info,
467 crate_info,
468
e74abb32 469 coordinator_send,
a1dfa0c6
XL
470 codegen_worker_receive,
471 shared_emitter_main,
472 future: coordinator_thread,
473 output_filenames: tcx.output_filenames(LOCAL_CRATE),
474 }
475}
476
477fn copy_all_cgu_workproducts_to_incr_comp_cache_dir(
478 sess: &Session,
479 compiled_modules: &CompiledModules,
480) -> FxHashMap<WorkProductId, WorkProduct> {
481 let mut work_products = FxHashMap::default();
482
483 if sess.opts.incremental.is_none() {
484 return work_products;
485 }
486
f9f354fc 487 let _timer = sess.timer("copy_all_cgu_workproducts_to_incr_comp_cache_dir");
dfeec247 488
a1dfa0c6 489 for module in compiled_modules.modules.iter().filter(|m| m.kind == ModuleKind::Regular) {
3dfed10e 490 let path = module.object.as_ref().cloned();
a1dfa0c6
XL
491
492 if let Some((id, product)) =
f9f354fc 493 copy_cgu_workproduct_to_incr_comp_cache_dir(sess, &module.name, &path)
dfeec247 494 {
a1dfa0c6
XL
495 work_products.insert(id, product);
496 }
497 }
498
499 work_products
500}
501
dfeec247
XL
502fn produce_final_output_artifacts(
503 sess: &Session,
504 compiled_modules: &CompiledModules,
505 crate_output: &OutputFilenames,
506) {
a1dfa0c6
XL
507 let mut user_wants_bitcode = false;
508 let mut user_wants_objects = false;
509
510 // Produce final compile outputs.
511 let copy_gracefully = |from: &Path, to: &Path| {
512 if let Err(e) = fs::copy(from, to) {
513 sess.err(&format!("could not copy {:?} to {:?}: {}", from, to, e));
514 }
515 };
516
dfeec247 517 let copy_if_one_unit = |output_type: OutputType, keep_numbered: bool| {
a1dfa0c6
XL
518 if compiled_modules.modules.len() == 1 {
519 // 1) Only one codegen unit. In this case it's no difficulty
520 // to copy `foo.0.x` to `foo.x`.
521 let module_name = Some(&compiled_modules.modules[0].name[..]);
522 let path = crate_output.temp_path(output_type, module_name);
dfeec247 523 copy_gracefully(&path, &crate_output.path(output_type));
a1dfa0c6
XL
524 if !sess.opts.cg.save_temps && !keep_numbered {
525 // The user just wants `foo.x`, not `foo.#module-name#.x`.
526 remove(sess, &path);
527 }
528 } else {
dfeec247
XL
529 let ext = crate_output
530 .temp_path(output_type, None)
531 .extension()
532 .unwrap()
533 .to_str()
534 .unwrap()
535 .to_owned();
a1dfa0c6
XL
536
537 if crate_output.outputs.contains_key(&output_type) {
538 // 2) Multiple codegen units, with `--emit foo=some_name`. We have
539 // no good solution for this case, so warn the user.
dfeec247
XL
540 sess.warn(&format!(
541 "ignoring emit path because multiple .{} files \
542 were produced",
543 ext
544 ));
a1dfa0c6
XL
545 } else if crate_output.single_output_file.is_some() {
546 // 3) Multiple codegen units, with `-o some_name`. We have
547 // no good solution for this case, so warn the user.
dfeec247
XL
548 sess.warn(&format!(
549 "ignoring -o because multiple .{} files \
550 were produced",
551 ext
552 ));
a1dfa0c6
XL
553 } else {
554 // 4) Multiple codegen units, but no explicit name. We
555 // just leave the `foo.0.x` files in place.
556 // (We don't have to do any work in this case.)
557 }
558 }
559 };
560
561 // Flag to indicate whether the user explicitly requested bitcode.
562 // Otherwise, we produced it only as a temporary output, and will need
563 // to get rid of it.
564 for output_type in crate_output.outputs.keys() {
565 match *output_type {
566 OutputType::Bitcode => {
567 user_wants_bitcode = true;
568 // Copy to .bc, but always keep the .0.bc. There is a later
569 // check to figure out if we should delete .0.bc files, or keep
570 // them for making an rlib.
571 copy_if_one_unit(OutputType::Bitcode, true);
572 }
573 OutputType::LlvmAssembly => {
574 copy_if_one_unit(OutputType::LlvmAssembly, false);
575 }
576 OutputType::Assembly => {
577 copy_if_one_unit(OutputType::Assembly, false);
578 }
579 OutputType::Object => {
580 user_wants_objects = true;
581 copy_if_one_unit(OutputType::Object, true);
582 }
dfeec247 583 OutputType::Mir | OutputType::Metadata | OutputType::Exe | OutputType::DepInfo => {}
a1dfa0c6
XL
584 }
585 }
586
587 // Clean up unwanted temporary files.
588
589 // We create the following files by default:
590 // - #crate#.#module-name#.bc
591 // - #crate#.#module-name#.o
592 // - #crate#.crate.metadata.bc
593 // - #crate#.crate.metadata.o
594 // - #crate#.o (linked from crate.##.o)
595 // - #crate#.bc (copied from crate.##.bc)
596 // We may create additional files if requested by the user (through
597 // `-C save-temps` or `--emit=` flags).
598
599 if !sess.opts.cg.save_temps {
600 // Remove the temporary .#module-name#.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.
604
605 // Specific rules for keeping .#module-name#.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#.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#.bc.
612 // If you change how this works, also update back::link::link_rlib,
613 // where .#module-name#.bc files are (maybe) deleted after making an
614 // rlib.
615 let needs_crate_object = crate_output.outputs.contains_key(&OutputType::Exe);
616
617 let keep_numbered_bitcode = user_wants_bitcode && sess.codegen_units() > 1;
618
dfeec247
XL
619 let keep_numbered_objects =
620 needs_crate_object || (user_wants_objects && sess.codegen_units() > 1);
a1dfa0c6
XL
621
622 for module in compiled_modules.modules.iter() {
623 if let Some(ref path) = module.object {
624 if !keep_numbered_objects {
625 remove(sess, path);
626 }
627 }
628
629 if let Some(ref path) = module.bytecode {
630 if !keep_numbered_bitcode {
631 remove(sess, path);
632 }
633 }
634 }
635
636 if !user_wants_bitcode {
48663c56
XL
637 if let Some(ref metadata_module) = compiled_modules.metadata_module {
638 if let Some(ref path) = metadata_module.bytecode {
639 remove(sess, &path);
640 }
a1dfa0c6
XL
641 }
642
643 if let Some(ref allocator_module) = compiled_modules.allocator_module {
644 if let Some(ref path) = allocator_module.bytecode {
645 remove(sess, path);
646 }
647 }
648 }
649 }
650
651 // We leave the following files around by default:
652 // - #crate#.o
653 // - #crate#.crate.metadata.o
654 // - #crate#.bc
655 // These are used in linking steps and will be cleaned up afterward.
656}
657
a1dfa0c6
XL
658pub enum WorkItem<B: WriteBackendMethods> {
659 /// Optimize a newly codegened, totally unoptimized module.
660 Optimize(ModuleCodegen<B::Module>),
661 /// Copy the post-LTO artifacts from the incremental cache to the output
662 /// directory.
663 CopyPostLtoArtifacts(CachedModuleCodegen),
9fa01778 664 /// Performs (Thin)LTO on the given module.
a1dfa0c6
XL
665 LTO(lto::LtoModuleCodegen<B>),
666}
667
668impl<B: WriteBackendMethods> WorkItem<B> {
669 pub fn module_kind(&self) -> ModuleKind {
670 match *self {
671 WorkItem::Optimize(ref m) => m.kind,
dfeec247 672 WorkItem::CopyPostLtoArtifacts(_) | WorkItem::LTO(_) => ModuleKind::Regular,
a1dfa0c6
XL
673 }
674 }
675
74b04a01 676 fn start_profiling<'a>(&self, cgcx: &'a CodegenContext<B>) -> TimingGuard<'a> {
a1dfa0c6 677 match *self {
74b04a01
XL
678 WorkItem::Optimize(ref m) => {
679 cgcx.prof.generic_activity_with_arg("codegen_module_optimize", &m.name[..])
680 }
681 WorkItem::CopyPostLtoArtifacts(ref m) => cgcx
682 .prof
683 .generic_activity_with_arg("codegen_copy_artifacts_from_incr_cache", &m.name[..]),
684 WorkItem::LTO(ref m) => {
685 cgcx.prof.generic_activity_with_arg("codegen_module_perform_lto", m.name())
686 }
a1dfa0c6
XL
687 }
688 }
689}
690
0731742a 691enum WorkItemResult<B: WriteBackendMethods> {
a1dfa0c6 692 Compiled(CompiledModule),
1b1a35ee 693 NeedsLink(ModuleCodegen<B::Module>),
9fa01778 694 NeedsFatLTO(FatLTOInput<B>),
0731742a 695 NeedsThinLTO(String, B::ThinBuffer),
a1dfa0c6
XL
696}
697
9fa01778 698pub enum FatLTOInput<B: WriteBackendMethods> {
dfeec247 699 Serialized { name: String, buffer: B::ModuleBuffer },
9fa01778
XL
700 InMemory(ModuleCodegen<B::Module>),
701}
702
a1dfa0c6
XL
703fn execute_work_item<B: ExtraBackendMethods>(
704 cgcx: &CodegenContext<B>,
705 work_item: WorkItem<B>,
0731742a 706) -> Result<WorkItemResult<B>, FatalError> {
a1dfa0c6
XL
707 let module_config = cgcx.config(work_item.module_kind());
708
709 match work_item {
dfeec247 710 WorkItem::Optimize(module) => execute_optimize_work_item(cgcx, module, module_config),
a1dfa0c6 711 WorkItem::CopyPostLtoArtifacts(module) => {
532ac7d7 712 execute_copy_from_cache_work_item(cgcx, module, module_config)
a1dfa0c6 713 }
dfeec247 714 WorkItem::LTO(module) => execute_lto_work_item(cgcx, module, module_config),
a1dfa0c6
XL
715 }
716}
717
74b04a01 718// Actual LTO type we end up choosing based on multiple factors.
f9f354fc 719pub enum ComputedLtoType {
0731742a
XL
720 No,
721 Thin,
722 Fat,
723}
724
f9f354fc
XL
725pub fn compute_per_cgu_lto_type(
726 sess_lto: &Lto,
727 opts: &config::Options,
728 sess_crate_types: &[CrateType],
729 module_kind: ModuleKind,
730) -> ComputedLtoType {
731 // Metadata modules never participate in LTO regardless of the lto
732 // settings.
733 if module_kind == ModuleKind::Metadata {
734 return ComputedLtoType::No;
a1dfa0c6
XL
735 }
736
0731742a
XL
737 // If the linker does LTO, we don't have to do it. Note that we
738 // keep doing full LTO, if it is requested, as not to break the
739 // assumption that the output will be a single module.
f9f354fc 740 let linker_does_lto = opts.cg.linker_plugin_lto.enabled();
a1dfa0c6 741
0731742a
XL
742 // When we're automatically doing ThinLTO for multi-codegen-unit
743 // builds we don't actually want to LTO the allocator modules if
744 // it shows up. This is due to various linker shenanigans that
745 // we'll encounter later.
f9f354fc 746 let is_allocator = module_kind == ModuleKind::Allocator;
a1dfa0c6 747
0731742a
XL
748 // We ignore a request for full crate grath LTO if the cate type
749 // is only an rlib, as there is no full crate graph to process,
750 // that'll happen later.
751 //
752 // This use case currently comes up primarily for targets that
753 // require LTO so the request for LTO is always unconditionally
754 // passed down to the backend, but we don't actually want to do
755 // anything about it yet until we've got a final product.
f9f354fc 756 let is_rlib = sess_crate_types.len() == 1 && sess_crate_types[0] == CrateType::Rlib;
a1dfa0c6 757
f9f354fc
XL
758 match sess_lto {
759 Lto::ThinLocal if !linker_does_lto && !is_allocator => ComputedLtoType::Thin,
760 Lto::Thin if !linker_does_lto && !is_rlib => ComputedLtoType::Thin,
761 Lto::Fat if !is_rlib => ComputedLtoType::Fat,
762 _ => ComputedLtoType::No,
763 }
764}
765
766fn execute_optimize_work_item<B: ExtraBackendMethods>(
767 cgcx: &CodegenContext<B>,
768 module: ModuleCodegen<B::Module>,
769 module_config: &ModuleConfig,
770) -> Result<WorkItemResult<B>, FatalError> {
771 let diag_handler = cgcx.create_diag_handler();
772
773 unsafe {
774 B::optimize(cgcx, &diag_handler, &module, module_config)?;
775 }
776
777 // After we've done the initial round of optimizations we need to
778 // decide whether to synchronously codegen this module or ship it
779 // back to the coordinator thread for further LTO processing (which
780 // has to wait for all the initial modules to be optimized).
781
782 let lto_type = compute_per_cgu_lto_type(&cgcx.lto, &cgcx.opts, &cgcx.crate_types, module.kind);
0731742a 783
9fa01778
XL
784 // If we're doing some form of incremental LTO then we need to be sure to
785 // save our module to disk first.
786 let bitcode = if cgcx.config(module.kind).emit_pre_lto_bc {
787 let filename = pre_lto_bitcode_filename(&module.name);
788 cgcx.incr_comp_session_dir.as_ref().map(|path| path.join(&filename))
789 } else {
790 None
791 };
792
1b1a35ee
XL
793 match lto_type {
794 ComputedLtoType::No => finish_intra_module_work(cgcx, module, module_config),
0731742a 795 ComputedLtoType::Thin => {
9fa01778
XL
796 let (name, thin_buffer) = B::prepare_thin(module);
797 if let Some(path) = bitcode {
798 fs::write(&path, thin_buffer.data()).unwrap_or_else(|e| {
dfeec247 799 panic!("Error writing pre-lto-bitcode file `{}`: {}", path.display(), e);
9fa01778
XL
800 });
801 }
1b1a35ee 802 Ok(WorkItemResult::NeedsThinLTO(name, thin_buffer))
0731742a 803 }
dfeec247
XL
804 ComputedLtoType::Fat => match bitcode {
805 Some(path) => {
806 let (name, buffer) = B::serialize_module(module);
807 fs::write(&path, buffer.data()).unwrap_or_else(|e| {
808 panic!("Error writing pre-lto-bitcode file `{}`: {}", path.display(), e);
809 });
1b1a35ee 810 Ok(WorkItemResult::NeedsFatLTO(FatLTOInput::Serialized { name, buffer }))
9fa01778 811 }
1b1a35ee 812 None => Ok(WorkItemResult::NeedsFatLTO(FatLTOInput::InMemory(module))),
dfeec247 813 },
1b1a35ee 814 }
a1dfa0c6
XL
815}
816
817fn execute_copy_from_cache_work_item<B: ExtraBackendMethods>(
818 cgcx: &CodegenContext<B>,
819 module: CachedModuleCodegen,
820 module_config: &ModuleConfig,
0731742a 821) -> Result<WorkItemResult<B>, FatalError> {
dfeec247 822 let incr_comp_session_dir = cgcx.incr_comp_session_dir.as_ref().unwrap();
a1dfa0c6 823 let mut object = None;
f9f354fc
XL
824 if let Some(saved_file) = module.source.saved_file {
825 let obj_out = cgcx.output_filenames.temp_path(OutputType::Object, Some(&module.name));
826 object = Some(obj_out.clone());
dfeec247
XL
827 let source_file = in_incr_comp_dir(&incr_comp_session_dir, &saved_file);
828 debug!(
829 "copying pre-existing module `{}` from {:?} to {}",
830 module.name,
831 source_file,
832 obj_out.display()
833 );
a1dfa0c6
XL
834 if let Err(err) = link_or_copy(&source_file, &obj_out) {
835 let diag_handler = cgcx.create_diag_handler();
dfeec247
XL
836 diag_handler.err(&format!(
837 "unable to copy {} to {}: {}",
838 source_file.display(),
839 obj_out.display(),
840 err
841 ));
a1dfa0c6
XL
842 }
843 }
844
ba9703b0 845 assert_eq!(object.is_some(), module_config.emit_obj != EmitObj::None);
a1dfa0c6
XL
846
847 Ok(WorkItemResult::Compiled(CompiledModule {
848 name: module.name,
849 kind: ModuleKind::Regular,
850 object,
f9f354fc 851 bytecode: None,
a1dfa0c6
XL
852 }))
853}
854
855fn execute_lto_work_item<B: ExtraBackendMethods>(
856 cgcx: &CodegenContext<B>,
857 mut module: lto::LtoModuleCodegen<B>,
858 module_config: &ModuleConfig,
1b1a35ee
XL
859) -> Result<WorkItemResult<B>, FatalError> {
860 let module = unsafe { module.optimize(cgcx)? };
861 finish_intra_module_work(cgcx, module, module_config)
862}
863
864fn finish_intra_module_work<B: ExtraBackendMethods>(
865 cgcx: &CodegenContext<B>,
866 module: ModuleCodegen<B::Module>,
867 module_config: &ModuleConfig,
0731742a 868) -> Result<WorkItemResult<B>, FatalError> {
a1dfa0c6
XL
869 let diag_handler = cgcx.create_diag_handler();
870
1b1a35ee
XL
871 if !cgcx.opts.debugging_opts.combine_cgu
872 || module.kind == ModuleKind::Metadata
873 || module.kind == ModuleKind::Allocator
874 {
875 let module = unsafe { B::codegen(cgcx, &diag_handler, module, module_config)? };
a1dfa0c6 876 Ok(WorkItemResult::Compiled(module))
1b1a35ee
XL
877 } else {
878 Ok(WorkItemResult::NeedsLink(module))
a1dfa0c6
XL
879 }
880}
881
882pub enum Message<B: WriteBackendMethods> {
883 Token(io::Result<Acquired>),
0731742a 884 NeedsFatLTO {
9fa01778 885 result: FatLTOInput<B>,
a1dfa0c6
XL
886 worker_id: usize,
887 },
0731742a
XL
888 NeedsThinLTO {
889 name: String,
890 thin_buffer: B::ThinBuffer,
891 worker_id: usize,
892 },
1b1a35ee
XL
893 NeedsLink {
894 module: ModuleCodegen<B::Module>,
895 worker_id: usize,
896 },
a1dfa0c6 897 Done {
dfeec247 898 result: Result<CompiledModule, Option<WorkerFatalError>>,
a1dfa0c6
XL
899 worker_id: usize,
900 },
901 CodegenDone {
902 llvm_work_item: WorkItem<B>,
903 cost: u64,
904 },
905 AddImportOnlyModule {
906 module_data: SerializedModule<B::ModuleBuffer>,
907 work_product: WorkProduct,
908 },
909 CodegenComplete,
910 CodegenItem,
911 CodegenAborted,
912}
913
914struct Diagnostic {
915 msg: String,
916 code: Option<DiagnosticId>,
917 lvl: Level,
918}
919
920#[derive(PartialEq, Clone, Copy, Debug)]
921enum MainThreadWorkerState {
922 Idle,
923 Codegenning,
924 LLVMing,
925}
926
927fn start_executing_work<B: ExtraBackendMethods>(
928 backend: B,
dc9dc135 929 tcx: TyCtxt<'_>,
a1dfa0c6
XL
930 crate_info: &CrateInfo,
931 shared_emitter: SharedEmitter,
932 codegen_worker_send: Sender<Message<B>>,
933 coordinator_receive: Receiver<Box<dyn Any + Send>>,
934 total_cgus: usize,
935 jobserver: Client,
ba9703b0 936 regular_config: Arc<ModuleConfig>,
a1dfa0c6 937 metadata_config: Arc<ModuleConfig>,
dc9dc135 938 allocator_config: Arc<ModuleConfig>,
e74abb32 939 tx_to_llvm_workers: Sender<Box<dyn Any + Send>>,
a1dfa0c6 940) -> thread::JoinHandle<Result<CompiledModules, ()>> {
e74abb32 941 let coordinator_send = tx_to_llvm_workers;
a1dfa0c6
XL
942 let sess = tcx.sess;
943
944 // Compute the set of symbols we need to retain when doing LTO (if we need to)
945 let exported_symbols = {
946 let mut exported_symbols = FxHashMap::default();
947
948 let copy_symbols = |cnum| {
dfeec247
XL
949 let symbols = tcx
950 .exported_symbols(cnum)
951 .iter()
952 .map(|&(s, lvl)| (symbol_name_for_instance_in_crate(tcx, s, cnum), lvl))
953 .collect();
a1dfa0c6
XL
954 Arc::new(symbols)
955 };
956
957 match sess.lto() {
958 Lto::No => None,
959 Lto::ThinLocal => {
960 exported_symbols.insert(LOCAL_CRATE, copy_symbols(LOCAL_CRATE));
961 Some(Arc::new(exported_symbols))
962 }
963 Lto::Fat | Lto::Thin => {
964 exported_symbols.insert(LOCAL_CRATE, copy_symbols(LOCAL_CRATE));
965 for &cnum in tcx.crates().iter() {
966 exported_symbols.insert(cnum, copy_symbols(cnum));
967 }
968 Some(Arc::new(exported_symbols))
969 }
970 }
971 };
972
973 // First up, convert our jobserver into a helper thread so we can use normal
974 // mpsc channels to manage our messages and such.
975 // After we've requested tokens then we'll, when we can,
976 // get tokens on `coordinator_receive` which will
977 // get managed in the main loop below.
978 let coordinator_send2 = coordinator_send.clone();
dfeec247
XL
979 let helper = jobserver
980 .into_helper_thread(move |token| {
981 drop(coordinator_send2.send(Box::new(Message::Token::<B>(token))));
982 })
983 .expect("failed to spawn helper thread");
a1dfa0c6
XL
984
985 let mut each_linked_rlib_for_lto = Vec::new();
e74abb32 986 drop(link::each_linked_rlib(crate_info, &mut |cnum, path| {
a1dfa0c6 987 if link::ignored_for_lto(sess, crate_info, cnum) {
dfeec247 988 return;
a1dfa0c6
XL
989 }
990 each_linked_rlib_for_lto.push((cnum, path.to_path_buf()));
991 }));
992
532ac7d7 993 let ol = if tcx.sess.opts.debugging_opts.no_codegen
dfeec247
XL
994 || !tcx.sess.opts.output_types.should_codegen()
995 {
532ac7d7
XL
996 // If we know that we won’t be doing codegen, create target machines without optimisation.
997 config::OptLevel::No
998 } else {
999 tcx.backend_optimization_level(LOCAL_CRATE)
1000 };
a1dfa0c6
XL
1001 let cgcx = CodegenContext::<B> {
1002 backend: backend.clone(),
f9f354fc 1003 crate_types: sess.crate_types().to_vec(),
a1dfa0c6
XL
1004 each_linked_rlib_for_lto,
1005 lto: sess.lto(),
f9f354fc 1006 no_landing_pads: sess.panic_strategy() == PanicStrategy::Abort,
a1dfa0c6
XL
1007 fewer_names: sess.fewer_names(),
1008 save_temps: sess.opts.cg.save_temps,
1009 opts: Arc::new(sess.opts.clone()),
e74abb32 1010 prof: sess.prof.clone(),
a1dfa0c6 1011 exported_symbols,
a1dfa0c6
XL
1012 remark: sess.opts.cg.remark.clone(),
1013 worker: 0,
1014 incr_comp_session_dir: sess.incr_comp_session_dir_opt().map(|r| r.clone()),
1015 cgu_reuse_tracker: sess.cgu_reuse_tracker.clone(),
1016 coordinator_send,
1017 diag_emitter: shared_emitter.clone(),
a1dfa0c6 1018 output_filenames: tcx.output_filenames(LOCAL_CRATE),
ba9703b0 1019 regular_module_config: regular_config,
a1dfa0c6
XL
1020 metadata_module_config: metadata_config,
1021 allocator_module_config: allocator_config,
f9f354fc 1022 tm_factory: TargetMachineFactory(backend.target_machine_factory(tcx.sess, ol)),
a1dfa0c6
XL
1023 total_cgus,
1024 msvc_imps_needed: msvc_imps_needed(tcx),
29967ef6
XL
1025 target_pointer_width: tcx.sess.target.pointer_width,
1026 target_arch: tcx.sess.target.arch.clone(),
a1dfa0c6 1027 debuginfo: tcx.sess.opts.debuginfo,
a1dfa0c6
XL
1028 };
1029
1030 // This is the "main loop" of parallel work happening for parallel codegen.
1031 // It's here that we manage parallelism, schedule work, and work with
1032 // messages coming from clients.
1033 //
1034 // There are a few environmental pre-conditions that shape how the system
1035 // is set up:
1036 //
1037 // - Error reporting only can happen on the main thread because that's the
1038 // only place where we have access to the compiler `Session`.
1039 // - LLVM work can be done on any thread.
1040 // - Codegen can only happen on the main thread.
1041 // - Each thread doing substantial work most be in possession of a `Token`
1042 // from the `Jobserver`.
1043 // - The compiler process always holds one `Token`. Any additional `Tokens`
1044 // have to be requested from the `Jobserver`.
1045 //
1046 // Error Reporting
1047 // ===============
1048 // The error reporting restriction is handled separately from the rest: We
1049 // set up a `SharedEmitter` the holds an open channel to the main thread.
1050 // When an error occurs on any thread, the shared emitter will send the
1051 // error message to the receiver main thread (`SharedEmitterMain`). The
1052 // main thread will periodically query this error message queue and emit
1053 // any error messages it has received. It might even abort compilation if
1054 // has received a fatal error. In this case we rely on all other threads
1055 // being torn down automatically with the main thread.
1056 // Since the main thread will often be busy doing codegen work, error
1057 // reporting will be somewhat delayed, since the message queue can only be
1058 // checked in between to work packages.
1059 //
1060 // Work Processing Infrastructure
1061 // ==============================
1062 // The work processing infrastructure knows three major actors:
1063 //
1064 // - the coordinator thread,
1065 // - the main thread, and
1066 // - LLVM worker threads
1067 //
1068 // The coordinator thread is running a message loop. It instructs the main
1069 // thread about what work to do when, and it will spawn off LLVM worker
1070 // threads as open LLVM WorkItems become available.
1071 //
1072 // The job of the main thread is to codegen CGUs into LLVM work package
1073 // (since the main thread is the only thread that can do this). The main
1074 // thread will block until it receives a message from the coordinator, upon
1075 // which it will codegen one CGU, send it to the coordinator and block
1076 // again. This way the coordinator can control what the main thread is
1077 // doing.
1078 //
1079 // The coordinator keeps a queue of LLVM WorkItems, and when a `Token` is
1080 // available, it will spawn off a new LLVM worker thread and let it process
1081 // that a WorkItem. When a LLVM worker thread is done with its WorkItem,
1082 // it will just shut down, which also frees all resources associated with
1083 // the given LLVM module, and sends a message to the coordinator that the
1084 // has been completed.
1085 //
1086 // Work Scheduling
1087 // ===============
1088 // The scheduler's goal is to minimize the time it takes to complete all
1089 // work there is, however, we also want to keep memory consumption low
1090 // if possible. These two goals are at odds with each other: If memory
1091 // consumption were not an issue, we could just let the main thread produce
1092 // LLVM WorkItems at full speed, assuring maximal utilization of
1093 // Tokens/LLVM worker threads. However, since codegen usual is faster
1094 // than LLVM processing, the queue of LLVM WorkItems would fill up and each
1095 // WorkItem potentially holds on to a substantial amount of memory.
1096 //
1097 // So the actual goal is to always produce just enough LLVM WorkItems as
1098 // not to starve our LLVM worker threads. That means, once we have enough
1099 // WorkItems in our queue, we can block the main thread, so it does not
1100 // produce more until we need them.
1101 //
1102 // Doing LLVM Work on the Main Thread
1103 // ----------------------------------
1104 // Since the main thread owns the compiler processes implicit `Token`, it is
1105 // wasteful to keep it blocked without doing any work. Therefore, what we do
1106 // in this case is: We spawn off an additional LLVM worker thread that helps
1107 // reduce the queue. The work it is doing corresponds to the implicit
1108 // `Token`. The coordinator will mark the main thread as being busy with
1109 // LLVM work. (The actual work happens on another OS thread but we just care
1110 // about `Tokens`, not actual threads).
1111 //
1112 // When any LLVM worker thread finishes while the main thread is marked as
1113 // "busy with LLVM work", we can do a little switcheroo: We give the Token
1114 // of the just finished thread to the LLVM worker thread that is working on
1115 // behalf of the main thread's implicit Token, thus freeing up the main
1116 // thread again. The coordinator can then again decide what the main thread
1117 // should do. This allows the coordinator to make decisions at more points
1118 // in time.
1119 //
1120 // Striking a Balance between Throughput and Memory Consumption
1121 // ------------------------------------------------------------
1122 // Since our two goals, (1) use as many Tokens as possible and (2) keep
1123 // memory consumption as low as possible, are in conflict with each other,
1124 // we have to find a trade off between them. Right now, the goal is to keep
1125 // all workers busy, which means that no worker should find the queue empty
1126 // when it is ready to start.
1127 // How do we do achieve this? Good question :) We actually never know how
1128 // many `Tokens` are potentially available so it's hard to say how much to
1129 // fill up the queue before switching the main thread to LLVM work. Also we
1130 // currently don't have a means to estimate how long a running LLVM worker
1131 // will still be busy with it's current WorkItem. However, we know the
1132 // maximal count of available Tokens that makes sense (=the number of CPU
1133 // cores), so we can take a conservative guess. The heuristic we use here
1134 // is implemented in the `queue_full_enough()` function.
1135 //
1136 // Some Background on Jobservers
1137 // -----------------------------
1138 // It's worth also touching on the management of parallelism here. We don't
1139 // want to just spawn a thread per work item because while that's optimal
1140 // parallelism it may overload a system with too many threads or violate our
1141 // configuration for the maximum amount of cpu to use for this process. To
1142 // manage this we use the `jobserver` crate.
1143 //
1144 // Job servers are an artifact of GNU make and are used to manage
1145 // parallelism between processes. A jobserver is a glorified IPC semaphore
1146 // basically. Whenever we want to run some work we acquire the semaphore,
1147 // and whenever we're done with that work we release the semaphore. In this
1148 // manner we can ensure that the maximum number of parallel workers is
1149 // capped at any one point in time.
1150 //
1151 // LTO and the coordinator thread
1152 // ------------------------------
1153 //
1154 // The final job the coordinator thread is responsible for is managing LTO
1155 // and how that works. When LTO is requested what we'll to is collect all
1156 // optimized LLVM modules into a local vector on the coordinator. Once all
1157 // modules have been codegened and optimized we hand this to the `lto`
1158 // module for further optimization. The `lto` module will return back a list
1159 // of more modules to work on, which the coordinator will continue to spawn
1160 // work for.
1161 //
1162 // Each LLVM module is automatically sent back to the coordinator for LTO if
1163 // necessary. There's already optimizations in place to avoid sending work
1164 // back to the coordinator if LTO isn't requested.
1165 return thread::spawn(move || {
29967ef6 1166 let max_workers = num_cpus::get();
a1dfa0c6
XL
1167 let mut worker_id_counter = 0;
1168 let mut free_worker_ids = Vec::new();
1169 let mut get_worker_id = |free_worker_ids: &mut Vec<usize>| {
1170 if let Some(id) = free_worker_ids.pop() {
1171 id
1172 } else {
1173 let id = worker_id_counter;
1174 worker_id_counter += 1;
1175 id
1176 }
1177 };
1178
1179 // This is where we collect codegen units that have gone all the way
1180 // through codegen and LLVM.
1181 let mut compiled_modules = vec![];
1182 let mut compiled_metadata_module = None;
1183 let mut compiled_allocator_module = None;
1b1a35ee 1184 let mut needs_link = Vec::new();
0731742a
XL
1185 let mut needs_fat_lto = Vec::new();
1186 let mut needs_thin_lto = Vec::new();
a1dfa0c6
XL
1187 let mut lto_import_only_modules = Vec::new();
1188 let mut started_lto = false;
1189 let mut codegen_aborted = false;
1190
1191 // This flag tracks whether all items have gone through codegens
1192 let mut codegen_done = false;
1193
1194 // This is the queue of LLVM work items that still need processing.
1195 let mut work_items = Vec::<(WorkItem<B>, u64)>::new();
1196
1197 // This are the Jobserver Tokens we currently hold. Does not include
1198 // the implicit Token the compiler process owns no matter what.
1199 let mut tokens = Vec::new();
1200
1201 let mut main_thread_worker_state = MainThreadWorkerState::Idle;
1202 let mut running = 0;
1203
dfeec247
XL
1204 let prof = &cgcx.prof;
1205 let mut llvm_start_time: Option<VerboseTimingGuard<'_>> = None;
a1dfa0c6
XL
1206
1207 // Run the message loop while there's still anything that needs message
1208 // processing. Note that as soon as codegen is aborted we simply want to
1209 // wait for all existing work to finish, so many of the conditions here
1210 // only apply if codegen hasn't been aborted as they represent pending
1211 // work to be done.
dfeec247
XL
1212 while !codegen_done
1213 || running > 0
1214 || (!codegen_aborted
74b04a01
XL
1215 && !(work_items.is_empty()
1216 && needs_fat_lto.is_empty()
1217 && needs_thin_lto.is_empty()
1218 && lto_import_only_modules.is_empty()
1219 && main_thread_worker_state == MainThreadWorkerState::Idle))
a1dfa0c6 1220 {
a1dfa0c6
XL
1221 // While there are still CGUs to be codegened, the coordinator has
1222 // to decide how to utilize the compiler processes implicit Token:
1223 // For codegenning more CGU or for running them through LLVM.
1224 if !codegen_done {
1225 if main_thread_worker_state == MainThreadWorkerState::Idle {
1226 if !queue_full_enough(work_items.len(), running, max_workers) {
1227 // The queue is not full enough, codegen more items:
74b04a01 1228 if codegen_worker_send.send(Message::CodegenItem).is_err() {
a1dfa0c6
XL
1229 panic!("Could not send Message::CodegenItem to main thread")
1230 }
1231 main_thread_worker_state = MainThreadWorkerState::Codegenning;
1232 } else {
1233 // The queue is full enough to not let the worker
1234 // threads starve. Use the implicit Token to do some
1235 // LLVM work too.
dfeec247
XL
1236 let (item, _) =
1237 work_items.pop().expect("queue empty - queue_full_enough() broken?");
a1dfa0c6
XL
1238 let cgcx = CodegenContext {
1239 worker: get_worker_id(&mut free_worker_ids),
dfeec247 1240 ..cgcx.clone()
a1dfa0c6 1241 };
dfeec247
XL
1242 maybe_start_llvm_timer(
1243 prof,
1244 cgcx.config(item.module_kind()),
1245 &mut llvm_start_time,
1246 );
a1dfa0c6
XL
1247 main_thread_worker_state = MainThreadWorkerState::LLVMing;
1248 spawn_work(cgcx, item);
1249 }
1250 }
1251 } else if codegen_aborted {
1252 // don't queue up any more work if codegen was aborted, we're
1253 // just waiting for our existing children to finish
1254 } else {
1255 // If we've finished everything related to normal codegen
1256 // then it must be the case that we've got some LTO work to do.
1257 // Perform the serial work here of figuring out what we're
1258 // going to LTO and then push a bunch of work items onto our
1259 // queue to do LTO
74b04a01 1260 if work_items.is_empty()
dfeec247
XL
1261 && running == 0
1262 && main_thread_worker_state == MainThreadWorkerState::Idle
1263 {
a1dfa0c6 1264 assert!(!started_lto);
a1dfa0c6 1265 started_lto = true;
0731742a 1266
416331ca
XL
1267 let needs_fat_lto = mem::take(&mut needs_fat_lto);
1268 let needs_thin_lto = mem::take(&mut needs_thin_lto);
1269 let import_only_modules = mem::take(&mut lto_import_only_modules);
0731742a 1270
dfeec247
XL
1271 for (work, cost) in
1272 generate_lto_work(&cgcx, needs_fat_lto, needs_thin_lto, import_only_modules)
1273 {
a1dfa0c6
XL
1274 let insertion_index = work_items
1275 .binary_search_by_key(&cost, |&(_, cost)| cost)
1276 .unwrap_or_else(|e| e);
1277 work_items.insert(insertion_index, (work, cost));
1278 if !cgcx.opts.debugging_opts.no_parallel_llvm {
1279 helper.request_token();
1280 }
1281 }
1282 }
1283
1284 // In this branch, we know that everything has been codegened,
1285 // so it's just a matter of determining whether the implicit
1286 // Token is free to use for LLVM work.
1287 match main_thread_worker_state {
1288 MainThreadWorkerState::Idle => {
1289 if let Some((item, _)) = work_items.pop() {
1290 let cgcx = CodegenContext {
1291 worker: get_worker_id(&mut free_worker_ids),
dfeec247 1292 ..cgcx.clone()
a1dfa0c6 1293 };
dfeec247
XL
1294 maybe_start_llvm_timer(
1295 prof,
1296 cgcx.config(item.module_kind()),
1297 &mut llvm_start_time,
1298 );
a1dfa0c6
XL
1299 main_thread_worker_state = MainThreadWorkerState::LLVMing;
1300 spawn_work(cgcx, item);
1301 } else {
1302 // There is no unstarted work, so let the main thread
1303 // take over for a running worker. Otherwise the
1304 // implicit token would just go to waste.
1305 // We reduce the `running` counter by one. The
1306 // `tokens.truncate()` below will take care of
1307 // giving the Token back.
1308 debug_assert!(running > 0);
1309 running -= 1;
1310 main_thread_worker_state = MainThreadWorkerState::LLVMing;
1311 }
1312 }
dfeec247
XL
1313 MainThreadWorkerState::Codegenning => bug!(
1314 "codegen worker should not be codegenning after \
1315 codegen was already completed"
1316 ),
a1dfa0c6
XL
1317 MainThreadWorkerState::LLVMing => {
1318 // Already making good use of that token
1319 }
1320 }
1321 }
1322
1323 // Spin up what work we can, only doing this while we've got available
1324 // parallelism slots and work left to spawn.
74b04a01 1325 while !codegen_aborted && !work_items.is_empty() && running < tokens.len() {
a1dfa0c6
XL
1326 let (item, _) = work_items.pop().unwrap();
1327
dfeec247 1328 maybe_start_llvm_timer(prof, cgcx.config(item.module_kind()), &mut llvm_start_time);
a1dfa0c6 1329
dfeec247
XL
1330 let cgcx =
1331 CodegenContext { worker: get_worker_id(&mut free_worker_ids), ..cgcx.clone() };
a1dfa0c6
XL
1332
1333 spawn_work(cgcx, item);
1334 running += 1;
1335 }
1336
1337 // Relinquish accidentally acquired extra tokens
1338 tokens.truncate(running);
1339
0731742a
XL
1340 // If a thread exits successfully then we drop a token associated
1341 // with that worker and update our `running` count. We may later
1342 // re-acquire a token to continue running more work. We may also not
1343 // actually drop a token here if the worker was running with an
1344 // "ephemeral token"
1345 let mut free_worker = |worker_id| {
1346 if main_thread_worker_state == MainThreadWorkerState::LLVMing {
1347 main_thread_worker_state = MainThreadWorkerState::Idle;
1348 } else {
1349 running -= 1;
1350 }
1351
1352 free_worker_ids.push(worker_id);
1353 };
1354
a1dfa0c6
XL
1355 let msg = coordinator_receive.recv().unwrap();
1356 match *msg.downcast::<Message<B>>().ok().unwrap() {
1357 // Save the token locally and the next turn of the loop will use
1358 // this to spawn a new unit of work, or it may get dropped
1359 // immediately if we have no more work to spawn.
1360 Message::Token(token) => {
1361 match token {
1362 Ok(token) => {
1363 tokens.push(token);
1364
1365 if main_thread_worker_state == MainThreadWorkerState::LLVMing {
1366 // If the main thread token is used for LLVM work
1367 // at the moment, we turn that thread into a regular
1368 // LLVM worker thread, so the main thread is free
1369 // to react to codegen demand.
1370 main_thread_worker_state = MainThreadWorkerState::Idle;
1371 running += 1;
1372 }
1373 }
1374 Err(e) => {
1375 let msg = &format!("failed to acquire jobserver token: {}", e);
1376 shared_emitter.fatal(msg);
1377 // Exit the coordinator thread
1378 panic!("{}", msg)
1379 }
1380 }
1381 }
1382
1383 Message::CodegenDone { llvm_work_item, cost } => {
1384 // We keep the queue sorted by estimated processing cost,
1385 // so that more expensive items are processed earlier. This
1386 // is good for throughput as it gives the main thread more
1387 // time to fill up the queue and it avoids scheduling
1388 // expensive items to the end.
1389 // Note, however, that this is not ideal for memory
1390 // consumption, as LLVM module sizes are not evenly
1391 // distributed.
dfeec247 1392 let insertion_index = work_items.binary_search_by_key(&cost, |&(_, cost)| cost);
a1dfa0c6 1393 let insertion_index = match insertion_index {
dfeec247 1394 Ok(idx) | Err(idx) => idx,
a1dfa0c6
XL
1395 };
1396 work_items.insert(insertion_index, (llvm_work_item, cost));
1397
1398 if !cgcx.opts.debugging_opts.no_parallel_llvm {
1399 helper.request_token();
1400 }
1401 assert!(!codegen_aborted);
dfeec247 1402 assert_eq!(main_thread_worker_state, MainThreadWorkerState::Codegenning);
a1dfa0c6
XL
1403 main_thread_worker_state = MainThreadWorkerState::Idle;
1404 }
1405
1406 Message::CodegenComplete => {
1407 codegen_done = true;
1408 assert!(!codegen_aborted);
dfeec247 1409 assert_eq!(main_thread_worker_state, MainThreadWorkerState::Codegenning);
a1dfa0c6
XL
1410 main_thread_worker_state = MainThreadWorkerState::Idle;
1411 }
1412
1413 // If codegen is aborted that means translation was aborted due
1414 // to some normal-ish compiler error. In this situation we want
1415 // to exit as soon as possible, but we want to make sure all
1416 // existing work has finished. Flag codegen as being done, and
1417 // then conditions above will ensure no more work is spawned but
1418 // we'll keep executing this loop until `running` hits 0.
1419 Message::CodegenAborted => {
1420 assert!(!codegen_aborted);
1421 codegen_done = true;
1422 codegen_aborted = true;
dfeec247 1423 assert_eq!(main_thread_worker_state, MainThreadWorkerState::Codegenning);
a1dfa0c6 1424 }
a1dfa0c6 1425 Message::Done { result: Ok(compiled_module), worker_id } => {
0731742a 1426 free_worker(worker_id);
a1dfa0c6
XL
1427 match compiled_module.kind {
1428 ModuleKind::Regular => {
1429 compiled_modules.push(compiled_module);
1430 }
1431 ModuleKind::Metadata => {
1432 assert!(compiled_metadata_module.is_none());
1433 compiled_metadata_module = Some(compiled_module);
1434 }
1435 ModuleKind::Allocator => {
1436 assert!(compiled_allocator_module.is_none());
1437 compiled_allocator_module = Some(compiled_module);
1438 }
1439 }
1440 }
1b1a35ee
XL
1441 Message::NeedsLink { module, worker_id } => {
1442 free_worker(worker_id);
1443 needs_link.push(module);
1444 }
0731742a 1445 Message::NeedsFatLTO { result, worker_id } => {
a1dfa0c6 1446 assert!(!started_lto);
0731742a
XL
1447 free_worker(worker_id);
1448 needs_fat_lto.push(result);
1449 }
1450 Message::NeedsThinLTO { name, thin_buffer, worker_id } => {
1451 assert!(!started_lto);
1452 free_worker(worker_id);
1453 needs_thin_lto.push((name, thin_buffer));
a1dfa0c6
XL
1454 }
1455 Message::AddImportOnlyModule { module_data, work_product } => {
1456 assert!(!started_lto);
1457 assert!(!codegen_done);
dfeec247 1458 assert_eq!(main_thread_worker_state, MainThreadWorkerState::Codegenning);
a1dfa0c6
XL
1459 lto_import_only_modules.push((module_data, work_product));
1460 main_thread_worker_state = MainThreadWorkerState::Idle;
1461 }
0731742a 1462 // If the thread failed that means it panicked, so we abort immediately.
dfeec247 1463 Message::Done { result: Err(None), worker_id: _ } => {
a1dfa0c6
XL
1464 bug!("worker thread panicked");
1465 }
dfeec247
XL
1466 Message::Done { result: Err(Some(WorkerFatalError)), worker_id: _ } => {
1467 return Err(());
a1dfa0c6 1468 }
dfeec247 1469 Message::CodegenItem => bug!("the coordinator should not receive codegen requests"),
a1dfa0c6
XL
1470 }
1471 }
1472
1b1a35ee
XL
1473 let needs_link = mem::take(&mut needs_link);
1474 if !needs_link.is_empty() {
1475 assert!(compiled_modules.is_empty());
1476 let diag_handler = cgcx.create_diag_handler();
1477 let module = B::run_link(&cgcx, &diag_handler, needs_link).map_err(|_| ())?;
1478 let module = unsafe {
1479 B::codegen(&cgcx, &diag_handler, module, cgcx.config(ModuleKind::Regular))
1480 .map_err(|_| ())?
1481 };
1482 compiled_modules.push(module);
1483 }
1484
dfeec247
XL
1485 // Drop to print timings
1486 drop(llvm_start_time);
a1dfa0c6
XL
1487
1488 // Regardless of what order these modules completed in, report them to
1489 // the backend in the same order every time to ensure that we're handing
1490 // out deterministic results.
1491 compiled_modules.sort_by(|a, b| a.name.cmp(&b.name));
1492
a1dfa0c6
XL
1493 Ok(CompiledModules {
1494 modules: compiled_modules,
1495 metadata_module: compiled_metadata_module,
1496 allocator_module: compiled_allocator_module,
1497 })
1498 });
1499
1500 // A heuristic that determines if we have enough LLVM WorkItems in the
1501 // queue so that the main thread can do LLVM work instead of codegen
dfeec247
XL
1502 fn queue_full_enough(
1503 items_in_queue: usize,
1504 workers_running: usize,
1505 max_workers: usize,
1506 ) -> bool {
a1dfa0c6 1507 // Tune me, plz.
dfeec247 1508 items_in_queue > 0 && items_in_queue >= max_workers.saturating_sub(workers_running / 2)
a1dfa0c6
XL
1509 }
1510
dfeec247
XL
1511 fn maybe_start_llvm_timer<'a>(
1512 prof: &'a SelfProfilerRef,
1513 config: &ModuleConfig,
1514 llvm_start_time: &mut Option<VerboseTimingGuard<'a>>,
1515 ) {
1516 if config.time_module && llvm_start_time.is_none() {
74b04a01 1517 *llvm_start_time = Some(prof.extra_verbose_generic_activity("LLVM_passes", "crate"));
a1dfa0c6
XL
1518 }
1519 }
1520}
1521
dfeec247
XL
1522/// `FatalError` is explicitly not `Send`.
1523#[must_use]
1524pub struct WorkerFatalError;
a1dfa0c6 1525
dfeec247 1526fn spawn_work<B: ExtraBackendMethods>(cgcx: CodegenContext<B>, work: WorkItem<B>) {
a1dfa0c6 1527 thread::spawn(move || {
a1dfa0c6
XL
1528 // Set up a destructor which will fire off a message that we're done as
1529 // we exit.
1530 struct Bomb<B: ExtraBackendMethods> {
1531 coordinator_send: Sender<Box<dyn Any + Send>>,
dfeec247 1532 result: Option<Result<WorkItemResult<B>, FatalError>>,
a1dfa0c6
XL
1533 worker_id: usize,
1534 }
1535 impl<B: ExtraBackendMethods> Drop for Bomb<B> {
1536 fn drop(&mut self) {
1537 let worker_id = self.worker_id;
1538 let msg = match self.result.take() {
dfeec247 1539 Some(Ok(WorkItemResult::Compiled(m))) => {
a1dfa0c6
XL
1540 Message::Done::<B> { result: Ok(m), worker_id }
1541 }
1b1a35ee
XL
1542 Some(Ok(WorkItemResult::NeedsLink(m))) => {
1543 Message::NeedsLink::<B> { module: m, worker_id }
1544 }
dfeec247 1545 Some(Ok(WorkItemResult::NeedsFatLTO(m))) => {
0731742a
XL
1546 Message::NeedsFatLTO::<B> { result: m, worker_id }
1547 }
dfeec247 1548 Some(Ok(WorkItemResult::NeedsThinLTO(name, thin_buffer))) => {
0731742a 1549 Message::NeedsThinLTO::<B> { name, thin_buffer, worker_id }
a1dfa0c6 1550 }
dfeec247
XL
1551 Some(Err(FatalError)) => {
1552 Message::Done::<B> { result: Err(Some(WorkerFatalError)), worker_id }
1553 }
1554 None => Message::Done::<B> { result: Err(None), worker_id },
a1dfa0c6
XL
1555 };
1556 drop(self.coordinator_send.send(Box::new(msg)));
1557 }
1558 }
1559
1560 let mut bomb = Bomb::<B> {
1561 coordinator_send: cgcx.coordinator_send.clone(),
1562 result: None,
1563 worker_id: cgcx.worker,
1564 };
1565
1566 // Execute the work itself, and if it finishes successfully then flag
1567 // ourselves as a success as well.
1568 //
1569 // Note that we ignore any `FatalError` coming out of `execute_work_item`,
1570 // as a diagnostic was already sent off to the main thread - just
1571 // surface that there was an error in this worker.
1572 bomb.result = {
74b04a01 1573 let _prof_timer = work.start_profiling(&cgcx);
dfeec247 1574 Some(execute_work_item(&cgcx, work))
a1dfa0c6
XL
1575 };
1576 });
1577}
1578
a1dfa0c6
XL
1579enum SharedEmitterMessage {
1580 Diagnostic(Diagnostic),
f035d41b 1581 InlineAsmError(u32, String, Level, Option<(String, Vec<InnerSpan>)>),
a1dfa0c6
XL
1582 AbortIfErrors,
1583 Fatal(String),
1584}
1585
1586#[derive(Clone)]
1587pub struct SharedEmitter {
1588 sender: Sender<SharedEmitterMessage>,
1589}
1590
1591pub struct SharedEmitterMain {
1592 receiver: Receiver<SharedEmitterMessage>,
1593}
1594
1595impl SharedEmitter {
1596 pub fn new() -> (SharedEmitter, SharedEmitterMain) {
1597 let (sender, receiver) = channel();
1598
1599 (SharedEmitter { sender }, SharedEmitterMain { receiver })
1600 }
1601
f9f354fc
XL
1602 pub fn inline_asm_error(
1603 &self,
1604 cookie: u32,
1605 msg: String,
f035d41b 1606 level: Level,
f9f354fc
XL
1607 source: Option<(String, Vec<InnerSpan>)>,
1608 ) {
f035d41b 1609 drop(self.sender.send(SharedEmitterMessage::InlineAsmError(cookie, msg, level, source)));
a1dfa0c6
XL
1610 }
1611
1612 pub fn fatal(&self, msg: &str) {
1613 drop(self.sender.send(SharedEmitterMessage::Fatal(msg.to_string())));
1614 }
1615}
1616
1617impl Emitter for SharedEmitter {
e74abb32 1618 fn emit_diagnostic(&mut self, diag: &rustc_errors::Diagnostic) {
a1dfa0c6 1619 drop(self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
e74abb32
XL
1620 msg: diag.message(),
1621 code: diag.code.clone(),
1622 lvl: diag.level,
a1dfa0c6 1623 })));
e74abb32 1624 for child in &diag.children {
a1dfa0c6
XL
1625 drop(self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
1626 msg: child.message(),
1627 code: None,
1628 lvl: child.level,
1629 })));
1630 }
1631 drop(self.sender.send(SharedEmitterMessage::AbortIfErrors));
1632 }
60c5eb7d 1633 fn source_map(&self) -> Option<&Lrc<SourceMap>> {
e74abb32
XL
1634 None
1635 }
a1dfa0c6
XL
1636}
1637
1638impl SharedEmitterMain {
1639 pub fn check(&self, sess: &Session, blocking: bool) {
1640 loop {
1641 let message = if blocking {
1642 match self.receiver.recv() {
1643 Ok(message) => Ok(message),
1644 Err(_) => Err(()),
1645 }
1646 } else {
1647 match self.receiver.try_recv() {
1648 Ok(message) => Ok(message),
1649 Err(_) => Err(()),
1650 }
1651 };
1652
1653 match message {
1654 Ok(SharedEmitterMessage::Diagnostic(diag)) => {
1655 let handler = sess.diagnostic();
e1599b0c
XL
1656 let mut d = rustc_errors::Diagnostic::new(diag.lvl, &diag.msg);
1657 if let Some(code) = diag.code {
1658 d.code(code);
a1dfa0c6 1659 }
e1599b0c 1660 handler.emit_diagnostic(&d);
a1dfa0c6 1661 }
f035d41b 1662 Ok(SharedEmitterMessage::InlineAsmError(cookie, msg, level, source)) => {
f9f354fc
XL
1663 let msg = msg.strip_prefix("error: ").unwrap_or(&msg);
1664
f035d41b
XL
1665 let mut err = match level {
1666 Level::Error => sess.struct_err(&msg),
1667 Level::Warning => sess.struct_warn(&msg),
1668 Level::Note => sess.struct_note_without_error(&msg),
1669 _ => bug!("Invalid inline asm diagnostic level"),
1670 };
1671
f9f354fc 1672 // If the cookie is 0 then we don't have span information.
f035d41b 1673 if cookie != 0 {
f9f354fc
XL
1674 let pos = BytePos::from_u32(cookie);
1675 let span = Span::with_root_ctxt(pos, pos);
f035d41b 1676 err.set_span(span);
f9f354fc
XL
1677 };
1678
1679 // Point to the generated assembly if it is available.
1680 if let Some((buffer, spans)) = source {
1681 let source = sess
1682 .source_map()
1683 .new_source_file(FileName::inline_asm_source_code(&buffer), buffer);
1684 let source_span = Span::with_root_ctxt(source.start_pos, source.end_pos);
1685 let spans: Vec<_> =
1686 spans.iter().map(|sp| source_span.from_inner(*sp)).collect();
1687 err.span_note(spans, "instantiated into assembly here");
1688 }
1689
1690 err.emit();
a1dfa0c6
XL
1691 }
1692 Ok(SharedEmitterMessage::AbortIfErrors) => {
1693 sess.abort_if_errors();
1694 }
1695 Ok(SharedEmitterMessage::Fatal(msg)) => {
1696 sess.fatal(&msg);
1697 }
1698 Err(_) => {
1699 break;
1700 }
1701 }
a1dfa0c6
XL
1702 }
1703 }
1704}
1705
1706pub struct OngoingCodegen<B: ExtraBackendMethods> {
1707 pub backend: B,
1708 pub crate_name: Symbol,
a1dfa0c6
XL
1709 pub metadata: EncodedMetadata,
1710 pub windows_subsystem: Option<String>,
1711 pub linker_info: LinkerInfo,
1712 pub crate_info: CrateInfo,
a1dfa0c6
XL
1713 pub coordinator_send: Sender<Box<dyn Any + Send>>,
1714 pub codegen_worker_receive: Receiver<Message<B>>,
1715 pub shared_emitter_main: SharedEmitterMain,
1716 pub future: thread::JoinHandle<Result<CompiledModules, ()>>,
1717 pub output_filenames: Arc<OutputFilenames>,
1718}
1719
1720impl<B: ExtraBackendMethods> OngoingCodegen<B> {
dfeec247
XL
1721 pub fn join(self, sess: &Session) -> (CodegenResults, FxHashMap<WorkProductId, WorkProduct>) {
1722 let _timer = sess.timer("finish_ongoing_codegen");
1723
a1dfa0c6 1724 self.shared_emitter_main.check(sess, true);
dfeec247
XL
1725 let future = self.future;
1726 let compiled_modules = sess.time("join_worker_thread", || match future.join() {
a1dfa0c6
XL
1727 Ok(Ok(compiled_modules)) => compiled_modules,
1728 Ok(Err(())) => {
1729 sess.abort_if_errors();
1730 panic!("expected abort due to worker thread errors")
dfeec247 1731 }
a1dfa0c6
XL
1732 Err(_) => {
1733 bug!("panic during codegen/LLVM phase");
1734 }
dfeec247 1735 });
a1dfa0c6 1736
60c5eb7d 1737 sess.cgu_reuse_tracker.check_expected_reuse(sess.diagnostic());
a1dfa0c6
XL
1738
1739 sess.abort_if_errors();
1740
a1dfa0c6 1741 let work_products =
dfeec247
XL
1742 copy_all_cgu_workproducts_to_incr_comp_cache_dir(sess, &compiled_modules);
1743 produce_final_output_artifacts(sess, &compiled_modules, &self.output_filenames);
a1dfa0c6
XL
1744
1745 // FIXME: time_llvm_passes support - does this use a global context or
1746 // something?
1747 if sess.codegen_units() == 1 && sess.time_llvm_passes() {
1748 self.backend.print_pass_timings()
1749 }
1750
dfeec247
XL
1751 (
1752 CodegenResults {
1753 crate_name: self.crate_name,
dfeec247
XL
1754 metadata: self.metadata,
1755 windows_subsystem: self.windows_subsystem,
1756 linker_info: self.linker_info,
1757 crate_info: self.crate_info,
1758
1759 modules: compiled_modules.modules,
1760 allocator_module: compiled_modules.allocator_module,
1761 metadata_module: compiled_modules.metadata_module,
1762 },
1763 work_products,
1764 )
a1dfa0c6
XL
1765 }
1766
dc9dc135
XL
1767 pub fn submit_pre_codegened_module_to_llvm(
1768 &self,
1769 tcx: TyCtxt<'_>,
1770 module: ModuleCodegen<B::Module>,
1771 ) {
a1dfa0c6
XL
1772 self.wait_for_signal_to_codegen_item();
1773 self.check_for_errors(tcx.sess);
1774
48663c56 1775 // These are generally cheap and won't throw off scheduling.
a1dfa0c6 1776 let cost = 0;
e74abb32 1777 submit_codegened_module_to_llvm(&self.backend, &self.coordinator_send, module, cost);
a1dfa0c6
XL
1778 }
1779
dc9dc135 1780 pub fn codegen_finished(&self, tcx: TyCtxt<'_>) {
a1dfa0c6
XL
1781 self.wait_for_signal_to_codegen_item();
1782 self.check_for_errors(tcx.sess);
1783 drop(self.coordinator_send.send(Box::new(Message::CodegenComplete::<B>)));
1784 }
1785
9fa01778 1786 /// Consumes this context indicating that codegen was entirely aborted, and
a1dfa0c6
XL
1787 /// we need to exit as quickly as possible.
1788 ///
1789 /// This method blocks the current thread until all worker threads have
1790 /// finished, and all worker threads should have exited or be real close to
1791 /// exiting at this point.
1792 pub fn codegen_aborted(self) {
1793 // Signal to the coordinator it should spawn no more work and start
1794 // shutdown.
1795 drop(self.coordinator_send.send(Box::new(Message::CodegenAborted::<B>)));
1796 drop(self.future.join());
1797 }
1798
1799 pub fn check_for_errors(&self, sess: &Session) {
1800 self.shared_emitter_main.check(sess, false);
1801 }
1802
1803 pub fn wait_for_signal_to_codegen_item(&self) {
1804 match self.codegen_worker_receive.recv() {
1805 Ok(Message::CodegenItem) => {
1806 // Nothing to do
1807 }
1808 Ok(_) => panic!("unexpected message"),
1809 Err(_) => {
1810 // One of the LLVM threads must have panicked, fall through so
1811 // error handling can be reached.
1812 }
1813 }
1814 }
1815}
1816
1817pub fn submit_codegened_module_to_llvm<B: ExtraBackendMethods>(
1818 _backend: &B,
e74abb32 1819 tx_to_llvm_workers: &Sender<Box<dyn Any + Send>>,
a1dfa0c6 1820 module: ModuleCodegen<B::Module>,
dc9dc135 1821 cost: u64,
a1dfa0c6
XL
1822) {
1823 let llvm_work_item = WorkItem::Optimize(module);
dfeec247 1824 drop(tx_to_llvm_workers.send(Box::new(Message::CodegenDone::<B> { llvm_work_item, cost })));
a1dfa0c6
XL
1825}
1826
1827pub fn submit_post_lto_module_to_llvm<B: ExtraBackendMethods>(
1828 _backend: &B,
e74abb32 1829 tx_to_llvm_workers: &Sender<Box<dyn Any + Send>>,
dc9dc135 1830 module: CachedModuleCodegen,
a1dfa0c6
XL
1831) {
1832 let llvm_work_item = WorkItem::CopyPostLtoArtifacts(module);
dfeec247 1833 drop(tx_to_llvm_workers.send(Box::new(Message::CodegenDone::<B> { llvm_work_item, cost: 0 })));
a1dfa0c6
XL
1834}
1835
1836pub fn submit_pre_lto_module_to_llvm<B: ExtraBackendMethods>(
1837 _backend: &B,
dc9dc135 1838 tcx: TyCtxt<'_>,
e74abb32 1839 tx_to_llvm_workers: &Sender<Box<dyn Any + Send>>,
dc9dc135 1840 module: CachedModuleCodegen,
a1dfa0c6
XL
1841) {
1842 let filename = pre_lto_bitcode_filename(&module.name);
1843 let bc_path = in_incr_comp_dir_sess(tcx.sess, &filename);
dfeec247
XL
1844 let file = fs::File::open(&bc_path)
1845 .unwrap_or_else(|e| panic!("failed to open bitcode file `{}`: {}", bc_path.display(), e));
a1dfa0c6
XL
1846
1847 let mmap = unsafe {
1848 memmap::Mmap::map(&file).unwrap_or_else(|e| {
1849 panic!("failed to mmap bitcode file `{}`: {}", bc_path.display(), e)
1850 })
1851 };
1852 // Schedule the module to be loaded
e74abb32 1853 drop(tx_to_llvm_workers.send(Box::new(Message::AddImportOnlyModule::<B> {
a1dfa0c6
XL
1854 module_data: SerializedModule::FromUncompressedFile(mmap),
1855 work_product: module.source,
1856 })));
1857}
1858
1859pub fn pre_lto_bitcode_filename(module_name: &str) -> String {
9fa01778 1860 format!("{}.{}", module_name, PRE_LTO_BC_EXT)
a1dfa0c6
XL
1861}
1862
dc9dc135 1863fn msvc_imps_needed(tcx: TyCtxt<'_>) -> bool {
a1dfa0c6
XL
1864 // This should never be true (because it's not supported). If it is true,
1865 // something is wrong with commandline arg validation.
dfeec247
XL
1866 assert!(
1867 !(tcx.sess.opts.cg.linker_plugin_lto.enabled()
29967ef6 1868 && tcx.sess.target.is_like_windows
dfeec247
XL
1869 && tcx.sess.opts.cg.prefer_dynamic)
1870 );
a1dfa0c6 1871
29967ef6 1872 tcx.sess.target.is_like_windows &&
f9f354fc 1873 tcx.sess.crate_types().iter().any(|ct| *ct == CrateType::Rlib) &&
a1dfa0c6
XL
1874 // ThinLTO can't handle this workaround in all cases, so we don't
1875 // emit the `__imp_` symbols. Instead we make them unnecessary by disallowing
9fa01778
XL
1876 // dynamic linking when linker plugin LTO is enabled.
1877 !tcx.sess.opts.cg.linker_plugin_lto.enabled()
a1dfa0c6 1878}