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