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