]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_ssa/back/write.rs
859dfb99d92b8598306d5af13c6fdfef1c218ed8
[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, Sanitizer, Lto};
16 use rustc::session::Session;
17 use rustc::util::nodemap::FxHashMap;
18 use rustc::hir::def_id::{CrateNum, LOCAL_CRATE};
19 use rustc::ty::TyCtxt;
20 use rustc::util::common::{time_depth, set_time_depth, print_time_passes_entry};
21 use rustc::util::profiling::{ProfileCategory, SelfProfiler};
22 use rustc_fs_util::link_or_copy;
23 use rustc_data_structures::svh::Svh;
24 use rustc_errors::{Handler, Level, DiagnosticBuilder, FatalError, DiagnosticId};
25 use rustc_errors::emitter::{Emitter};
26 use rustc_target::spec::MergeFunctions;
27 use syntax::attr;
28 use syntax::ext::hygiene::Mark;
29 use syntax_pos::MultiSpan;
30 use syntax_pos::symbol::Symbol;
31 use jobserver::{Client, Acquired};
32 use parking_lot::Mutex as PlMutex;
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: Option<String>,
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: None,
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_passes();
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<PlMutex<SelfProfiler>>>,
202     category: ProfileCategory,
203     label: Cow<'static, str>,
204 }
205
206 impl ProfileGenericActivityTimer {
207     pub fn start(
208         profiler: Option<Arc<PlMutex<SelfProfiler>>>,
209         category: ProfileCategory,
210         label: Cow<'static, str>,
211     ) -> ProfileGenericActivityTimer {
212         if let Some(profiler) = &profiler {
213             let mut p = profiler.lock();
214             p.start_activity(category, label.clone());
215         }
216
217         ProfileGenericActivityTimer {
218             profiler,
219             category,
220             label,
221         }
222     }
223 }
224
225 impl Drop for ProfileGenericActivityTimer {
226     fn drop(&mut self) {
227         if let Some(profiler) = &self.profiler {
228             let mut p = profiler.lock();
229             p.end_activity(self.category, self.label.clone());
230         }
231     }
232 }
233
234 /// Additional resources used by optimize_and_codegen (not module specific)
235 #[derive(Clone)]
236 pub struct CodegenContext<B: WriteBackendMethods> {
237     // Resources needed when running LTO
238     pub backend: B,
239     pub time_passes: bool,
240     pub profiler: Option<Arc<PlMutex<SelfProfiler>>>,
241     pub lto: Lto,
242     pub no_landing_pads: bool,
243     pub save_temps: bool,
244     pub fewer_names: bool,
245     pub exported_symbols: Option<Arc<ExportedSymbols>>,
246     pub opts: Arc<config::Options>,
247     pub crate_types: Vec<config::CrateType>,
248     pub each_linked_rlib_for_lto: Vec<(CrateNum, PathBuf)>,
249     pub output_filenames: Arc<OutputFilenames>,
250     pub regular_module_config: Arc<ModuleConfig>,
251     pub metadata_module_config: Arc<ModuleConfig>,
252     pub allocator_module_config: Arc<ModuleConfig>,
253     pub tm_factory: TargetMachineFactory<B>,
254     pub msvc_imps_needed: bool,
255     pub target_pointer_width: String,
256     pub debuginfo: config::DebugInfo,
257
258     // Number of cgus excluding the allocator/metadata modules
259     pub total_cgus: usize,
260     // Handler to use for diagnostics produced during codegen.
261     pub diag_emitter: SharedEmitter,
262     // LLVM passes added by plugins.
263     pub plugin_passes: Vec<String>,
264     // LLVM optimizations for which we want to print remarks.
265     pub remark: Passes,
266     // Worker thread number
267     pub worker: usize,
268     // The incremental compilation session directory, or None if we are not
269     // compiling incrementally
270     pub incr_comp_session_dir: Option<PathBuf>,
271     // Used to update CGU re-use information during the thinlto phase.
272     pub cgu_reuse_tracker: CguReuseTracker,
273     // Channel back to the main control thread to send messages to
274     pub coordinator_send: Sender<Box<dyn Any + Send>>,
275     // The assembler command if no_integrated_as option is enabled, None otherwise
276     pub assembler_cmd: Option<Arc<AssemblerCommand>>
277 }
278
279 impl<B: WriteBackendMethods> CodegenContext<B> {
280     pub fn create_diag_handler(&self) -> Handler {
281         Handler::with_emitter(true, None, Box::new(self.diag_emitter.clone()))
282     }
283
284     pub fn config(&self, kind: ModuleKind) -> &ModuleConfig {
285         match kind {
286             ModuleKind::Regular => &self.regular_module_config,
287             ModuleKind::Metadata => &self.metadata_module_config,
288             ModuleKind::Allocator => &self.allocator_module_config,
289         }
290     }
291
292     #[inline(never)]
293     #[cold]
294     fn profiler_active<F: FnOnce(&mut SelfProfiler) -> ()>(&self, f: F) {
295         match &self.profiler {
296             None => bug!("profiler_active() called but there was no profiler active"),
297             Some(profiler) => {
298                 let mut p = profiler.lock();
299
300                 f(&mut p);
301             }
302         }
303     }
304
305     #[inline(always)]
306     pub fn profile<F: FnOnce(&mut SelfProfiler) -> ()>(&self, f: F) {
307         if unlikely!(self.profiler.is_some()) {
308             self.profiler_active(f)
309         }
310     }
311
312     pub fn profile_activity(
313         &self,
314         category: ProfileCategory,
315         label: impl Into<Cow<'static, str>>,
316     ) -> ProfileGenericActivityTimer {
317         ProfileGenericActivityTimer::start(self.profiler.clone(), category, label.into())
318     }
319 }
320
321 fn generate_lto_work<B: ExtraBackendMethods>(
322     cgcx: &CodegenContext<B>,
323     needs_fat_lto: Vec<FatLTOInput<B>>,
324     needs_thin_lto: Vec<(String, B::ThinBuffer)>,
325     import_only_modules: Vec<(SerializedModule<B::ModuleBuffer>, WorkProduct)>
326 ) -> Vec<(WorkItem<B>, u64)> {
327     cgcx.profile(|p| p.start_activity(ProfileCategory::Linking, "codegen_run_lto"));
328
329     let (lto_modules, copy_jobs) = if !needs_fat_lto.is_empty() {
330         assert!(needs_thin_lto.is_empty());
331         let lto_module = B::run_fat_lto(
332             cgcx,
333             needs_fat_lto,
334             import_only_modules,
335         )
336         .unwrap_or_else(|e| e.raise());
337         (vec![lto_module], vec![])
338     } else {
339         assert!(needs_fat_lto.is_empty());
340         B::run_thin_lto(cgcx, needs_thin_lto, import_only_modules)
341             .unwrap_or_else(|e| e.raise())
342     };
343
344     let result = lto_modules.into_iter().map(|module| {
345         let cost = module.cost();
346         (WorkItem::LTO(module), cost)
347     }).chain(copy_jobs.into_iter().map(|wp| {
348         (WorkItem::CopyPostLtoArtifacts(CachedModuleCodegen {
349             name: wp.cgu_name.clone(),
350             source: wp,
351         }), 0)
352     })).collect();
353
354     cgcx.profile(|p| p.end_activity(ProfileCategory::Linking, "codegen_run_lto"));
355
356     result
357 }
358
359 pub struct CompiledModules {
360     pub modules: Vec<CompiledModule>,
361     pub metadata_module: CompiledModule,
362     pub allocator_module: Option<CompiledModule>,
363 }
364
365 fn need_crate_bitcode_for_rlib(sess: &Session) -> bool {
366     sess.crate_types.borrow().contains(&config::CrateType::Rlib) &&
367     sess.opts.output_types.contains_key(&OutputType::Exe)
368 }
369
370 fn need_pre_lto_bitcode_for_incr_comp(sess: &Session) -> bool {
371     if sess.opts.incremental.is_none() {
372         return false
373     }
374
375     match sess.lto() {
376         Lto::No => false,
377         Lto::Fat |
378         Lto::Thin |
379         Lto::ThinLocal => true,
380     }
381 }
382
383 pub fn start_async_codegen<B: ExtraBackendMethods>(
384     backend: B,
385     tcx: TyCtxt<'_, '_, '_>,
386     metadata: EncodedMetadata,
387     coordinator_receive: Receiver<Box<dyn Any + Send>>,
388     total_cgus: usize
389 ) -> OngoingCodegen<B> {
390     let sess = tcx.sess;
391     let crate_name = tcx.crate_name(LOCAL_CRATE);
392     let crate_hash = tcx.crate_hash(LOCAL_CRATE);
393     let no_builtins = attr::contains_name(&tcx.hir().krate().attrs, "no_builtins");
394     let subsystem = attr::first_attr_value_str_by_name(&tcx.hir().krate().attrs,
395                                                        "windows_subsystem");
396     let windows_subsystem = subsystem.map(|subsystem| {
397         if subsystem != "windows" && subsystem != "console" {
398             tcx.sess.fatal(&format!("invalid windows subsystem `{}`, only \
399                                      `windows` and `console` are allowed",
400                                     subsystem));
401         }
402         subsystem.to_string()
403     });
404
405     let linker_info = LinkerInfo::new(tcx);
406     let crate_info = CrateInfo::new(tcx);
407
408     // Figure out what we actually need to build.
409     let mut modules_config = ModuleConfig::new(sess.opts.cg.passes.clone());
410     let mut metadata_config = ModuleConfig::new(vec![]);
411     let mut allocator_config = ModuleConfig::new(vec![]);
412
413     if let Some(ref sanitizer) = sess.opts.debugging_opts.sanitizer {
414         match *sanitizer {
415             Sanitizer::Address => {
416                 modules_config.passes.push("asan".to_owned());
417                 modules_config.passes.push("asan-module".to_owned());
418             }
419             Sanitizer::Memory => {
420                 modules_config.passes.push("msan".to_owned())
421             }
422             Sanitizer::Thread => {
423                 modules_config.passes.push("tsan".to_owned())
424             }
425             _ => {}
426         }
427     }
428
429     if sess.opts.debugging_opts.profile {
430         modules_config.passes.push("insert-gcov-profiling".to_owned())
431     }
432
433     modules_config.pgo_gen = sess.opts.debugging_opts.pgo_gen.clone();
434     modules_config.pgo_use = sess.opts.debugging_opts.pgo_use.clone();
435
436     modules_config.opt_level = Some(sess.opts.optimize);
437     modules_config.opt_size = Some(sess.opts.optimize);
438
439     // Save all versions of the bytecode if we're saving our temporaries.
440     if sess.opts.cg.save_temps {
441         modules_config.emit_no_opt_bc = true;
442         modules_config.emit_pre_lto_bc = true;
443         modules_config.emit_bc = true;
444         modules_config.emit_lto_bc = true;
445         metadata_config.emit_bc = true;
446         allocator_config.emit_bc = true;
447     }
448
449     // Emit compressed bitcode files for the crate if we're emitting an rlib.
450     // Whenever an rlib is created, the bitcode is inserted into the archive in
451     // order to allow LTO against it.
452     if need_crate_bitcode_for_rlib(sess) {
453         modules_config.emit_bc_compressed = true;
454         allocator_config.emit_bc_compressed = true;
455     }
456
457     modules_config.emit_pre_lto_bc =
458         need_pre_lto_bitcode_for_incr_comp(sess);
459
460     modules_config.no_integrated_as = tcx.sess.opts.cg.no_integrated_as ||
461         tcx.sess.target.target.options.no_integrated_as;
462
463     for output_type in sess.opts.output_types.keys() {
464         match *output_type {
465             OutputType::Bitcode => { modules_config.emit_bc = true; }
466             OutputType::LlvmAssembly => { modules_config.emit_ir = true; }
467             OutputType::Assembly => {
468                 modules_config.emit_asm = true;
469                 // If we're not using the LLVM assembler, this function
470                 // could be invoked specially with output_type_assembly, so
471                 // in this case we still want the metadata object file.
472                 if !sess.opts.output_types.contains_key(&OutputType::Assembly) {
473                     metadata_config.emit_obj = true;
474                     allocator_config.emit_obj = true;
475                 }
476             }
477             OutputType::Object => { modules_config.emit_obj = true; }
478             OutputType::Metadata => { metadata_config.emit_obj = true; }
479             OutputType::Exe => {
480                 modules_config.emit_obj = true;
481                 metadata_config.emit_obj = true;
482                 allocator_config.emit_obj = true;
483             },
484             OutputType::Mir => {}
485             OutputType::DepInfo => {}
486         }
487     }
488
489     modules_config.set_flags(sess, no_builtins);
490     metadata_config.set_flags(sess, no_builtins);
491     allocator_config.set_flags(sess, no_builtins);
492
493     // Exclude metadata and allocator modules from time_passes output, since
494     // they throw off the "LLVM passes" measurement.
495     metadata_config.time_passes = false;
496     allocator_config.time_passes = false;
497
498     let (shared_emitter, shared_emitter_main) = SharedEmitter::new();
499     let (codegen_worker_send, codegen_worker_receive) = channel();
500
501     let coordinator_thread = start_executing_work(backend.clone(),
502                                                   tcx,
503                                                   &crate_info,
504                                                   shared_emitter,
505                                                   codegen_worker_send,
506                                                   coordinator_receive,
507                                                   total_cgus,
508                                                   sess.jobserver.clone(),
509                                                   Arc::new(modules_config),
510                                                   Arc::new(metadata_config),
511                                                   Arc::new(allocator_config));
512
513     OngoingCodegen {
514         backend,
515         crate_name,
516         crate_hash,
517         metadata,
518         windows_subsystem,
519         linker_info,
520         crate_info,
521
522         coordinator_send: tcx.tx_to_llvm_workers.lock().clone(),
523         codegen_worker_receive,
524         shared_emitter_main,
525         future: coordinator_thread,
526         output_filenames: tcx.output_filenames(LOCAL_CRATE),
527     }
528 }
529
530 fn copy_all_cgu_workproducts_to_incr_comp_cache_dir(
531     sess: &Session,
532     compiled_modules: &CompiledModules,
533 ) -> FxHashMap<WorkProductId, WorkProduct> {
534     let mut work_products = FxHashMap::default();
535
536     if sess.opts.incremental.is_none() {
537         return work_products;
538     }
539
540     for module in compiled_modules.modules.iter().filter(|m| m.kind == ModuleKind::Regular) {
541         let mut files = vec![];
542
543         if let Some(ref path) = module.object {
544             files.push((WorkProductFileKind::Object, path.clone()));
545         }
546         if let Some(ref path) = module.bytecode {
547             files.push((WorkProductFileKind::Bytecode, path.clone()));
548         }
549         if let Some(ref path) = module.bytecode_compressed {
550             files.push((WorkProductFileKind::BytecodeCompressed, path.clone()));
551         }
552
553         if let Some((id, product)) =
554                 copy_cgu_workproducts_to_incr_comp_cache_dir(sess, &module.name, &files) {
555             work_products.insert(id, product);
556         }
557     }
558
559     work_products
560 }
561
562 fn produce_final_output_artifacts(sess: &Session,
563                                   compiled_modules: &CompiledModules,
564                                   crate_output: &OutputFilenames) {
565     let mut user_wants_bitcode = false;
566     let mut user_wants_objects = false;
567
568     // Produce final compile outputs.
569     let copy_gracefully = |from: &Path, to: &Path| {
570         if let Err(e) = fs::copy(from, to) {
571             sess.err(&format!("could not copy {:?} to {:?}: {}", from, to, e));
572         }
573     };
574
575     let copy_if_one_unit = |output_type: OutputType,
576                             keep_numbered: bool| {
577         if compiled_modules.modules.len() == 1 {
578             // 1) Only one codegen unit.  In this case it's no difficulty
579             //    to copy `foo.0.x` to `foo.x`.
580             let module_name = Some(&compiled_modules.modules[0].name[..]);
581             let path = crate_output.temp_path(output_type, module_name);
582             copy_gracefully(&path,
583                             &crate_output.path(output_type));
584             if !sess.opts.cg.save_temps && !keep_numbered {
585                 // The user just wants `foo.x`, not `foo.#module-name#.x`.
586                 remove(sess, &path);
587             }
588         } else {
589             let ext = crate_output.temp_path(output_type, None)
590                                   .extension()
591                                   .unwrap()
592                                   .to_str()
593                                   .unwrap()
594                                   .to_owned();
595
596             if crate_output.outputs.contains_key(&output_type) {
597                 // 2) Multiple codegen units, with `--emit foo=some_name`.  We have
598                 //    no good solution for this case, so warn the user.
599                 sess.warn(&format!("ignoring emit path because multiple .{} files \
600                                     were produced", ext));
601             } else if crate_output.single_output_file.is_some() {
602                 // 3) Multiple codegen units, with `-o some_name`.  We have
603                 //    no good solution for this case, so warn the user.
604                 sess.warn(&format!("ignoring -o because multiple .{} files \
605                                     were produced", ext));
606             } else {
607                 // 4) Multiple codegen units, but no explicit name.  We
608                 //    just leave the `foo.0.x` files in place.
609                 // (We don't have to do any work in this case.)
610             }
611         }
612     };
613
614     // Flag to indicate whether the user explicitly requested bitcode.
615     // Otherwise, we produced it only as a temporary output, and will need
616     // to get rid of it.
617     for output_type in crate_output.outputs.keys() {
618         match *output_type {
619             OutputType::Bitcode => {
620                 user_wants_bitcode = true;
621                 // Copy to .bc, but always keep the .0.bc.  There is a later
622                 // check to figure out if we should delete .0.bc files, or keep
623                 // them for making an rlib.
624                 copy_if_one_unit(OutputType::Bitcode, true);
625             }
626             OutputType::LlvmAssembly => {
627                 copy_if_one_unit(OutputType::LlvmAssembly, false);
628             }
629             OutputType::Assembly => {
630                 copy_if_one_unit(OutputType::Assembly, false);
631             }
632             OutputType::Object => {
633                 user_wants_objects = true;
634                 copy_if_one_unit(OutputType::Object, true);
635             }
636             OutputType::Mir |
637             OutputType::Metadata |
638             OutputType::Exe |
639             OutputType::DepInfo => {}
640         }
641     }
642
643     // Clean up unwanted temporary files.
644
645     // We create the following files by default:
646     //  - #crate#.#module-name#.bc
647     //  - #crate#.#module-name#.o
648     //  - #crate#.crate.metadata.bc
649     //  - #crate#.crate.metadata.o
650     //  - #crate#.o (linked from crate.##.o)
651     //  - #crate#.bc (copied from crate.##.bc)
652     // We may create additional files if requested by the user (through
653     // `-C save-temps` or `--emit=` flags).
654
655     if !sess.opts.cg.save_temps {
656         // Remove the temporary .#module-name#.o objects.  If the user didn't
657         // explicitly request bitcode (with --emit=bc), and the bitcode is not
658         // needed for building an rlib, then we must remove .#module-name#.bc as
659         // well.
660
661         // Specific rules for keeping .#module-name#.bc:
662         //  - If the user requested bitcode (`user_wants_bitcode`), and
663         //    codegen_units > 1, then keep it.
664         //  - If the user requested bitcode but codegen_units == 1, then we
665         //    can toss .#module-name#.bc because we copied it to .bc earlier.
666         //  - If we're not building an rlib and the user didn't request
667         //    bitcode, then delete .#module-name#.bc.
668         // If you change how this works, also update back::link::link_rlib,
669         // where .#module-name#.bc files are (maybe) deleted after making an
670         // rlib.
671         let needs_crate_object = crate_output.outputs.contains_key(&OutputType::Exe);
672
673         let keep_numbered_bitcode = user_wants_bitcode && sess.codegen_units() > 1;
674
675         let keep_numbered_objects = needs_crate_object ||
676                 (user_wants_objects && sess.codegen_units() > 1);
677
678         for module in compiled_modules.modules.iter() {
679             if let Some(ref path) = module.object {
680                 if !keep_numbered_objects {
681                     remove(sess, path);
682                 }
683             }
684
685             if let Some(ref path) = module.bytecode {
686                 if !keep_numbered_bitcode {
687                     remove(sess, path);
688                 }
689             }
690         }
691
692         if !user_wants_bitcode {
693             if let Some(ref path) = compiled_modules.metadata_module.bytecode {
694                 remove(sess, &path);
695             }
696
697             if let Some(ref allocator_module) = compiled_modules.allocator_module {
698                 if let Some(ref path) = allocator_module.bytecode {
699                     remove(sess, path);
700                 }
701             }
702         }
703     }
704
705     // We leave the following files around by default:
706     //  - #crate#.o
707     //  - #crate#.crate.metadata.o
708     //  - #crate#.bc
709     // These are used in linking steps and will be cleaned up afterward.
710 }
711
712 pub fn dump_incremental_data(_codegen_results: &CodegenResults) {
713     // FIXME(mw): This does not work at the moment because the situation has
714     //            become more complicated due to incremental LTO. Now a CGU
715     //            can have more than two caching states.
716     // println!("[incremental] Re-using {} out of {} modules",
717     //           codegen_results.modules.iter().filter(|m| m.pre_existing).count(),
718     //           codegen_results.modules.len());
719 }
720
721 pub enum WorkItem<B: WriteBackendMethods> {
722     /// Optimize a newly codegened, totally unoptimized module.
723     Optimize(ModuleCodegen<B::Module>),
724     /// Copy the post-LTO artifacts from the incremental cache to the output
725     /// directory.
726     CopyPostLtoArtifacts(CachedModuleCodegen),
727     /// Performs (Thin)LTO on the given module.
728     LTO(lto::LtoModuleCodegen<B>),
729 }
730
731 impl<B: WriteBackendMethods> WorkItem<B> {
732     pub fn module_kind(&self) -> ModuleKind {
733         match *self {
734             WorkItem::Optimize(ref m) => m.kind,
735             WorkItem::CopyPostLtoArtifacts(_) |
736             WorkItem::LTO(_) => ModuleKind::Regular,
737         }
738     }
739
740     pub fn name(&self) -> String {
741         match *self {
742             WorkItem::Optimize(ref m) => format!("optimize: {}", m.name),
743             WorkItem::CopyPostLtoArtifacts(ref m) => format!("copy post LTO artifacts: {}", m.name),
744             WorkItem::LTO(ref m) => format!("lto: {}", m.name()),
745         }
746     }
747 }
748
749 enum WorkItemResult<B: WriteBackendMethods> {
750     Compiled(CompiledModule),
751     NeedsFatLTO(FatLTOInput<B>),
752     NeedsThinLTO(String, B::ThinBuffer),
753 }
754
755 pub enum FatLTOInput<B: WriteBackendMethods> {
756     Serialized {
757         name: String,
758         buffer: B::ModuleBuffer,
759     },
760     InMemory(ModuleCodegen<B::Module>),
761 }
762
763 fn execute_work_item<B: ExtraBackendMethods>(
764     cgcx: &CodegenContext<B>,
765     work_item: WorkItem<B>,
766 ) -> Result<WorkItemResult<B>, FatalError> {
767     let module_config = cgcx.config(work_item.module_kind());
768
769     match work_item {
770         WorkItem::Optimize(module) => {
771             execute_optimize_work_item(cgcx, module, module_config)
772         }
773         WorkItem::CopyPostLtoArtifacts(module) => {
774             execute_copy_from_cache_work_item(cgcx, module, module_config)
775         }
776         WorkItem::LTO(module) => {
777             execute_lto_work_item(cgcx, module, module_config)
778         }
779     }
780 }
781
782 // Actual LTO type we end up chosing based on multiple factors.
783 enum ComputedLtoType {
784     No,
785     Thin,
786     Fat,
787 }
788
789 fn execute_optimize_work_item<B: ExtraBackendMethods>(
790     cgcx: &CodegenContext<B>,
791     module: ModuleCodegen<B::Module>,
792     module_config: &ModuleConfig,
793 ) -> Result<WorkItemResult<B>, FatalError> {
794     let diag_handler = cgcx.create_diag_handler();
795
796     unsafe {
797         B::optimize(cgcx, &diag_handler, &module, module_config)?;
798     }
799
800     // After we've done the initial round of optimizations we need to
801     // decide whether to synchronously codegen this module or ship it
802     // back to the coordinator thread for further LTO processing (which
803     // has to wait for all the initial modules to be optimized).
804
805     // If the linker does LTO, we don't have to do it. Note that we
806     // keep doing full LTO, if it is requested, as not to break the
807     // assumption that the output will be a single module.
808     let linker_does_lto = cgcx.opts.cg.linker_plugin_lto.enabled();
809
810     // When we're automatically doing ThinLTO for multi-codegen-unit
811     // builds we don't actually want to LTO the allocator modules if
812     // it shows up. This is due to various linker shenanigans that
813     // we'll encounter later.
814     let is_allocator = module.kind == ModuleKind::Allocator;
815
816     // We ignore a request for full crate grath LTO if the cate type
817     // is only an rlib, as there is no full crate graph to process,
818     // that'll happen later.
819     //
820     // This use case currently comes up primarily for targets that
821     // require LTO so the request for LTO is always unconditionally
822     // passed down to the backend, but we don't actually want to do
823     // anything about it yet until we've got a final product.
824     let is_rlib = cgcx.crate_types.len() == 1
825         && cgcx.crate_types[0] == config::CrateType::Rlib;
826
827     // Metadata modules never participate in LTO regardless of the lto
828     // settings.
829     let lto_type = if module.kind == ModuleKind::Metadata {
830         ComputedLtoType::No
831     } else {
832         match cgcx.lto {
833             Lto::ThinLocal if !linker_does_lto && !is_allocator
834                 => ComputedLtoType::Thin,
835             Lto::Thin if !linker_does_lto && !is_rlib
836                 => ComputedLtoType::Thin,
837             Lto::Fat if !is_rlib => ComputedLtoType::Fat,
838             _ => ComputedLtoType::No,
839         }
840     };
841
842     // If we're doing some form of incremental LTO then we need to be sure to
843     // save our module to disk first.
844     let bitcode = if cgcx.config(module.kind).emit_pre_lto_bc {
845         let filename = pre_lto_bitcode_filename(&module.name);
846         cgcx.incr_comp_session_dir.as_ref().map(|path| path.join(&filename))
847     } else {
848         None
849     };
850
851     Ok(match lto_type {
852         ComputedLtoType::No => {
853             let module = unsafe {
854                 B::codegen(cgcx, &diag_handler, module, module_config)?
855             };
856             WorkItemResult::Compiled(module)
857         }
858         ComputedLtoType::Thin => {
859             let (name, thin_buffer) = B::prepare_thin(module);
860             if let Some(path) = bitcode {
861                 fs::write(&path, thin_buffer.data()).unwrap_or_else(|e| {
862                     panic!("Error writing pre-lto-bitcode file `{}`: {}",
863                            path.display(),
864                            e);
865                 });
866             }
867             WorkItemResult::NeedsThinLTO(name, thin_buffer)
868         }
869         ComputedLtoType::Fat => {
870             match bitcode {
871                 Some(path) => {
872                     let (name, buffer) = B::serialize_module(module);
873                     fs::write(&path, buffer.data()).unwrap_or_else(|e| {
874                         panic!("Error writing pre-lto-bitcode file `{}`: {}",
875                                path.display(),
876                                e);
877                     });
878                     WorkItemResult::NeedsFatLTO(FatLTOInput::Serialized { name, buffer })
879                 }
880                 None => WorkItemResult::NeedsFatLTO(FatLTOInput::InMemory(module)),
881             }
882         }
883     })
884 }
885
886 fn execute_copy_from_cache_work_item<B: ExtraBackendMethods>(
887     cgcx: &CodegenContext<B>,
888     module: CachedModuleCodegen,
889     module_config: &ModuleConfig,
890 ) -> Result<WorkItemResult<B>, FatalError> {
891     let incr_comp_session_dir = cgcx.incr_comp_session_dir
892                                     .as_ref()
893                                     .unwrap();
894     let mut object = None;
895     let mut bytecode = None;
896     let mut bytecode_compressed = None;
897     for (kind, saved_file) in &module.source.saved_files {
898         let obj_out = match kind {
899             WorkProductFileKind::Object => {
900                 let path = cgcx.output_filenames.temp_path(OutputType::Object,
901                                                            Some(&module.name));
902                 object = Some(path.clone());
903                 path
904             }
905             WorkProductFileKind::Bytecode => {
906                 let path = cgcx.output_filenames.temp_path(OutputType::Bitcode,
907                                                            Some(&module.name));
908                 bytecode = Some(path.clone());
909                 path
910             }
911             WorkProductFileKind::BytecodeCompressed => {
912                 let path = cgcx.output_filenames.temp_path(OutputType::Bitcode,
913                                                            Some(&module.name))
914                     .with_extension(RLIB_BYTECODE_EXTENSION);
915                 bytecode_compressed = Some(path.clone());
916                 path
917             }
918         };
919         let source_file = in_incr_comp_dir(&incr_comp_session_dir,
920                                            &saved_file);
921         debug!("copying pre-existing module `{}` from {:?} to {}",
922                module.name,
923                source_file,
924                obj_out.display());
925         if let Err(err) = link_or_copy(&source_file, &obj_out) {
926             let diag_handler = cgcx.create_diag_handler();
927             diag_handler.err(&format!("unable to copy {} to {}: {}",
928                                       source_file.display(),
929                                       obj_out.display(),
930                                       err));
931         }
932     }
933
934     assert_eq!(object.is_some(), module_config.emit_obj);
935     assert_eq!(bytecode.is_some(), module_config.emit_bc);
936     assert_eq!(bytecode_compressed.is_some(), module_config.emit_bc_compressed);
937
938     Ok(WorkItemResult::Compiled(CompiledModule {
939         name: module.name,
940         kind: ModuleKind::Regular,
941         object,
942         bytecode,
943         bytecode_compressed,
944     }))
945 }
946
947 fn execute_lto_work_item<B: ExtraBackendMethods>(
948     cgcx: &CodegenContext<B>,
949     mut module: lto::LtoModuleCodegen<B>,
950     module_config: &ModuleConfig,
951 ) -> Result<WorkItemResult<B>, FatalError> {
952     let diag_handler = cgcx.create_diag_handler();
953
954     unsafe {
955         let module = module.optimize(cgcx)?;
956         let module = B::codegen(cgcx, &diag_handler, module, module_config)?;
957         Ok(WorkItemResult::Compiled(module))
958     }
959 }
960
961 pub enum Message<B: WriteBackendMethods> {
962     Token(io::Result<Acquired>),
963     NeedsFatLTO {
964         result: FatLTOInput<B>,
965         worker_id: usize,
966     },
967     NeedsThinLTO {
968         name: String,
969         thin_buffer: B::ThinBuffer,
970         worker_id: usize,
971     },
972     Done {
973         result: Result<CompiledModule, ()>,
974         worker_id: usize,
975     },
976     CodegenDone {
977         llvm_work_item: WorkItem<B>,
978         cost: u64,
979     },
980     AddImportOnlyModule {
981         module_data: SerializedModule<B::ModuleBuffer>,
982         work_product: WorkProduct,
983     },
984     CodegenComplete,
985     CodegenItem,
986     CodegenAborted,
987 }
988
989 struct Diagnostic {
990     msg: String,
991     code: Option<DiagnosticId>,
992     lvl: Level,
993 }
994
995 #[derive(PartialEq, Clone, Copy, Debug)]
996 enum MainThreadWorkerState {
997     Idle,
998     Codegenning,
999     LLVMing,
1000 }
1001
1002 fn start_executing_work<B: ExtraBackendMethods>(
1003     backend: B,
1004     tcx: TyCtxt<'_, '_, '_>,
1005     crate_info: &CrateInfo,
1006     shared_emitter: SharedEmitter,
1007     codegen_worker_send: Sender<Message<B>>,
1008     coordinator_receive: Receiver<Box<dyn Any + Send>>,
1009     total_cgus: usize,
1010     jobserver: Client,
1011     modules_config: Arc<ModuleConfig>,
1012     metadata_config: Arc<ModuleConfig>,
1013     allocator_config: Arc<ModuleConfig>
1014 ) -> thread::JoinHandle<Result<CompiledModules, ()>> {
1015     let coordinator_send = tcx.tx_to_llvm_workers.lock().clone();
1016     let sess = tcx.sess;
1017
1018     // Compute the set of symbols we need to retain when doing LTO (if we need to)
1019     let exported_symbols = {
1020         let mut exported_symbols = FxHashMap::default();
1021
1022         let copy_symbols = |cnum| {
1023             let symbols = tcx.exported_symbols(cnum)
1024                              .iter()
1025                              .map(|&(s, lvl)| (s.symbol_name(tcx).to_string(), lvl))
1026                              .collect();
1027             Arc::new(symbols)
1028         };
1029
1030         match sess.lto() {
1031             Lto::No => None,
1032             Lto::ThinLocal => {
1033                 exported_symbols.insert(LOCAL_CRATE, copy_symbols(LOCAL_CRATE));
1034                 Some(Arc::new(exported_symbols))
1035             }
1036             Lto::Fat | Lto::Thin => {
1037                 exported_symbols.insert(LOCAL_CRATE, copy_symbols(LOCAL_CRATE));
1038                 for &cnum in tcx.crates().iter() {
1039                     exported_symbols.insert(cnum, copy_symbols(cnum));
1040                 }
1041                 Some(Arc::new(exported_symbols))
1042             }
1043         }
1044     };
1045
1046     // First up, convert our jobserver into a helper thread so we can use normal
1047     // mpsc channels to manage our messages and such.
1048     // After we've requested tokens then we'll, when we can,
1049     // get tokens on `coordinator_receive` which will
1050     // get managed in the main loop below.
1051     let coordinator_send2 = coordinator_send.clone();
1052     let helper = jobserver.into_helper_thread(move |token| {
1053         drop(coordinator_send2.send(Box::new(Message::Token::<B>(token))));
1054     }).expect("failed to spawn helper thread");
1055
1056     let mut each_linked_rlib_for_lto = Vec::new();
1057     drop(link::each_linked_rlib(sess, crate_info, &mut |cnum, path| {
1058         if link::ignored_for_lto(sess, crate_info, cnum) {
1059             return
1060         }
1061         each_linked_rlib_for_lto.push((cnum, path.to_path_buf()));
1062     }));
1063
1064     let assembler_cmd = if modules_config.no_integrated_as {
1065         // HACK: currently we use linker (gcc) as our assembler
1066         let (linker, flavor) = link::linker_and_flavor(sess);
1067
1068         let (name, mut cmd) = get_linker(sess, &linker, flavor);
1069         cmd.args(&sess.target.target.options.asm_args);
1070         Some(Arc::new(AssemblerCommand {
1071             name,
1072             cmd,
1073         }))
1074     } else {
1075         None
1076     };
1077
1078     let ol = tcx.backend_optimization_level(LOCAL_CRATE);
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_passes(),
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         let compiled_metadata_module = compiled_metadata_module
1570             .expect("Metadata module not compiled?");
1571
1572         Ok(CompiledModules {
1573             modules: compiled_modules,
1574             metadata_module: compiled_metadata_module,
1575             allocator_module: compiled_allocator_module,
1576         })
1577     });
1578
1579     // A heuristic that determines if we have enough LLVM WorkItems in the
1580     // queue so that the main thread can do LLVM work instead of codegen
1581     fn queue_full_enough(items_in_queue: usize,
1582                          workers_running: usize,
1583                          max_workers: usize) -> bool {
1584         // Tune me, plz.
1585         items_in_queue > 0 &&
1586         items_in_queue >= max_workers.saturating_sub(workers_running / 2)
1587     }
1588
1589     fn maybe_start_llvm_timer(config: &ModuleConfig,
1590                               llvm_start_time: &mut Option<Instant>) {
1591         // We keep track of the -Ztime-passes output manually,
1592         // since the closure-based interface does not fit well here.
1593         if config.time_passes {
1594             if llvm_start_time.is_none() {
1595                 *llvm_start_time = Some(Instant::now());
1596             }
1597         }
1598     }
1599 }
1600
1601 pub const CODEGEN_WORKER_ID: usize = ::std::usize::MAX;
1602
1603 fn spawn_work<B: ExtraBackendMethods>(
1604     cgcx: CodegenContext<B>,
1605     work: WorkItem<B>
1606 ) {
1607     let depth = time_depth();
1608
1609     thread::spawn(move || {
1610         set_time_depth(depth);
1611
1612         // Set up a destructor which will fire off a message that we're done as
1613         // we exit.
1614         struct Bomb<B: ExtraBackendMethods> {
1615             coordinator_send: Sender<Box<dyn Any + Send>>,
1616             result: Option<WorkItemResult<B>>,
1617             worker_id: usize,
1618         }
1619         impl<B: ExtraBackendMethods> Drop for Bomb<B> {
1620             fn drop(&mut self) {
1621                 let worker_id = self.worker_id;
1622                 let msg = match self.result.take() {
1623                     Some(WorkItemResult::Compiled(m)) => {
1624                         Message::Done::<B> { result: Ok(m), worker_id }
1625                     }
1626                     Some(WorkItemResult::NeedsFatLTO(m)) => {
1627                         Message::NeedsFatLTO::<B> { result: m, worker_id }
1628                     }
1629                     Some(WorkItemResult::NeedsThinLTO(name, thin_buffer)) => {
1630                         Message::NeedsThinLTO::<B> { name, thin_buffer, worker_id }
1631                     }
1632                     None => Message::Done::<B> { result: Err(()), worker_id }
1633                 };
1634                 drop(self.coordinator_send.send(Box::new(msg)));
1635             }
1636         }
1637
1638         let mut bomb = Bomb::<B> {
1639             coordinator_send: cgcx.coordinator_send.clone(),
1640             result: None,
1641             worker_id: cgcx.worker,
1642         };
1643
1644         // Execute the work itself, and if it finishes successfully then flag
1645         // ourselves as a success as well.
1646         //
1647         // Note that we ignore any `FatalError` coming out of `execute_work_item`,
1648         // as a diagnostic was already sent off to the main thread - just
1649         // surface that there was an error in this worker.
1650         bomb.result = {
1651             let label = work.name();
1652             cgcx.profile(|p| p.start_activity(ProfileCategory::Codegen, label.clone()));
1653             let result = execute_work_item(&cgcx, work).ok();
1654             cgcx.profile(|p| p.end_activity(ProfileCategory::Codegen, label));
1655
1656             result
1657         };
1658     });
1659 }
1660
1661 pub fn run_assembler<B: ExtraBackendMethods>(
1662     cgcx: &CodegenContext<B>,
1663     handler: &Handler,
1664     assembly: &Path,
1665     object: &Path
1666 ) {
1667     let assembler = cgcx.assembler_cmd
1668         .as_ref()
1669         .expect("cgcx.assembler_cmd is missing?");
1670
1671     let pname = &assembler.name;
1672     let mut cmd = assembler.cmd.clone();
1673     cmd.arg("-c").arg("-o").arg(object).arg(assembly);
1674     debug!("{:?}", cmd);
1675
1676     match cmd.output() {
1677         Ok(prog) => {
1678             if !prog.status.success() {
1679                 let mut note = prog.stderr.clone();
1680                 note.extend_from_slice(&prog.stdout);
1681
1682                 handler.struct_err(&format!("linking with `{}` failed: {}",
1683                                             pname.display(),
1684                                             prog.status))
1685                     .note(&format!("{:?}", &cmd))
1686                     .note(str::from_utf8(&note[..]).unwrap())
1687                     .emit();
1688                 handler.abort_if_errors();
1689             }
1690         },
1691         Err(e) => {
1692             handler.err(&format!("could not exec the linker `{}`: {}", pname.display(), e));
1693             handler.abort_if_errors();
1694         }
1695     }
1696 }
1697
1698
1699 enum SharedEmitterMessage {
1700     Diagnostic(Diagnostic),
1701     InlineAsmError(u32, String),
1702     AbortIfErrors,
1703     Fatal(String),
1704 }
1705
1706 #[derive(Clone)]
1707 pub struct SharedEmitter {
1708     sender: Sender<SharedEmitterMessage>,
1709 }
1710
1711 pub struct SharedEmitterMain {
1712     receiver: Receiver<SharedEmitterMessage>,
1713 }
1714
1715 impl SharedEmitter {
1716     pub fn new() -> (SharedEmitter, SharedEmitterMain) {
1717         let (sender, receiver) = channel();
1718
1719         (SharedEmitter { sender }, SharedEmitterMain { receiver })
1720     }
1721
1722     pub fn inline_asm_error(&self, cookie: u32, msg: String) {
1723         drop(self.sender.send(SharedEmitterMessage::InlineAsmError(cookie, msg)));
1724     }
1725
1726     pub fn fatal(&self, msg: &str) {
1727         drop(self.sender.send(SharedEmitterMessage::Fatal(msg.to_string())));
1728     }
1729 }
1730
1731 impl Emitter for SharedEmitter {
1732     fn emit(&mut self, db: &DiagnosticBuilder<'_>) {
1733         drop(self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
1734             msg: db.message(),
1735             code: db.code.clone(),
1736             lvl: db.level,
1737         })));
1738         for child in &db.children {
1739             drop(self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
1740                 msg: child.message(),
1741                 code: None,
1742                 lvl: child.level,
1743             })));
1744         }
1745         drop(self.sender.send(SharedEmitterMessage::AbortIfErrors));
1746     }
1747 }
1748
1749 impl SharedEmitterMain {
1750     pub fn check(&self, sess: &Session, blocking: bool) {
1751         loop {
1752             let message = if blocking {
1753                 match self.receiver.recv() {
1754                     Ok(message) => Ok(message),
1755                     Err(_) => Err(()),
1756                 }
1757             } else {
1758                 match self.receiver.try_recv() {
1759                     Ok(message) => Ok(message),
1760                     Err(_) => Err(()),
1761                 }
1762             };
1763
1764             match message {
1765                 Ok(SharedEmitterMessage::Diagnostic(diag)) => {
1766                     let handler = sess.diagnostic();
1767                     match diag.code {
1768                         Some(ref code) => {
1769                             handler.emit_with_code(&MultiSpan::new(),
1770                                                    &diag.msg,
1771                                                    code.clone(),
1772                                                    diag.lvl);
1773                         }
1774                         None => {
1775                             handler.emit(&MultiSpan::new(),
1776                                          &diag.msg,
1777                                          diag.lvl);
1778                         }
1779                     }
1780                 }
1781                 Ok(SharedEmitterMessage::InlineAsmError(cookie, msg)) => {
1782                     match Mark::from_u32(cookie).expn_info() {
1783                         Some(ei) => sess.span_err(ei.call_site, &msg),
1784                         None     => sess.err(&msg),
1785                     }
1786                 }
1787                 Ok(SharedEmitterMessage::AbortIfErrors) => {
1788                     sess.abort_if_errors();
1789                 }
1790                 Ok(SharedEmitterMessage::Fatal(msg)) => {
1791                     sess.fatal(&msg);
1792                 }
1793                 Err(_) => {
1794                     break;
1795                 }
1796             }
1797
1798         }
1799     }
1800 }
1801
1802 pub struct OngoingCodegen<B: ExtraBackendMethods> {
1803     pub backend: B,
1804     pub crate_name: Symbol,
1805     pub crate_hash: Svh,
1806     pub metadata: EncodedMetadata,
1807     pub windows_subsystem: Option<String>,
1808     pub linker_info: LinkerInfo,
1809     pub crate_info: CrateInfo,
1810     pub coordinator_send: Sender<Box<dyn Any + Send>>,
1811     pub codegen_worker_receive: Receiver<Message<B>>,
1812     pub shared_emitter_main: SharedEmitterMain,
1813     pub future: thread::JoinHandle<Result<CompiledModules, ()>>,
1814     pub output_filenames: Arc<OutputFilenames>,
1815 }
1816
1817 impl<B: ExtraBackendMethods> OngoingCodegen<B> {
1818     pub fn join(
1819         self,
1820         sess: &Session
1821     ) -> (CodegenResults, FxHashMap<WorkProductId, WorkProduct>) {
1822         self.shared_emitter_main.check(sess, true);
1823         let compiled_modules = match self.future.join() {
1824             Ok(Ok(compiled_modules)) => compiled_modules,
1825             Ok(Err(())) => {
1826                 sess.abort_if_errors();
1827                 panic!("expected abort due to worker thread errors")
1828             },
1829             Err(_) => {
1830                 bug!("panic during codegen/LLVM phase");
1831             }
1832         };
1833
1834         sess.cgu_reuse_tracker.check_expected_reuse(sess);
1835
1836         sess.abort_if_errors();
1837
1838         let work_products =
1839             copy_all_cgu_workproducts_to_incr_comp_cache_dir(sess,
1840                                                              &compiled_modules);
1841         produce_final_output_artifacts(sess,
1842                                        &compiled_modules,
1843                                        &self.output_filenames);
1844
1845         // FIXME: time_llvm_passes support - does this use a global context or
1846         // something?
1847         if sess.codegen_units() == 1 && sess.time_llvm_passes() {
1848             self.backend.print_pass_timings()
1849         }
1850
1851         (CodegenResults {
1852             crate_name: self.crate_name,
1853             crate_hash: self.crate_hash,
1854             metadata: self.metadata,
1855             windows_subsystem: self.windows_subsystem,
1856             linker_info: self.linker_info,
1857             crate_info: self.crate_info,
1858
1859             modules: compiled_modules.modules,
1860             allocator_module: compiled_modules.allocator_module,
1861             metadata_module: compiled_modules.metadata_module,
1862         }, work_products)
1863     }
1864
1865     pub fn submit_pre_codegened_module_to_llvm(&self,
1866                                                        tcx: TyCtxt<'_, '_, '_>,
1867                                                        module: ModuleCodegen<B::Module>) {
1868         self.wait_for_signal_to_codegen_item();
1869         self.check_for_errors(tcx.sess);
1870
1871         // These are generally cheap and won't through off scheduling.
1872         let cost = 0;
1873         submit_codegened_module_to_llvm(&self.backend, tcx, module, cost);
1874     }
1875
1876     pub fn codegen_finished(&self, tcx: TyCtxt<'_, '_, '_>) {
1877         self.wait_for_signal_to_codegen_item();
1878         self.check_for_errors(tcx.sess);
1879         drop(self.coordinator_send.send(Box::new(Message::CodegenComplete::<B>)));
1880     }
1881
1882     /// Consumes this context indicating that codegen was entirely aborted, and
1883     /// we need to exit as quickly as possible.
1884     ///
1885     /// This method blocks the current thread until all worker threads have
1886     /// finished, and all worker threads should have exited or be real close to
1887     /// exiting at this point.
1888     pub fn codegen_aborted(self) {
1889         // Signal to the coordinator it should spawn no more work and start
1890         // shutdown.
1891         drop(self.coordinator_send.send(Box::new(Message::CodegenAborted::<B>)));
1892         drop(self.future.join());
1893     }
1894
1895     pub fn check_for_errors(&self, sess: &Session) {
1896         self.shared_emitter_main.check(sess, false);
1897     }
1898
1899     pub fn wait_for_signal_to_codegen_item(&self) {
1900         match self.codegen_worker_receive.recv() {
1901             Ok(Message::CodegenItem) => {
1902                 // Nothing to do
1903             }
1904             Ok(_) => panic!("unexpected message"),
1905             Err(_) => {
1906                 // One of the LLVM threads must have panicked, fall through so
1907                 // error handling can be reached.
1908             }
1909         }
1910     }
1911 }
1912
1913 pub fn submit_codegened_module_to_llvm<B: ExtraBackendMethods>(
1914     _backend: &B,
1915     tcx: TyCtxt<'_, '_, '_>,
1916     module: ModuleCodegen<B::Module>,
1917     cost: u64
1918 ) {
1919     let llvm_work_item = WorkItem::Optimize(module);
1920     drop(tcx.tx_to_llvm_workers.lock().send(Box::new(Message::CodegenDone::<B> {
1921         llvm_work_item,
1922         cost,
1923     })));
1924 }
1925
1926 pub fn submit_post_lto_module_to_llvm<B: ExtraBackendMethods>(
1927     _backend: &B,
1928     tcx: TyCtxt<'_, '_, '_>,
1929     module: CachedModuleCodegen
1930 ) {
1931     let llvm_work_item = WorkItem::CopyPostLtoArtifacts(module);
1932     drop(tcx.tx_to_llvm_workers.lock().send(Box::new(Message::CodegenDone::<B> {
1933         llvm_work_item,
1934         cost: 0,
1935     })));
1936 }
1937
1938 pub fn submit_pre_lto_module_to_llvm<B: ExtraBackendMethods>(
1939     _backend: &B,
1940     tcx: TyCtxt<'_, '_, '_>,
1941     module: CachedModuleCodegen
1942 ) {
1943     let filename = pre_lto_bitcode_filename(&module.name);
1944     let bc_path = in_incr_comp_dir_sess(tcx.sess, &filename);
1945     let file = fs::File::open(&bc_path).unwrap_or_else(|e| {
1946         panic!("failed to open bitcode file `{}`: {}", bc_path.display(), e)
1947     });
1948
1949     let mmap = unsafe {
1950         memmap::Mmap::map(&file).unwrap_or_else(|e| {
1951             panic!("failed to mmap bitcode file `{}`: {}", bc_path.display(), e)
1952         })
1953     };
1954     // Schedule the module to be loaded
1955     drop(tcx.tx_to_llvm_workers.lock().send(Box::new(Message::AddImportOnlyModule::<B> {
1956         module_data: SerializedModule::FromUncompressedFile(mmap),
1957         work_product: module.source,
1958     })));
1959 }
1960
1961 pub fn pre_lto_bitcode_filename(module_name: &str) -> String {
1962     format!("{}.{}", module_name, PRE_LTO_BC_EXT)
1963 }
1964
1965 fn msvc_imps_needed(tcx: TyCtxt<'_, '_, '_>) -> bool {
1966     // This should never be true (because it's not supported). If it is true,
1967     // something is wrong with commandline arg validation.
1968     assert!(!(tcx.sess.opts.cg.linker_plugin_lto.enabled() &&
1969               tcx.sess.target.target.options.is_like_msvc &&
1970               tcx.sess.opts.cg.prefer_dynamic));
1971
1972     tcx.sess.target.target.options.is_like_msvc &&
1973         tcx.sess.crate_types.borrow().iter().any(|ct| *ct == config::CrateType::Rlib) &&
1974     // ThinLTO can't handle this workaround in all cases, so we don't
1975     // emit the `__imp_` symbols. Instead we make them unnecessary by disallowing
1976     // dynamic linking when linker plugin LTO is enabled.
1977     !tcx.sess.opts.cg.linker_plugin_lto.enabled()
1978 }