]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_llvm/back/write.rs
Auto merge of #55681 - matthiaskrgr:clippy, r=oli-obk
[rust.git] / src / librustc_codegen_llvm / back / write.rs
1 // Copyright 2013-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use attributes;
12 use back::bytecode::{self, RLIB_BYTECODE_EXTENSION};
13 use back::lto::{self, ThinBuffer, SerializedModule};
14 use back::link::{self, get_linker, remove};
15 use base;
16 use consts;
17 use memmap;
18 use rustc_incremental::{copy_cgu_workproducts_to_incr_comp_cache_dir,
19                         in_incr_comp_dir, in_incr_comp_dir_sess};
20 use rustc::dep_graph::{WorkProduct, WorkProductId, WorkProductFileKind};
21 use rustc::dep_graph::cgu_reuse_tracker::CguReuseTracker;
22 use rustc::middle::cstore::EncodedMetadata;
23 use rustc::session::config::{self, OutputFilenames, OutputType, Passes, Sanitizer, Lto};
24 use rustc::session::Session;
25 use rustc::util::nodemap::FxHashMap;
26 use time_graph::{self, TimeGraph, Timeline};
27 use llvm::{self, DiagnosticInfo, PassManager, SMDiagnostic};
28 use llvm_util;
29 use {CodegenResults, ModuleCodegen, CompiledModule, ModuleKind, // ModuleLlvm,
30      CachedModuleCodegen};
31 use CrateInfo;
32 use rustc::hir::def_id::{CrateNum, LOCAL_CRATE};
33 use rustc::ty::TyCtxt;
34 use rustc::util::common::{time_ext, time_depth, set_time_depth, print_time_passes_entry};
35 use rustc_fs_util::{path2cstr, link_or_copy};
36 use rustc_data_structures::small_c_str::SmallCStr;
37 use rustc_data_structures::svh::Svh;
38 use rustc_codegen_utils::command::Command;
39 use rustc_codegen_utils::linker::LinkerInfo;
40 use rustc_codegen_utils::symbol_export::ExportedSymbols;
41 use errors::{self, Handler, Level, DiagnosticBuilder, FatalError, DiagnosticId};
42 use errors::emitter::{Emitter};
43 use syntax::attr;
44 use syntax::ext::hygiene::Mark;
45 use syntax_pos::MultiSpan;
46 use syntax_pos::symbol::Symbol;
47 use type_::Type;
48 use context::{is_pie_binary, get_reloc_model};
49 use common::{C_bytes_in_context, val_ty};
50 use jobserver::{Client, Acquired};
51 use rustc_demangle;
52
53 use std::any::Any;
54 use std::ffi::{CString, CStr};
55 use std::fs;
56 use std::io::{self, Write};
57 use std::mem;
58 use std::path::{Path, PathBuf};
59 use std::str;
60 use std::sync::Arc;
61 use std::sync::mpsc::{channel, Sender, Receiver};
62 use std::slice;
63 use std::time::Instant;
64 use std::thread;
65 use libc::{c_uint, c_void, c_char, size_t};
66
67 pub const RELOC_MODEL_ARGS : [(&'static str, llvm::RelocMode); 7] = [
68     ("pic", llvm::RelocMode::PIC),
69     ("static", llvm::RelocMode::Static),
70     ("default", llvm::RelocMode::Default),
71     ("dynamic-no-pic", llvm::RelocMode::DynamicNoPic),
72     ("ropi", llvm::RelocMode::ROPI),
73     ("rwpi", llvm::RelocMode::RWPI),
74     ("ropi-rwpi", llvm::RelocMode::ROPI_RWPI),
75 ];
76
77 pub const CODE_GEN_MODEL_ARGS: &[(&str, llvm::CodeModel)] = &[
78     ("small", llvm::CodeModel::Small),
79     ("kernel", llvm::CodeModel::Kernel),
80     ("medium", llvm::CodeModel::Medium),
81     ("large", llvm::CodeModel::Large),
82 ];
83
84 pub const TLS_MODEL_ARGS : [(&'static str, llvm::ThreadLocalMode); 4] = [
85     ("global-dynamic", llvm::ThreadLocalMode::GeneralDynamic),
86     ("local-dynamic", llvm::ThreadLocalMode::LocalDynamic),
87     ("initial-exec", llvm::ThreadLocalMode::InitialExec),
88     ("local-exec", llvm::ThreadLocalMode::LocalExec),
89 ];
90
91 const PRE_THIN_LTO_BC_EXT: &str = "pre-thin-lto.bc";
92
93 pub fn llvm_err(handler: &errors::Handler, msg: String) -> FatalError {
94     match llvm::last_error() {
95         Some(err) => handler.fatal(&format!("{}: {}", msg, err)),
96         None => handler.fatal(&msg),
97     }
98 }
99
100 pub fn write_output_file(
101         handler: &errors::Handler,
102         target: &'ll llvm::TargetMachine,
103         pm: &llvm::PassManager<'ll>,
104         m: &'ll llvm::Module,
105         output: &Path,
106         file_type: llvm::FileType) -> Result<(), FatalError> {
107     unsafe {
108         let output_c = path2cstr(output);
109         let result = llvm::LLVMRustWriteOutputFile(
110                 target, pm, m, output_c.as_ptr(), file_type);
111         if result.into_result().is_err() {
112             let msg = format!("could not write output to {}", output.display());
113             Err(llvm_err(handler, msg))
114         } else {
115             Ok(())
116         }
117     }
118 }
119
120 fn get_llvm_opt_level(optimize: config::OptLevel) -> llvm::CodeGenOptLevel {
121     match optimize {
122       config::OptLevel::No => llvm::CodeGenOptLevel::None,
123       config::OptLevel::Less => llvm::CodeGenOptLevel::Less,
124       config::OptLevel::Default => llvm::CodeGenOptLevel::Default,
125       config::OptLevel::Aggressive => llvm::CodeGenOptLevel::Aggressive,
126       _ => llvm::CodeGenOptLevel::Default,
127     }
128 }
129
130 fn get_llvm_opt_size(optimize: config::OptLevel) -> llvm::CodeGenOptSize {
131     match optimize {
132       config::OptLevel::Size => llvm::CodeGenOptSizeDefault,
133       config::OptLevel::SizeMin => llvm::CodeGenOptSizeAggressive,
134       _ => llvm::CodeGenOptSizeNone,
135     }
136 }
137
138 pub fn create_target_machine(
139     sess: &Session,
140     find_features: bool,
141 ) -> &'static mut llvm::TargetMachine {
142     target_machine_factory(sess, find_features)().unwrap_or_else(|err| {
143         llvm_err(sess.diagnostic(), err).raise()
144     })
145 }
146
147 // If find_features is true this won't access `sess.crate_types` by assuming
148 // that `is_pie_binary` is false. When we discover LLVM target features
149 // `sess.crate_types` is uninitialized so we cannot access it.
150 pub fn target_machine_factory(sess: &Session, find_features: bool)
151     -> Arc<dyn Fn() -> Result<&'static mut llvm::TargetMachine, String> + Send + Sync>
152 {
153     let reloc_model = get_reloc_model(sess);
154
155     let opt_level = get_llvm_opt_level(sess.opts.optimize);
156     let use_softfp = sess.opts.cg.soft_float;
157
158     let ffunction_sections = sess.target.target.options.function_sections;
159     let fdata_sections = ffunction_sections;
160
161     let code_model_arg = sess.opts.cg.code_model.as_ref().or(
162         sess.target.target.options.code_model.as_ref(),
163     );
164
165     let code_model = match code_model_arg {
166         Some(s) => {
167             match CODE_GEN_MODEL_ARGS.iter().find(|arg| arg.0 == s) {
168                 Some(x) => x.1,
169                 _ => {
170                     sess.err(&format!("{:?} is not a valid code model",
171                                       code_model_arg));
172                     sess.abort_if_errors();
173                     bug!();
174                 }
175             }
176         }
177         None => llvm::CodeModel::None,
178     };
179
180     let features = attributes::llvm_target_features(sess).collect::<Vec<_>>();
181     let mut singlethread = sess.target.target.options.singlethread;
182
183     // On the wasm target once the `atomics` feature is enabled that means that
184     // we're no longer single-threaded, or otherwise we don't want LLVM to
185     // lower atomic operations to single-threaded operations.
186     if singlethread &&
187         sess.target.target.llvm_target.contains("wasm32") &&
188         features.iter().any(|s| *s == "+atomics")
189     {
190         singlethread = false;
191     }
192
193     let triple = SmallCStr::new(&sess.target.target.llvm_target);
194     let cpu = SmallCStr::new(llvm_util::target_cpu(sess));
195     let features = features.join(",");
196     let features = CString::new(features).unwrap();
197     let is_pie_binary = !find_features && is_pie_binary(sess);
198     let trap_unreachable = sess.target.target.options.trap_unreachable;
199     let emit_stack_size_section = sess.opts.debugging_opts.emit_stack_sizes;
200
201     let asm_comments = sess.asm_comments();
202
203     Arc::new(move || {
204         let tm = unsafe {
205             llvm::LLVMRustCreateTargetMachine(
206                 triple.as_ptr(), cpu.as_ptr(), features.as_ptr(),
207                 code_model,
208                 reloc_model,
209                 opt_level,
210                 use_softfp,
211                 is_pie_binary,
212                 ffunction_sections,
213                 fdata_sections,
214                 trap_unreachable,
215                 singlethread,
216                 asm_comments,
217                 emit_stack_size_section,
218             )
219         };
220
221         tm.ok_or_else(|| {
222             format!("Could not create LLVM TargetMachine for triple: {}",
223                     triple.to_str().unwrap())
224         })
225     })
226 }
227
228 /// Module-specific configuration for `optimize_and_codegen`.
229 pub struct ModuleConfig {
230     /// Names of additional optimization passes to run.
231     passes: Vec<String>,
232     /// Some(level) to optimize at a certain level, or None to run
233     /// absolutely no optimizations (used for the metadata module).
234     pub opt_level: Option<llvm::CodeGenOptLevel>,
235
236     /// Some(level) to optimize binary size, or None to not affect program size.
237     opt_size: Option<llvm::CodeGenOptSize>,
238
239     pgo_gen: Option<String>,
240     pgo_use: String,
241
242     // Flags indicating which outputs to produce.
243     pub emit_pre_thin_lto_bc: bool,
244     emit_no_opt_bc: bool,
245     emit_bc: bool,
246     emit_bc_compressed: bool,
247     emit_lto_bc: bool,
248     emit_ir: bool,
249     emit_asm: bool,
250     emit_obj: bool,
251     // Miscellaneous flags.  These are mostly copied from command-line
252     // options.
253     pub verify_llvm_ir: bool,
254     no_prepopulate_passes: bool,
255     no_builtins: bool,
256     time_passes: bool,
257     vectorize_loop: bool,
258     vectorize_slp: bool,
259     merge_functions: bool,
260     inline_threshold: Option<usize>,
261     // Instead of creating an object file by doing LLVM codegen, just
262     // make the object file bitcode. Provides easy compatibility with
263     // emscripten's ecc compiler, when used as the linker.
264     obj_is_bitcode: bool,
265     no_integrated_as: bool,
266     embed_bitcode: bool,
267     embed_bitcode_marker: bool,
268 }
269
270 impl ModuleConfig {
271     fn new(passes: Vec<String>) -> ModuleConfig {
272         ModuleConfig {
273             passes,
274             opt_level: None,
275             opt_size: None,
276
277             pgo_gen: None,
278             pgo_use: String::new(),
279
280             emit_no_opt_bc: false,
281             emit_pre_thin_lto_bc: false,
282             emit_bc: false,
283             emit_bc_compressed: false,
284             emit_lto_bc: false,
285             emit_ir: false,
286             emit_asm: false,
287             emit_obj: false,
288             obj_is_bitcode: false,
289             embed_bitcode: false,
290             embed_bitcode_marker: false,
291             no_integrated_as: false,
292
293             verify_llvm_ir: false,
294             no_prepopulate_passes: false,
295             no_builtins: false,
296             time_passes: false,
297             vectorize_loop: false,
298             vectorize_slp: false,
299             merge_functions: false,
300             inline_threshold: None
301         }
302     }
303
304     fn set_flags(&mut self, sess: &Session, no_builtins: bool) {
305         self.verify_llvm_ir = sess.verify_llvm_ir();
306         self.no_prepopulate_passes = sess.opts.cg.no_prepopulate_passes;
307         self.no_builtins = no_builtins || sess.target.target.options.no_builtins;
308         self.time_passes = sess.time_passes();
309         self.inline_threshold = sess.opts.cg.inline_threshold;
310         self.obj_is_bitcode = sess.target.target.options.obj_is_bitcode ||
311                               sess.opts.debugging_opts.cross_lang_lto.enabled();
312         let embed_bitcode = sess.target.target.options.embed_bitcode ||
313                             sess.opts.debugging_opts.embed_bitcode;
314         if embed_bitcode {
315             match sess.opts.optimize {
316                 config::OptLevel::No |
317                 config::OptLevel::Less => {
318                     self.embed_bitcode_marker = embed_bitcode;
319                 }
320                 _ => self.embed_bitcode = embed_bitcode,
321             }
322         }
323
324         // Copy what clang does by turning on loop vectorization at O2 and
325         // slp vectorization at O3. Otherwise configure other optimization aspects
326         // of this pass manager builder.
327         // Turn off vectorization for emscripten, as it's not very well supported.
328         self.vectorize_loop = !sess.opts.cg.no_vectorize_loops &&
329                              (sess.opts.optimize == config::OptLevel::Default ||
330                               sess.opts.optimize == config::OptLevel::Aggressive) &&
331                              !sess.target.target.options.is_like_emscripten;
332
333         self.vectorize_slp = !sess.opts.cg.no_vectorize_slp &&
334                             sess.opts.optimize == config::OptLevel::Aggressive &&
335                             !sess.target.target.options.is_like_emscripten;
336
337         self.merge_functions = sess.opts.optimize == config::OptLevel::Default ||
338                                sess.opts.optimize == config::OptLevel::Aggressive;
339     }
340 }
341
342 /// Assembler name and command used by codegen when no_integrated_as is enabled
343 struct AssemblerCommand {
344     name: PathBuf,
345     cmd: Command,
346 }
347
348 /// Additional resources used by optimize_and_codegen (not module specific)
349 #[derive(Clone)]
350 pub struct CodegenContext {
351     // Resources needed when running LTO
352     pub time_passes: bool,
353     pub lto: Lto,
354     pub no_landing_pads: bool,
355     pub save_temps: bool,
356     pub fewer_names: bool,
357     pub exported_symbols: Option<Arc<ExportedSymbols>>,
358     pub opts: Arc<config::Options>,
359     pub crate_types: Vec<config::CrateType>,
360     pub each_linked_rlib_for_lto: Vec<(CrateNum, PathBuf)>,
361     output_filenames: Arc<OutputFilenames>,
362     regular_module_config: Arc<ModuleConfig>,
363     metadata_module_config: Arc<ModuleConfig>,
364     allocator_module_config: Arc<ModuleConfig>,
365     pub tm_factory: Arc<dyn Fn() -> Result<&'static mut llvm::TargetMachine, String> + Send + Sync>,
366     pub msvc_imps_needed: bool,
367     pub target_pointer_width: String,
368     debuginfo: config::DebugInfo,
369
370     // Number of cgus excluding the allocator/metadata modules
371     pub total_cgus: usize,
372     // Handler to use for diagnostics produced during codegen.
373     pub diag_emitter: SharedEmitter,
374     // LLVM passes added by plugins.
375     pub plugin_passes: Vec<String>,
376     // LLVM optimizations for which we want to print remarks.
377     pub remark: Passes,
378     // Worker thread number
379     pub worker: usize,
380     // The incremental compilation session directory, or None if we are not
381     // compiling incrementally
382     pub incr_comp_session_dir: Option<PathBuf>,
383     // Used to update CGU re-use information during the thinlto phase.
384     pub cgu_reuse_tracker: CguReuseTracker,
385     // Channel back to the main control thread to send messages to
386     coordinator_send: Sender<Box<dyn Any + Send>>,
387     // A reference to the TimeGraph so we can register timings. None means that
388     // measuring is disabled.
389     time_graph: Option<TimeGraph>,
390     // The assembler command if no_integrated_as option is enabled, None otherwise
391     assembler_cmd: Option<Arc<AssemblerCommand>>,
392 }
393
394 impl CodegenContext {
395     pub fn create_diag_handler(&self) -> Handler {
396         Handler::with_emitter(true, false, Box::new(self.diag_emitter.clone()))
397     }
398
399     pub(crate) fn config(&self, kind: ModuleKind) -> &ModuleConfig {
400         match kind {
401             ModuleKind::Regular => &self.regular_module_config,
402             ModuleKind::Metadata => &self.metadata_module_config,
403             ModuleKind::Allocator => &self.allocator_module_config,
404         }
405     }
406
407     pub(crate) fn save_temp_bitcode(&self, module: &ModuleCodegen, name: &str) {
408         if !self.save_temps {
409             return
410         }
411         unsafe {
412             let ext = format!("{}.bc", name);
413             let cgu = Some(&module.name[..]);
414             let path = self.output_filenames.temp_path_ext(&ext, cgu);
415             let cstr = path2cstr(&path);
416             let llmod = module.module_llvm.llmod();
417             llvm::LLVMWriteBitcodeToFile(llmod, cstr.as_ptr());
418         }
419     }
420 }
421
422 pub struct DiagnosticHandlers<'a> {
423     data: *mut (&'a CodegenContext, &'a Handler),
424     llcx: &'a llvm::Context,
425 }
426
427 impl<'a> DiagnosticHandlers<'a> {
428     pub fn new(cgcx: &'a CodegenContext,
429                handler: &'a Handler,
430                llcx: &'a llvm::Context) -> Self {
431         let data = Box::into_raw(Box::new((cgcx, handler)));
432         unsafe {
433             llvm::LLVMRustSetInlineAsmDiagnosticHandler(llcx, inline_asm_handler, data as *mut _);
434             llvm::LLVMContextSetDiagnosticHandler(llcx, diagnostic_handler, data as *mut _);
435         }
436         DiagnosticHandlers { data, llcx }
437     }
438 }
439
440 impl<'a> Drop for DiagnosticHandlers<'a> {
441     fn drop(&mut self) {
442         use std::ptr::null_mut;
443         unsafe {
444             llvm::LLVMRustSetInlineAsmDiagnosticHandler(self.llcx, inline_asm_handler, null_mut());
445             llvm::LLVMContextSetDiagnosticHandler(self.llcx, diagnostic_handler, null_mut());
446             drop(Box::from_raw(self.data));
447         }
448     }
449 }
450
451 unsafe extern "C" fn report_inline_asm<'a, 'b>(cgcx: &'a CodegenContext,
452                                                msg: &'b str,
453                                                cookie: c_uint) {
454     cgcx.diag_emitter.inline_asm_error(cookie as u32, msg.to_string());
455 }
456
457 unsafe extern "C" fn inline_asm_handler(diag: &SMDiagnostic,
458                                         user: *const c_void,
459                                         cookie: c_uint) {
460     if user.is_null() {
461         return
462     }
463     let (cgcx, _) = *(user as *const (&CodegenContext, &Handler));
464
465     let msg = llvm::build_string(|s| llvm::LLVMRustWriteSMDiagnosticToString(diag, s))
466         .expect("non-UTF8 SMDiagnostic");
467
468     report_inline_asm(cgcx, &msg, cookie);
469 }
470
471 unsafe extern "C" fn diagnostic_handler(info: &DiagnosticInfo, user: *mut c_void) {
472     if user.is_null() {
473         return
474     }
475     let (cgcx, diag_handler) = *(user as *const (&CodegenContext, &Handler));
476
477     match llvm::diagnostic::Diagnostic::unpack(info) {
478         llvm::diagnostic::InlineAsm(inline) => {
479             report_inline_asm(cgcx,
480                               &llvm::twine_to_string(inline.message),
481                               inline.cookie);
482         }
483
484         llvm::diagnostic::Optimization(opt) => {
485             let enabled = match cgcx.remark {
486                 Passes::All => true,
487                 Passes::Some(ref v) => v.iter().any(|s| *s == opt.pass_name),
488             };
489
490             if enabled {
491                 diag_handler.note_without_error(&format!("optimization {} for {} at {}:{}:{}: {}",
492                                                 opt.kind.describe(),
493                                                 opt.pass_name,
494                                                 opt.filename,
495                                                 opt.line,
496                                                 opt.column,
497                                                 opt.message));
498             }
499         }
500         llvm::diagnostic::PGO(diagnostic_ref) |
501         llvm::diagnostic::Linker(diagnostic_ref) => {
502             let msg = llvm::build_string(|s| {
503                 llvm::LLVMRustWriteDiagnosticInfoToString(diagnostic_ref, s)
504             }).expect("non-UTF8 diagnostic");
505             diag_handler.warn(&msg);
506         }
507         llvm::diagnostic::UnknownDiagnostic(..) => {},
508     }
509 }
510
511 // Unsafe due to LLVM calls.
512 unsafe fn optimize(cgcx: &CodegenContext,
513                    diag_handler: &Handler,
514                    module: &ModuleCodegen,
515                    config: &ModuleConfig,
516                    timeline: &mut Timeline)
517     -> Result<(), FatalError>
518 {
519     let llmod = module.module_llvm.llmod();
520     let llcx = &*module.module_llvm.llcx;
521     let tm = &*module.module_llvm.tm;
522     let _handlers = DiagnosticHandlers::new(cgcx, diag_handler, llcx);
523
524     let module_name = module.name.clone();
525     let module_name = Some(&module_name[..]);
526
527     if config.emit_no_opt_bc {
528         let out = cgcx.output_filenames.temp_path_ext("no-opt.bc", module_name);
529         let out = path2cstr(&out);
530         llvm::LLVMWriteBitcodeToFile(llmod, out.as_ptr());
531     }
532
533     if config.opt_level.is_some() {
534         // Create the two optimizing pass managers. These mirror what clang
535         // does, and are by populated by LLVM's default PassManagerBuilder.
536         // Each manager has a different set of passes, but they also share
537         // some common passes.
538         let fpm = llvm::LLVMCreateFunctionPassManagerForModule(llmod);
539         let mpm = llvm::LLVMCreatePassManager();
540
541         {
542             // If we're verifying or linting, add them to the function pass
543             // manager.
544             let addpass = |pass_name: &str| {
545                 let pass_name = SmallCStr::new(pass_name);
546                 let pass = match llvm::LLVMRustFindAndCreatePass(pass_name.as_ptr()) {
547                     Some(pass) => pass,
548                     None => return false,
549                 };
550                 let pass_manager = match llvm::LLVMRustPassKind(pass) {
551                     llvm::PassKind::Function => &*fpm,
552                     llvm::PassKind::Module => &*mpm,
553                     llvm::PassKind::Other => {
554                         diag_handler.err("Encountered LLVM pass kind we can't handle");
555                         return true
556                     },
557                 };
558                 llvm::LLVMRustAddPass(pass_manager, pass);
559                 true
560             };
561
562             if config.verify_llvm_ir { assert!(addpass("verify")); }
563
564             // Some options cause LLVM bitcode to be emitted, which uses ThinLTOBuffers, so we need
565             // to make sure we run LLVM's NameAnonGlobals pass when emitting bitcode; otherwise
566             // we'll get errors in LLVM.
567             let using_thin_buffers = config.emit_bc || config.obj_is_bitcode
568                 || config.emit_bc_compressed || config.embed_bitcode;
569             let mut have_name_anon_globals_pass = false;
570             if !config.no_prepopulate_passes {
571                 llvm::LLVMRustAddAnalysisPasses(tm, fpm, llmod);
572                 llvm::LLVMRustAddAnalysisPasses(tm, mpm, llmod);
573                 let opt_level = config.opt_level.unwrap_or(llvm::CodeGenOptLevel::None);
574                 let prepare_for_thin_lto = cgcx.lto == Lto::Thin || cgcx.lto == Lto::ThinLocal ||
575                     (cgcx.lto != Lto::Fat && cgcx.opts.debugging_opts.cross_lang_lto.enabled());
576                 have_name_anon_globals_pass = have_name_anon_globals_pass || prepare_for_thin_lto;
577                 if using_thin_buffers && !prepare_for_thin_lto {
578                     assert!(addpass("name-anon-globals"));
579                     have_name_anon_globals_pass = true;
580                 }
581                 with_llvm_pmb(llmod, &config, opt_level, prepare_for_thin_lto, &mut |b| {
582                     llvm::LLVMPassManagerBuilderPopulateFunctionPassManager(b, fpm);
583                     llvm::LLVMPassManagerBuilderPopulateModulePassManager(b, mpm);
584                 })
585             }
586
587             for pass in &config.passes {
588                 if !addpass(pass) {
589                     diag_handler.warn(&format!("unknown pass `{}`, ignoring",
590                                             pass));
591                 }
592                 if pass == "name-anon-globals" {
593                     have_name_anon_globals_pass = true;
594                 }
595             }
596
597             for pass in &cgcx.plugin_passes {
598                 if !addpass(pass) {
599                     diag_handler.err(&format!("a plugin asked for LLVM pass \
600                                             `{}` but LLVM does not \
601                                             recognize it", pass));
602                 }
603                 if pass == "name-anon-globals" {
604                     have_name_anon_globals_pass = true;
605                 }
606             }
607
608             if using_thin_buffers && !have_name_anon_globals_pass {
609                 // As described above, this will probably cause an error in LLVM
610                 if config.no_prepopulate_passes {
611                     diag_handler.err("The current compilation is going to use thin LTO buffers \
612                                      without running LLVM's NameAnonGlobals pass. \
613                                      This will likely cause errors in LLVM. Consider adding \
614                                      -C passes=name-anon-globals to the compiler command line.");
615                 } else {
616                     bug!("We are using thin LTO buffers without running the NameAnonGlobals pass. \
617                          This will likely cause errors in LLVM and should never happen.");
618                 }
619             }
620         }
621
622         diag_handler.abort_if_errors();
623
624         // Finally, run the actual optimization passes
625         time_ext(config.time_passes,
626                  None,
627                  &format!("llvm function passes [{}]", module_name.unwrap()),
628                  || {
629             llvm::LLVMRustRunFunctionPassManager(fpm, llmod)
630         });
631         timeline.record("fpm");
632         time_ext(config.time_passes,
633                  None,
634                  &format!("llvm module passes [{}]", module_name.unwrap()),
635                  || {
636             llvm::LLVMRunPassManager(mpm, llmod)
637         });
638
639         // Deallocate managers that we're now done with
640         llvm::LLVMDisposePassManager(fpm);
641         llvm::LLVMDisposePassManager(mpm);
642     }
643     Ok(())
644 }
645
646 fn generate_lto_work(cgcx: &CodegenContext,
647                      modules: Vec<ModuleCodegen>,
648                      import_only_modules: Vec<(SerializedModule, WorkProduct)>)
649     -> Vec<(WorkItem, u64)>
650 {
651     let mut timeline = cgcx.time_graph.as_ref().map(|tg| {
652         tg.start(CODEGEN_WORKER_TIMELINE,
653                  CODEGEN_WORK_PACKAGE_KIND,
654                  "generate lto")
655     }).unwrap_or(Timeline::noop());
656     let (lto_modules, copy_jobs) = lto::run(cgcx, modules, import_only_modules, &mut timeline)
657         .unwrap_or_else(|e| e.raise());
658
659     let lto_modules = lto_modules.into_iter().map(|module| {
660         let cost = module.cost();
661         (WorkItem::LTO(module), cost)
662     });
663
664     let copy_jobs = copy_jobs.into_iter().map(|wp| {
665         (WorkItem::CopyPostLtoArtifacts(CachedModuleCodegen {
666             name: wp.cgu_name.clone(),
667             source: wp,
668         }), 0)
669     });
670
671     lto_modules.chain(copy_jobs).collect()
672 }
673
674 unsafe fn codegen(cgcx: &CodegenContext,
675                   diag_handler: &Handler,
676                   module: ModuleCodegen,
677                   config: &ModuleConfig,
678                   timeline: &mut Timeline)
679     -> Result<CompiledModule, FatalError>
680 {
681     timeline.record("codegen");
682     {
683         let llmod = module.module_llvm.llmod();
684         let llcx = &*module.module_llvm.llcx;
685         let tm = &*module.module_llvm.tm;
686         let module_name = module.name.clone();
687         let module_name = Some(&module_name[..]);
688         let handlers = DiagnosticHandlers::new(cgcx, diag_handler, llcx);
689
690         if cgcx.msvc_imps_needed {
691             create_msvc_imps(cgcx, llcx, llmod);
692         }
693
694         // A codegen-specific pass manager is used to generate object
695         // files for an LLVM module.
696         //
697         // Apparently each of these pass managers is a one-shot kind of
698         // thing, so we create a new one for each type of output. The
699         // pass manager passed to the closure should be ensured to not
700         // escape the closure itself, and the manager should only be
701         // used once.
702         unsafe fn with_codegen<'ll, F, R>(tm: &'ll llvm::TargetMachine,
703                                     llmod: &'ll llvm::Module,
704                                     no_builtins: bool,
705                                     f: F) -> R
706             where F: FnOnce(&'ll mut PassManager<'ll>) -> R,
707         {
708             let cpm = llvm::LLVMCreatePassManager();
709             llvm::LLVMRustAddAnalysisPasses(tm, cpm, llmod);
710             llvm::LLVMRustAddLibraryInfo(cpm, llmod, no_builtins);
711             f(cpm)
712         }
713
714         // If we don't have the integrated assembler, then we need to emit asm
715         // from LLVM and use `gcc` to create the object file.
716         let asm_to_obj = config.emit_obj && config.no_integrated_as;
717
718         // Change what we write and cleanup based on whether obj files are
719         // just llvm bitcode. In that case write bitcode, and possibly
720         // delete the bitcode if it wasn't requested. Don't generate the
721         // machine code, instead copy the .o file from the .bc
722         let write_bc = config.emit_bc || config.obj_is_bitcode;
723         let rm_bc = !config.emit_bc && config.obj_is_bitcode;
724         let write_obj = config.emit_obj && !config.obj_is_bitcode && !asm_to_obj;
725         let copy_bc_to_obj = config.emit_obj && config.obj_is_bitcode;
726
727         let bc_out = cgcx.output_filenames.temp_path(OutputType::Bitcode, module_name);
728         let obj_out = cgcx.output_filenames.temp_path(OutputType::Object, module_name);
729
730
731         if write_bc || config.emit_bc_compressed || config.embed_bitcode {
732             let thin = ThinBuffer::new(llmod);
733             let data = thin.data();
734             timeline.record("make-bc");
735
736             if write_bc {
737                 if let Err(e) = fs::write(&bc_out, data) {
738                     diag_handler.err(&format!("failed to write bytecode: {}", e));
739                 }
740                 timeline.record("write-bc");
741             }
742
743             if config.embed_bitcode {
744                 embed_bitcode(cgcx, llcx, llmod, Some(data));
745                 timeline.record("embed-bc");
746             }
747
748             if config.emit_bc_compressed {
749                 let dst = bc_out.with_extension(RLIB_BYTECODE_EXTENSION);
750                 let data = bytecode::encode(&module.name, data);
751                 if let Err(e) = fs::write(&dst, data) {
752                     diag_handler.err(&format!("failed to write bytecode: {}", e));
753                 }
754                 timeline.record("compress-bc");
755             }
756         } else if config.embed_bitcode_marker {
757             embed_bitcode(cgcx, llcx, llmod, None);
758         }
759
760         time_ext(config.time_passes, None, &format!("codegen passes [{}]", module_name.unwrap()),
761             || -> Result<(), FatalError> {
762             if config.emit_ir {
763                 let out = cgcx.output_filenames.temp_path(OutputType::LlvmAssembly, module_name);
764                 let out = path2cstr(&out);
765
766                 extern "C" fn demangle_callback(input_ptr: *const c_char,
767                                                 input_len: size_t,
768                                                 output_ptr: *mut c_char,
769                                                 output_len: size_t) -> size_t {
770                     let input = unsafe {
771                         slice::from_raw_parts(input_ptr as *const u8, input_len as usize)
772                     };
773
774                     let input = match str::from_utf8(input) {
775                         Ok(s) => s,
776                         Err(_) => return 0,
777                     };
778
779                     let output = unsafe {
780                         slice::from_raw_parts_mut(output_ptr as *mut u8, output_len as usize)
781                     };
782                     let mut cursor = io::Cursor::new(output);
783
784                     let demangled = match rustc_demangle::try_demangle(input) {
785                         Ok(d) => d,
786                         Err(_) => return 0,
787                     };
788
789                     if let Err(_) = write!(cursor, "{:#}", demangled) {
790                         // Possible only if provided buffer is not big enough
791                         return 0;
792                     }
793
794                     cursor.position() as size_t
795                 }
796
797                 with_codegen(tm, llmod, config.no_builtins, |cpm| {
798                     llvm::LLVMRustPrintModule(cpm, llmod, out.as_ptr(), demangle_callback);
799                     llvm::LLVMDisposePassManager(cpm);
800                 });
801                 timeline.record("ir");
802             }
803
804             if config.emit_asm || asm_to_obj {
805                 let path = cgcx.output_filenames.temp_path(OutputType::Assembly, module_name);
806
807                 // We can't use the same module for asm and binary output, because that triggers
808                 // various errors like invalid IR or broken binaries, so we might have to clone the
809                 // module to produce the asm output
810                 let llmod = if config.emit_obj {
811                     llvm::LLVMCloneModule(llmod)
812                 } else {
813                     llmod
814                 };
815                 with_codegen(tm, llmod, config.no_builtins, |cpm| {
816                     write_output_file(diag_handler, tm, cpm, llmod, &path,
817                                     llvm::FileType::AssemblyFile)
818                 })?;
819                 timeline.record("asm");
820             }
821
822             if write_obj {
823                 with_codegen(tm, llmod, config.no_builtins, |cpm| {
824                     write_output_file(diag_handler, tm, cpm, llmod, &obj_out,
825                                     llvm::FileType::ObjectFile)
826                 })?;
827                 timeline.record("obj");
828             } else if asm_to_obj {
829                 let assembly = cgcx.output_filenames.temp_path(OutputType::Assembly, module_name);
830                 run_assembler(cgcx, diag_handler, &assembly, &obj_out);
831                 timeline.record("asm_to_obj");
832
833                 if !config.emit_asm && !cgcx.save_temps {
834                     drop(fs::remove_file(&assembly));
835                 }
836             }
837
838             Ok(())
839         })?;
840
841         if copy_bc_to_obj {
842             debug!("copying bitcode {:?} to obj {:?}", bc_out, obj_out);
843             if let Err(e) = link_or_copy(&bc_out, &obj_out) {
844                 diag_handler.err(&format!("failed to copy bitcode to object file: {}", e));
845             }
846         }
847
848         if rm_bc {
849             debug!("removing_bitcode {:?}", bc_out);
850             if let Err(e) = fs::remove_file(&bc_out) {
851                 diag_handler.err(&format!("failed to remove bitcode: {}", e));
852             }
853         }
854
855         drop(handlers);
856     }
857     Ok(module.into_compiled_module(config.emit_obj,
858                                    config.emit_bc,
859                                    config.emit_bc_compressed,
860                                    &cgcx.output_filenames))
861 }
862
863 /// Embed the bitcode of an LLVM module in the LLVM module itself.
864 ///
865 /// This is done primarily for iOS where it appears to be standard to compile C
866 /// code at least with `-fembed-bitcode` which creates two sections in the
867 /// executable:
868 ///
869 /// * __LLVM,__bitcode
870 /// * __LLVM,__cmdline
871 ///
872 /// It appears *both* of these sections are necessary to get the linker to
873 /// recognize what's going on. For us though we just always throw in an empty
874 /// cmdline section.
875 ///
876 /// Furthermore debug/O1 builds don't actually embed bitcode but rather just
877 /// embed an empty section.
878 ///
879 /// Basically all of this is us attempting to follow in the footsteps of clang
880 /// on iOS. See #35968 for lots more info.
881 unsafe fn embed_bitcode(cgcx: &CodegenContext,
882                         llcx: &llvm::Context,
883                         llmod: &llvm::Module,
884                         bitcode: Option<&[u8]>) {
885     let llconst = C_bytes_in_context(llcx, bitcode.unwrap_or(&[]));
886     let llglobal = llvm::LLVMAddGlobal(
887         llmod,
888         val_ty(llconst),
889         "rustc.embedded.module\0".as_ptr() as *const _,
890     );
891     llvm::LLVMSetInitializer(llglobal, llconst);
892
893     let is_apple = cgcx.opts.target_triple.triple().contains("-ios") ||
894                    cgcx.opts.target_triple.triple().contains("-darwin");
895
896     let section = if is_apple {
897         "__LLVM,__bitcode\0"
898     } else {
899         ".llvmbc\0"
900     };
901     llvm::LLVMSetSection(llglobal, section.as_ptr() as *const _);
902     llvm::LLVMRustSetLinkage(llglobal, llvm::Linkage::PrivateLinkage);
903     llvm::LLVMSetGlobalConstant(llglobal, llvm::True);
904
905     let llconst = C_bytes_in_context(llcx, &[]);
906     let llglobal = llvm::LLVMAddGlobal(
907         llmod,
908         val_ty(llconst),
909         "rustc.embedded.cmdline\0".as_ptr() as *const _,
910     );
911     llvm::LLVMSetInitializer(llglobal, llconst);
912     let section = if  is_apple {
913         "__LLVM,__cmdline\0"
914     } else {
915         ".llvmcmd\0"
916     };
917     llvm::LLVMSetSection(llglobal, section.as_ptr() as *const _);
918     llvm::LLVMRustSetLinkage(llglobal, llvm::Linkage::PrivateLinkage);
919 }
920
921 pub(crate) struct CompiledModules {
922     pub modules: Vec<CompiledModule>,
923     pub metadata_module: CompiledModule,
924     pub allocator_module: Option<CompiledModule>,
925 }
926
927 fn need_crate_bitcode_for_rlib(sess: &Session) -> bool {
928     sess.crate_types.borrow().contains(&config::CrateType::Rlib) &&
929     sess.opts.output_types.contains_key(&OutputType::Exe)
930 }
931
932 fn need_pre_thin_lto_bitcode_for_incr_comp(sess: &Session) -> bool {
933     if sess.opts.incremental.is_none() {
934         return false
935     }
936
937     match sess.lto() {
938         Lto::Fat |
939         Lto::No => false,
940         Lto::Thin |
941         Lto::ThinLocal => true,
942     }
943 }
944
945 pub fn start_async_codegen(tcx: TyCtxt,
946                                time_graph: Option<TimeGraph>,
947                                metadata: EncodedMetadata,
948                                coordinator_receive: Receiver<Box<dyn Any + Send>>,
949                                total_cgus: usize)
950                                -> OngoingCodegen {
951     let sess = tcx.sess;
952     let crate_name = tcx.crate_name(LOCAL_CRATE);
953     let crate_hash = tcx.crate_hash(LOCAL_CRATE);
954     let no_builtins = attr::contains_name(&tcx.hir.krate().attrs, "no_builtins");
955     let subsystem = attr::first_attr_value_str_by_name(&tcx.hir.krate().attrs,
956                                                        "windows_subsystem");
957     let windows_subsystem = subsystem.map(|subsystem| {
958         if subsystem != "windows" && subsystem != "console" {
959             tcx.sess.fatal(&format!("invalid windows subsystem `{}`, only \
960                                      `windows` and `console` are allowed",
961                                     subsystem));
962         }
963         subsystem.to_string()
964     });
965
966     let linker_info = LinkerInfo::new(tcx);
967     let crate_info = CrateInfo::new(tcx);
968
969     // Figure out what we actually need to build.
970     let mut modules_config = ModuleConfig::new(sess.opts.cg.passes.clone());
971     let mut metadata_config = ModuleConfig::new(vec![]);
972     let mut allocator_config = ModuleConfig::new(vec![]);
973
974     if let Some(ref sanitizer) = sess.opts.debugging_opts.sanitizer {
975         match *sanitizer {
976             Sanitizer::Address => {
977                 modules_config.passes.push("asan".to_owned());
978                 modules_config.passes.push("asan-module".to_owned());
979             }
980             Sanitizer::Memory => {
981                 modules_config.passes.push("msan".to_owned())
982             }
983             Sanitizer::Thread => {
984                 modules_config.passes.push("tsan".to_owned())
985             }
986             _ => {}
987         }
988     }
989
990     if sess.opts.debugging_opts.profile {
991         modules_config.passes.push("insert-gcov-profiling".to_owned())
992     }
993
994     modules_config.pgo_gen = sess.opts.debugging_opts.pgo_gen.clone();
995     modules_config.pgo_use = sess.opts.debugging_opts.pgo_use.clone();
996
997     modules_config.opt_level = Some(get_llvm_opt_level(sess.opts.optimize));
998     modules_config.opt_size = Some(get_llvm_opt_size(sess.opts.optimize));
999
1000     // Save all versions of the bytecode if we're saving our temporaries.
1001     if sess.opts.cg.save_temps {
1002         modules_config.emit_no_opt_bc = true;
1003         modules_config.emit_pre_thin_lto_bc = true;
1004         modules_config.emit_bc = true;
1005         modules_config.emit_lto_bc = true;
1006         metadata_config.emit_bc = true;
1007         allocator_config.emit_bc = true;
1008     }
1009
1010     // Emit compressed bitcode files for the crate if we're emitting an rlib.
1011     // Whenever an rlib is created, the bitcode is inserted into the archive in
1012     // order to allow LTO against it.
1013     if need_crate_bitcode_for_rlib(sess) {
1014         modules_config.emit_bc_compressed = true;
1015         allocator_config.emit_bc_compressed = true;
1016     }
1017
1018     modules_config.emit_pre_thin_lto_bc =
1019         need_pre_thin_lto_bitcode_for_incr_comp(sess);
1020
1021     modules_config.no_integrated_as = tcx.sess.opts.cg.no_integrated_as ||
1022         tcx.sess.target.target.options.no_integrated_as;
1023
1024     for output_type in sess.opts.output_types.keys() {
1025         match *output_type {
1026             OutputType::Bitcode => { modules_config.emit_bc = true; }
1027             OutputType::LlvmAssembly => { modules_config.emit_ir = true; }
1028             OutputType::Assembly => {
1029                 modules_config.emit_asm = true;
1030                 // If we're not using the LLVM assembler, this function
1031                 // could be invoked specially with output_type_assembly, so
1032                 // in this case we still want the metadata object file.
1033                 if !sess.opts.output_types.contains_key(&OutputType::Assembly) {
1034                     metadata_config.emit_obj = true;
1035                     allocator_config.emit_obj = true;
1036                 }
1037             }
1038             OutputType::Object => { modules_config.emit_obj = true; }
1039             OutputType::Metadata => { metadata_config.emit_obj = true; }
1040             OutputType::Exe => {
1041                 modules_config.emit_obj = true;
1042                 metadata_config.emit_obj = true;
1043                 allocator_config.emit_obj = true;
1044             },
1045             OutputType::Mir => {}
1046             OutputType::DepInfo => {}
1047         }
1048     }
1049
1050     modules_config.set_flags(sess, no_builtins);
1051     metadata_config.set_flags(sess, no_builtins);
1052     allocator_config.set_flags(sess, no_builtins);
1053
1054     // Exclude metadata and allocator modules from time_passes output, since
1055     // they throw off the "LLVM passes" measurement.
1056     metadata_config.time_passes = false;
1057     allocator_config.time_passes = false;
1058
1059     let (shared_emitter, shared_emitter_main) = SharedEmitter::new();
1060     let (codegen_worker_send, codegen_worker_receive) = channel();
1061
1062     let coordinator_thread = start_executing_work(tcx,
1063                                                   &crate_info,
1064                                                   shared_emitter,
1065                                                   codegen_worker_send,
1066                                                   coordinator_receive,
1067                                                   total_cgus,
1068                                                   sess.jobserver.clone(),
1069                                                   time_graph.clone(),
1070                                                   Arc::new(modules_config),
1071                                                   Arc::new(metadata_config),
1072                                                   Arc::new(allocator_config));
1073
1074     OngoingCodegen {
1075         crate_name,
1076         crate_hash,
1077         metadata,
1078         windows_subsystem,
1079         linker_info,
1080         crate_info,
1081
1082         time_graph,
1083         coordinator_send: tcx.tx_to_llvm_workers.lock().clone(),
1084         codegen_worker_receive,
1085         shared_emitter_main,
1086         future: coordinator_thread,
1087         output_filenames: tcx.output_filenames(LOCAL_CRATE),
1088     }
1089 }
1090
1091 fn copy_all_cgu_workproducts_to_incr_comp_cache_dir(
1092     sess: &Session,
1093     compiled_modules: &CompiledModules,
1094 ) -> FxHashMap<WorkProductId, WorkProduct> {
1095     let mut work_products = FxHashMap::default();
1096
1097     if sess.opts.incremental.is_none() {
1098         return work_products;
1099     }
1100
1101     for module in compiled_modules.modules.iter().filter(|m| m.kind == ModuleKind::Regular) {
1102         let mut files = vec![];
1103
1104         if let Some(ref path) = module.object {
1105             files.push((WorkProductFileKind::Object, path.clone()));
1106         }
1107         if let Some(ref path) = module.bytecode {
1108             files.push((WorkProductFileKind::Bytecode, path.clone()));
1109         }
1110         if let Some(ref path) = module.bytecode_compressed {
1111             files.push((WorkProductFileKind::BytecodeCompressed, path.clone()));
1112         }
1113
1114         if let Some((id, product)) =
1115                 copy_cgu_workproducts_to_incr_comp_cache_dir(sess, &module.name, &files) {
1116             work_products.insert(id, product);
1117         }
1118     }
1119
1120     work_products
1121 }
1122
1123 fn produce_final_output_artifacts(sess: &Session,
1124                                   compiled_modules: &CompiledModules,
1125                                   crate_output: &OutputFilenames) {
1126     let mut user_wants_bitcode = false;
1127     let mut user_wants_objects = false;
1128
1129     // Produce final compile outputs.
1130     let copy_gracefully = |from: &Path, to: &Path| {
1131         if let Err(e) = fs::copy(from, to) {
1132             sess.err(&format!("could not copy {:?} to {:?}: {}", from, to, e));
1133         }
1134     };
1135
1136     let copy_if_one_unit = |output_type: OutputType,
1137                             keep_numbered: bool| {
1138         if compiled_modules.modules.len() == 1 {
1139             // 1) Only one codegen unit.  In this case it's no difficulty
1140             //    to copy `foo.0.x` to `foo.x`.
1141             let module_name = Some(&compiled_modules.modules[0].name[..]);
1142             let path = crate_output.temp_path(output_type, module_name);
1143             copy_gracefully(&path,
1144                             &crate_output.path(output_type));
1145             if !sess.opts.cg.save_temps && !keep_numbered {
1146                 // The user just wants `foo.x`, not `foo.#module-name#.x`.
1147                 remove(sess, &path);
1148             }
1149         } else {
1150             let ext = crate_output.temp_path(output_type, None)
1151                                   .extension()
1152                                   .unwrap()
1153                                   .to_str()
1154                                   .unwrap()
1155                                   .to_owned();
1156
1157             if crate_output.outputs.contains_key(&output_type) {
1158                 // 2) Multiple codegen units, with `--emit foo=some_name`.  We have
1159                 //    no good solution for this case, so warn the user.
1160                 sess.warn(&format!("ignoring emit path because multiple .{} files \
1161                                     were produced", ext));
1162             } else if crate_output.single_output_file.is_some() {
1163                 // 3) Multiple codegen units, with `-o some_name`.  We have
1164                 //    no good solution for this case, so warn the user.
1165                 sess.warn(&format!("ignoring -o because multiple .{} files \
1166                                     were produced", ext));
1167             } else {
1168                 // 4) Multiple codegen units, but no explicit name.  We
1169                 //    just leave the `foo.0.x` files in place.
1170                 // (We don't have to do any work in this case.)
1171             }
1172         }
1173     };
1174
1175     // Flag to indicate whether the user explicitly requested bitcode.
1176     // Otherwise, we produced it only as a temporary output, and will need
1177     // to get rid of it.
1178     for output_type in crate_output.outputs.keys() {
1179         match *output_type {
1180             OutputType::Bitcode => {
1181                 user_wants_bitcode = true;
1182                 // Copy to .bc, but always keep the .0.bc.  There is a later
1183                 // check to figure out if we should delete .0.bc files, or keep
1184                 // them for making an rlib.
1185                 copy_if_one_unit(OutputType::Bitcode, true);
1186             }
1187             OutputType::LlvmAssembly => {
1188                 copy_if_one_unit(OutputType::LlvmAssembly, false);
1189             }
1190             OutputType::Assembly => {
1191                 copy_if_one_unit(OutputType::Assembly, false);
1192             }
1193             OutputType::Object => {
1194                 user_wants_objects = true;
1195                 copy_if_one_unit(OutputType::Object, true);
1196             }
1197             OutputType::Mir |
1198             OutputType::Metadata |
1199             OutputType::Exe |
1200             OutputType::DepInfo => {}
1201         }
1202     }
1203
1204     // Clean up unwanted temporary files.
1205
1206     // We create the following files by default:
1207     //  - #crate#.#module-name#.bc
1208     //  - #crate#.#module-name#.o
1209     //  - #crate#.crate.metadata.bc
1210     //  - #crate#.crate.metadata.o
1211     //  - #crate#.o (linked from crate.##.o)
1212     //  - #crate#.bc (copied from crate.##.bc)
1213     // We may create additional files if requested by the user (through
1214     // `-C save-temps` or `--emit=` flags).
1215
1216     if !sess.opts.cg.save_temps {
1217         // Remove the temporary .#module-name#.o objects.  If the user didn't
1218         // explicitly request bitcode (with --emit=bc), and the bitcode is not
1219         // needed for building an rlib, then we must remove .#module-name#.bc as
1220         // well.
1221
1222         // Specific rules for keeping .#module-name#.bc:
1223         //  - If the user requested bitcode (`user_wants_bitcode`), and
1224         //    codegen_units > 1, then keep it.
1225         //  - If the user requested bitcode but codegen_units == 1, then we
1226         //    can toss .#module-name#.bc because we copied it to .bc earlier.
1227         //  - If we're not building an rlib and the user didn't request
1228         //    bitcode, then delete .#module-name#.bc.
1229         // If you change how this works, also update back::link::link_rlib,
1230         // where .#module-name#.bc files are (maybe) deleted after making an
1231         // rlib.
1232         let needs_crate_object = crate_output.outputs.contains_key(&OutputType::Exe);
1233
1234         let keep_numbered_bitcode = user_wants_bitcode && sess.codegen_units() > 1;
1235
1236         let keep_numbered_objects = needs_crate_object ||
1237                 (user_wants_objects && sess.codegen_units() > 1);
1238
1239         for module in compiled_modules.modules.iter() {
1240             if let Some(ref path) = module.object {
1241                 if !keep_numbered_objects {
1242                     remove(sess, path);
1243                 }
1244             }
1245
1246             if let Some(ref path) = module.bytecode {
1247                 if !keep_numbered_bitcode {
1248                     remove(sess, path);
1249                 }
1250             }
1251         }
1252
1253         if !user_wants_bitcode {
1254             if let Some(ref path) = compiled_modules.metadata_module.bytecode {
1255                 remove(sess, &path);
1256             }
1257
1258             if let Some(ref allocator_module) = compiled_modules.allocator_module {
1259                 if let Some(ref path) = allocator_module.bytecode {
1260                     remove(sess, path);
1261                 }
1262             }
1263         }
1264     }
1265
1266     // We leave the following files around by default:
1267     //  - #crate#.o
1268     //  - #crate#.crate.metadata.o
1269     //  - #crate#.bc
1270     // These are used in linking steps and will be cleaned up afterward.
1271 }
1272
1273 pub(crate) fn dump_incremental_data(_codegen_results: &CodegenResults) {
1274     // FIXME(mw): This does not work at the moment because the situation has
1275     //            become more complicated due to incremental LTO. Now a CGU
1276     //            can have more than two caching states.
1277     // println!("[incremental] Re-using {} out of {} modules",
1278     //           codegen_results.modules.iter().filter(|m| m.pre_existing).count(),
1279     //           codegen_results.modules.len());
1280 }
1281
1282 enum WorkItem {
1283     /// Optimize a newly codegened, totally unoptimized module.
1284     Optimize(ModuleCodegen),
1285     /// Copy the post-LTO artifacts from the incremental cache to the output
1286     /// directory.
1287     CopyPostLtoArtifacts(CachedModuleCodegen),
1288     /// Perform (Thin)LTO on the given module.
1289     LTO(lto::LtoModuleCodegen),
1290 }
1291
1292 impl WorkItem {
1293     fn module_kind(&self) -> ModuleKind {
1294         match *self {
1295             WorkItem::Optimize(ref m) => m.kind,
1296             WorkItem::CopyPostLtoArtifacts(_) |
1297             WorkItem::LTO(_) => ModuleKind::Regular,
1298         }
1299     }
1300
1301     fn name(&self) -> String {
1302         match *self {
1303             WorkItem::Optimize(ref m) => format!("optimize: {}", m.name),
1304             WorkItem::CopyPostLtoArtifacts(ref m) => format!("copy post LTO artifacts: {}", m.name),
1305             WorkItem::LTO(ref m) => format!("lto: {}", m.name()),
1306         }
1307     }
1308 }
1309
1310 enum WorkItemResult {
1311     Compiled(CompiledModule),
1312     NeedsLTO(ModuleCodegen),
1313 }
1314
1315 fn execute_work_item(cgcx: &CodegenContext,
1316                      work_item: WorkItem,
1317                      timeline: &mut Timeline)
1318     -> Result<WorkItemResult, FatalError>
1319 {
1320     let module_config = cgcx.config(work_item.module_kind());
1321
1322     match work_item {
1323         WorkItem::Optimize(module) => {
1324             execute_optimize_work_item(cgcx, module, module_config, timeline)
1325         }
1326         WorkItem::CopyPostLtoArtifacts(module) => {
1327             execute_copy_from_cache_work_item(cgcx, module, module_config, timeline)
1328         }
1329         WorkItem::LTO(module) => {
1330             execute_lto_work_item(cgcx, module, module_config, timeline)
1331         }
1332     }
1333 }
1334
1335 fn execute_optimize_work_item(cgcx: &CodegenContext,
1336                               module: ModuleCodegen,
1337                               module_config: &ModuleConfig,
1338                               timeline: &mut Timeline)
1339     -> Result<WorkItemResult, FatalError>
1340 {
1341     let diag_handler = cgcx.create_diag_handler();
1342
1343     unsafe {
1344         optimize(cgcx, &diag_handler, &module, module_config, timeline)?;
1345     }
1346
1347     let linker_does_lto = cgcx.opts.debugging_opts.cross_lang_lto.enabled();
1348
1349     // After we've done the initial round of optimizations we need to
1350     // decide whether to synchronously codegen this module or ship it
1351     // back to the coordinator thread for further LTO processing (which
1352     // has to wait for all the initial modules to be optimized).
1353     //
1354     // Here we dispatch based on the `cgcx.lto` and kind of module we're
1355     // codegenning...
1356     let needs_lto = match cgcx.lto {
1357         Lto::No => false,
1358
1359         // If the linker does LTO, we don't have to do it. Note that we
1360         // keep doing full LTO, if it is requested, as not to break the
1361         // assumption that the output will be a single module.
1362         Lto::Thin | Lto::ThinLocal if linker_does_lto => false,
1363
1364         // Here we've got a full crate graph LTO requested. We ignore
1365         // this, however, if the crate type is only an rlib as there's
1366         // no full crate graph to process, that'll happen later.
1367         //
1368         // This use case currently comes up primarily for targets that
1369         // require LTO so the request for LTO is always unconditionally
1370         // passed down to the backend, but we don't actually want to do
1371         // anything about it yet until we've got a final product.
1372         Lto::Fat | Lto::Thin => {
1373             cgcx.crate_types.len() != 1 ||
1374                 cgcx.crate_types[0] != config::CrateType::Rlib
1375         }
1376
1377         // When we're automatically doing ThinLTO for multi-codegen-unit
1378         // builds we don't actually want to LTO the allocator modules if
1379         // it shows up. This is due to various linker shenanigans that
1380         // we'll encounter later.
1381         Lto::ThinLocal => {
1382             module.kind != ModuleKind::Allocator
1383         }
1384     };
1385
1386     // Metadata modules never participate in LTO regardless of the lto
1387     // settings.
1388     let needs_lto = needs_lto && module.kind != ModuleKind::Metadata;
1389
1390     if needs_lto {
1391         Ok(WorkItemResult::NeedsLTO(module))
1392     } else {
1393         let module = unsafe {
1394             codegen(cgcx, &diag_handler, module, module_config, timeline)?
1395         };
1396         Ok(WorkItemResult::Compiled(module))
1397     }
1398 }
1399
1400 fn execute_copy_from_cache_work_item(cgcx: &CodegenContext,
1401                                      module: CachedModuleCodegen,
1402                                      module_config: &ModuleConfig,
1403                                      _: &mut Timeline)
1404     -> Result<WorkItemResult, FatalError>
1405 {
1406     let incr_comp_session_dir = cgcx.incr_comp_session_dir
1407                                     .as_ref()
1408                                     .unwrap();
1409     let mut object = None;
1410     let mut bytecode = None;
1411     let mut bytecode_compressed = None;
1412     for (kind, saved_file) in &module.source.saved_files {
1413         let obj_out = match kind {
1414             WorkProductFileKind::Object => {
1415                 let path = cgcx.output_filenames.temp_path(OutputType::Object,
1416                                                            Some(&module.name));
1417                 object = Some(path.clone());
1418                 path
1419             }
1420             WorkProductFileKind::Bytecode => {
1421                 let path = cgcx.output_filenames.temp_path(OutputType::Bitcode,
1422                                                            Some(&module.name));
1423                 bytecode = Some(path.clone());
1424                 path
1425             }
1426             WorkProductFileKind::BytecodeCompressed => {
1427                 let path = cgcx.output_filenames.temp_path(OutputType::Bitcode,
1428                                                            Some(&module.name))
1429                     .with_extension(RLIB_BYTECODE_EXTENSION);
1430                 bytecode_compressed = Some(path.clone());
1431                 path
1432             }
1433         };
1434         let source_file = in_incr_comp_dir(&incr_comp_session_dir,
1435                                            &saved_file);
1436         debug!("copying pre-existing module `{}` from {:?} to {}",
1437                module.name,
1438                source_file,
1439                obj_out.display());
1440         match link_or_copy(&source_file, &obj_out) {
1441             Ok(_) => { }
1442             Err(err) => {
1443                 let diag_handler = cgcx.create_diag_handler();
1444                 diag_handler.err(&format!("unable to copy {} to {}: {}",
1445                                           source_file.display(),
1446                                           obj_out.display(),
1447                                           err));
1448             }
1449         }
1450     }
1451
1452     assert_eq!(object.is_some(), module_config.emit_obj);
1453     assert_eq!(bytecode.is_some(), module_config.emit_bc);
1454     assert_eq!(bytecode_compressed.is_some(), module_config.emit_bc_compressed);
1455
1456     Ok(WorkItemResult::Compiled(CompiledModule {
1457         name: module.name,
1458         kind: ModuleKind::Regular,
1459         object,
1460         bytecode,
1461         bytecode_compressed,
1462     }))
1463 }
1464
1465 fn execute_lto_work_item(cgcx: &CodegenContext,
1466                          mut module: lto::LtoModuleCodegen,
1467                          module_config: &ModuleConfig,
1468                          timeline: &mut Timeline)
1469     -> Result<WorkItemResult, FatalError>
1470 {
1471     let diag_handler = cgcx.create_diag_handler();
1472
1473     unsafe {
1474         let module = module.optimize(cgcx, timeline)?;
1475         let module = codegen(cgcx, &diag_handler, module, module_config, timeline)?;
1476         Ok(WorkItemResult::Compiled(module))
1477     }
1478 }
1479
1480 enum Message {
1481     Token(io::Result<Acquired>),
1482     NeedsLTO {
1483         result: ModuleCodegen,
1484         worker_id: usize,
1485     },
1486     Done {
1487         result: Result<CompiledModule, ()>,
1488         worker_id: usize,
1489     },
1490     CodegenDone {
1491         llvm_work_item: WorkItem,
1492         cost: u64,
1493     },
1494     AddImportOnlyModule {
1495         module_data: SerializedModule,
1496         work_product: WorkProduct,
1497     },
1498     CodegenComplete,
1499     CodegenItem,
1500     CodegenAborted,
1501 }
1502
1503 struct Diagnostic {
1504     msg: String,
1505     code: Option<DiagnosticId>,
1506     lvl: Level,
1507 }
1508
1509 #[derive(PartialEq, Clone, Copy, Debug)]
1510 enum MainThreadWorkerState {
1511     Idle,
1512     Codegenning,
1513     LLVMing,
1514 }
1515
1516 fn start_executing_work(tcx: TyCtxt,
1517                         crate_info: &CrateInfo,
1518                         shared_emitter: SharedEmitter,
1519                         codegen_worker_send: Sender<Message>,
1520                         coordinator_receive: Receiver<Box<dyn Any + Send>>,
1521                         total_cgus: usize,
1522                         jobserver: Client,
1523                         time_graph: Option<TimeGraph>,
1524                         modules_config: Arc<ModuleConfig>,
1525                         metadata_config: Arc<ModuleConfig>,
1526                         allocator_config: Arc<ModuleConfig>)
1527                         -> thread::JoinHandle<Result<CompiledModules, ()>> {
1528     let coordinator_send = tcx.tx_to_llvm_workers.lock().clone();
1529     let sess = tcx.sess;
1530
1531     // Compute the set of symbols we need to retain when doing LTO (if we need to)
1532     let exported_symbols = {
1533         let mut exported_symbols = FxHashMap::default();
1534
1535         let copy_symbols = |cnum| {
1536             let symbols = tcx.exported_symbols(cnum)
1537                              .iter()
1538                              .map(|&(s, lvl)| (s.symbol_name(tcx).to_string(), lvl))
1539                              .collect();
1540             Arc::new(symbols)
1541         };
1542
1543         match sess.lto() {
1544             Lto::No => None,
1545             Lto::ThinLocal => {
1546                 exported_symbols.insert(LOCAL_CRATE, copy_symbols(LOCAL_CRATE));
1547                 Some(Arc::new(exported_symbols))
1548             }
1549             Lto::Fat | Lto::Thin => {
1550                 exported_symbols.insert(LOCAL_CRATE, copy_symbols(LOCAL_CRATE));
1551                 for &cnum in tcx.crates().iter() {
1552                     exported_symbols.insert(cnum, copy_symbols(cnum));
1553                 }
1554                 Some(Arc::new(exported_symbols))
1555             }
1556         }
1557     };
1558
1559     // First up, convert our jobserver into a helper thread so we can use normal
1560     // mpsc channels to manage our messages and such.
1561     // After we've requested tokens then we'll, when we can,
1562     // get tokens on `coordinator_receive` which will
1563     // get managed in the main loop below.
1564     let coordinator_send2 = coordinator_send.clone();
1565     let helper = jobserver.into_helper_thread(move |token| {
1566         drop(coordinator_send2.send(Box::new(Message::Token(token))));
1567     }).expect("failed to spawn helper thread");
1568
1569     let mut each_linked_rlib_for_lto = Vec::new();
1570     drop(link::each_linked_rlib(sess, crate_info, &mut |cnum, path| {
1571         if link::ignored_for_lto(sess, crate_info, cnum) {
1572             return
1573         }
1574         each_linked_rlib_for_lto.push((cnum, path.to_path_buf()));
1575     }));
1576
1577     let assembler_cmd = if modules_config.no_integrated_as {
1578         // HACK: currently we use linker (gcc) as our assembler
1579         let (linker, flavor) = link::linker_and_flavor(sess);
1580
1581         let (name, mut cmd) = get_linker(sess, &linker, flavor);
1582         cmd.args(&sess.target.target.options.asm_args);
1583         Some(Arc::new(AssemblerCommand {
1584             name,
1585             cmd,
1586         }))
1587     } else {
1588         None
1589     };
1590
1591     let cgcx = CodegenContext {
1592         crate_types: sess.crate_types.borrow().clone(),
1593         each_linked_rlib_for_lto,
1594         lto: sess.lto(),
1595         no_landing_pads: sess.no_landing_pads(),
1596         fewer_names: sess.fewer_names(),
1597         save_temps: sess.opts.cg.save_temps,
1598         opts: Arc::new(sess.opts.clone()),
1599         time_passes: sess.time_passes(),
1600         exported_symbols,
1601         plugin_passes: sess.plugin_llvm_passes.borrow().clone(),
1602         remark: sess.opts.cg.remark.clone(),
1603         worker: 0,
1604         incr_comp_session_dir: sess.incr_comp_session_dir_opt().map(|r| r.clone()),
1605         cgu_reuse_tracker: sess.cgu_reuse_tracker.clone(),
1606         coordinator_send,
1607         diag_emitter: shared_emitter.clone(),
1608         time_graph,
1609         output_filenames: tcx.output_filenames(LOCAL_CRATE),
1610         regular_module_config: modules_config,
1611         metadata_module_config: metadata_config,
1612         allocator_module_config: allocator_config,
1613         tm_factory: target_machine_factory(tcx.sess, false),
1614         total_cgus,
1615         msvc_imps_needed: msvc_imps_needed(tcx),
1616         target_pointer_width: tcx.sess.target.target.target_pointer_width.clone(),
1617         debuginfo: tcx.sess.opts.debuginfo,
1618         assembler_cmd,
1619     };
1620
1621     // This is the "main loop" of parallel work happening for parallel codegen.
1622     // It's here that we manage parallelism, schedule work, and work with
1623     // messages coming from clients.
1624     //
1625     // There are a few environmental pre-conditions that shape how the system
1626     // is set up:
1627     //
1628     // - Error reporting only can happen on the main thread because that's the
1629     //   only place where we have access to the compiler `Session`.
1630     // - LLVM work can be done on any thread.
1631     // - Codegen can only happen on the main thread.
1632     // - Each thread doing substantial work most be in possession of a `Token`
1633     //   from the `Jobserver`.
1634     // - The compiler process always holds one `Token`. Any additional `Tokens`
1635     //   have to be requested from the `Jobserver`.
1636     //
1637     // Error Reporting
1638     // ===============
1639     // The error reporting restriction is handled separately from the rest: We
1640     // set up a `SharedEmitter` the holds an open channel to the main thread.
1641     // When an error occurs on any thread, the shared emitter will send the
1642     // error message to the receiver main thread (`SharedEmitterMain`). The
1643     // main thread will periodically query this error message queue and emit
1644     // any error messages it has received. It might even abort compilation if
1645     // has received a fatal error. In this case we rely on all other threads
1646     // being torn down automatically with the main thread.
1647     // Since the main thread will often be busy doing codegen work, error
1648     // reporting will be somewhat delayed, since the message queue can only be
1649     // checked in between to work packages.
1650     //
1651     // Work Processing Infrastructure
1652     // ==============================
1653     // The work processing infrastructure knows three major actors:
1654     //
1655     // - the coordinator thread,
1656     // - the main thread, and
1657     // - LLVM worker threads
1658     //
1659     // The coordinator thread is running a message loop. It instructs the main
1660     // thread about what work to do when, and it will spawn off LLVM worker
1661     // threads as open LLVM WorkItems become available.
1662     //
1663     // The job of the main thread is to codegen CGUs into LLVM work package
1664     // (since the main thread is the only thread that can do this). The main
1665     // thread will block until it receives a message from the coordinator, upon
1666     // which it will codegen one CGU, send it to the coordinator and block
1667     // again. This way the coordinator can control what the main thread is
1668     // doing.
1669     //
1670     // The coordinator keeps a queue of LLVM WorkItems, and when a `Token` is
1671     // available, it will spawn off a new LLVM worker thread and let it process
1672     // that a WorkItem. When a LLVM worker thread is done with its WorkItem,
1673     // it will just shut down, which also frees all resources associated with
1674     // the given LLVM module, and sends a message to the coordinator that the
1675     // has been completed.
1676     //
1677     // Work Scheduling
1678     // ===============
1679     // The scheduler's goal is to minimize the time it takes to complete all
1680     // work there is, however, we also want to keep memory consumption low
1681     // if possible. These two goals are at odds with each other: If memory
1682     // consumption were not an issue, we could just let the main thread produce
1683     // LLVM WorkItems at full speed, assuring maximal utilization of
1684     // Tokens/LLVM worker threads. However, since codegen usual is faster
1685     // than LLVM processing, the queue of LLVM WorkItems would fill up and each
1686     // WorkItem potentially holds on to a substantial amount of memory.
1687     //
1688     // So the actual goal is to always produce just enough LLVM WorkItems as
1689     // not to starve our LLVM worker threads. That means, once we have enough
1690     // WorkItems in our queue, we can block the main thread, so it does not
1691     // produce more until we need them.
1692     //
1693     // Doing LLVM Work on the Main Thread
1694     // ----------------------------------
1695     // Since the main thread owns the compiler processes implicit `Token`, it is
1696     // wasteful to keep it blocked without doing any work. Therefore, what we do
1697     // in this case is: We spawn off an additional LLVM worker thread that helps
1698     // reduce the queue. The work it is doing corresponds to the implicit
1699     // `Token`. The coordinator will mark the main thread as being busy with
1700     // LLVM work. (The actual work happens on another OS thread but we just care
1701     // about `Tokens`, not actual threads).
1702     //
1703     // When any LLVM worker thread finishes while the main thread is marked as
1704     // "busy with LLVM work", we can do a little switcheroo: We give the Token
1705     // of the just finished thread to the LLVM worker thread that is working on
1706     // behalf of the main thread's implicit Token, thus freeing up the main
1707     // thread again. The coordinator can then again decide what the main thread
1708     // should do. This allows the coordinator to make decisions at more points
1709     // in time.
1710     //
1711     // Striking a Balance between Throughput and Memory Consumption
1712     // ------------------------------------------------------------
1713     // Since our two goals, (1) use as many Tokens as possible and (2) keep
1714     // memory consumption as low as possible, are in conflict with each other,
1715     // we have to find a trade off between them. Right now, the goal is to keep
1716     // all workers busy, which means that no worker should find the queue empty
1717     // when it is ready to start.
1718     // How do we do achieve this? Good question :) We actually never know how
1719     // many `Tokens` are potentially available so it's hard to say how much to
1720     // fill up the queue before switching the main thread to LLVM work. Also we
1721     // currently don't have a means to estimate how long a running LLVM worker
1722     // will still be busy with it's current WorkItem. However, we know the
1723     // maximal count of available Tokens that makes sense (=the number of CPU
1724     // cores), so we can take a conservative guess. The heuristic we use here
1725     // is implemented in the `queue_full_enough()` function.
1726     //
1727     // Some Background on Jobservers
1728     // -----------------------------
1729     // It's worth also touching on the management of parallelism here. We don't
1730     // want to just spawn a thread per work item because while that's optimal
1731     // parallelism it may overload a system with too many threads or violate our
1732     // configuration for the maximum amount of cpu to use for this process. To
1733     // manage this we use the `jobserver` crate.
1734     //
1735     // Job servers are an artifact of GNU make and are used to manage
1736     // parallelism between processes. A jobserver is a glorified IPC semaphore
1737     // basically. Whenever we want to run some work we acquire the semaphore,
1738     // and whenever we're done with that work we release the semaphore. In this
1739     // manner we can ensure that the maximum number of parallel workers is
1740     // capped at any one point in time.
1741     //
1742     // LTO and the coordinator thread
1743     // ------------------------------
1744     //
1745     // The final job the coordinator thread is responsible for is managing LTO
1746     // and how that works. When LTO is requested what we'll to is collect all
1747     // optimized LLVM modules into a local vector on the coordinator. Once all
1748     // modules have been codegened and optimized we hand this to the `lto`
1749     // module for further optimization. The `lto` module will return back a list
1750     // of more modules to work on, which the coordinator will continue to spawn
1751     // work for.
1752     //
1753     // Each LLVM module is automatically sent back to the coordinator for LTO if
1754     // necessary. There's already optimizations in place to avoid sending work
1755     // back to the coordinator if LTO isn't requested.
1756     return thread::spawn(move || {
1757         // We pretend to be within the top-level LLVM time-passes task here:
1758         set_time_depth(1);
1759
1760         let max_workers = ::num_cpus::get();
1761         let mut worker_id_counter = 0;
1762         let mut free_worker_ids = Vec::new();
1763         let mut get_worker_id = |free_worker_ids: &mut Vec<usize>| {
1764             if let Some(id) = free_worker_ids.pop() {
1765                 id
1766             } else {
1767                 let id = worker_id_counter;
1768                 worker_id_counter += 1;
1769                 id
1770             }
1771         };
1772
1773         // This is where we collect codegen units that have gone all the way
1774         // through codegen and LLVM.
1775         let mut compiled_modules = vec![];
1776         let mut compiled_metadata_module = None;
1777         let mut compiled_allocator_module = None;
1778         let mut needs_lto = Vec::new();
1779         let mut lto_import_only_modules = Vec::new();
1780         let mut started_lto = false;
1781         let mut codegen_aborted = false;
1782
1783         // This flag tracks whether all items have gone through codegens
1784         let mut codegen_done = false;
1785
1786         // This is the queue of LLVM work items that still need processing.
1787         let mut work_items = Vec::<(WorkItem, u64)>::new();
1788
1789         // This are the Jobserver Tokens we currently hold. Does not include
1790         // the implicit Token the compiler process owns no matter what.
1791         let mut tokens = Vec::new();
1792
1793         let mut main_thread_worker_state = MainThreadWorkerState::Idle;
1794         let mut running = 0;
1795
1796         let mut llvm_start_time = None;
1797
1798         // Run the message loop while there's still anything that needs message
1799         // processing. Note that as soon as codegen is aborted we simply want to
1800         // wait for all existing work to finish, so many of the conditions here
1801         // only apply if codegen hasn't been aborted as they represent pending
1802         // work to be done.
1803         while !codegen_done ||
1804               running > 0 ||
1805               (!codegen_aborted && (
1806                   work_items.len() > 0 ||
1807                   needs_lto.len() > 0 ||
1808                   lto_import_only_modules.len() > 0 ||
1809                   main_thread_worker_state != MainThreadWorkerState::Idle
1810               ))
1811         {
1812
1813             // While there are still CGUs to be codegened, the coordinator has
1814             // to decide how to utilize the compiler processes implicit Token:
1815             // For codegenning more CGU or for running them through LLVM.
1816             if !codegen_done {
1817                 if main_thread_worker_state == MainThreadWorkerState::Idle {
1818                     if !queue_full_enough(work_items.len(), running, max_workers) {
1819                         // The queue is not full enough, codegen more items:
1820                         if let Err(_) = codegen_worker_send.send(Message::CodegenItem) {
1821                             panic!("Could not send Message::CodegenItem to main thread")
1822                         }
1823                         main_thread_worker_state = MainThreadWorkerState::Codegenning;
1824                     } else {
1825                         // The queue is full enough to not let the worker
1826                         // threads starve. Use the implicit Token to do some
1827                         // LLVM work too.
1828                         let (item, _) = work_items.pop()
1829                             .expect("queue empty - queue_full_enough() broken?");
1830                         let cgcx = CodegenContext {
1831                             worker: get_worker_id(&mut free_worker_ids),
1832                             .. cgcx.clone()
1833                         };
1834                         maybe_start_llvm_timer(cgcx.config(item.module_kind()),
1835                                                &mut llvm_start_time);
1836                         main_thread_worker_state = MainThreadWorkerState::LLVMing;
1837                         spawn_work(cgcx, item);
1838                     }
1839                 }
1840             } else if codegen_aborted {
1841                 // don't queue up any more work if codegen was aborted, we're
1842                 // just waiting for our existing children to finish
1843             } else {
1844                 // If we've finished everything related to normal codegen
1845                 // then it must be the case that we've got some LTO work to do.
1846                 // Perform the serial work here of figuring out what we're
1847                 // going to LTO and then push a bunch of work items onto our
1848                 // queue to do LTO
1849                 if work_items.len() == 0 &&
1850                    running == 0 &&
1851                    main_thread_worker_state == MainThreadWorkerState::Idle {
1852                     assert!(!started_lto);
1853                     assert!(needs_lto.len() + lto_import_only_modules.len() > 0);
1854                     started_lto = true;
1855                     let modules = mem::replace(&mut needs_lto, Vec::new());
1856                     let import_only_modules =
1857                         mem::replace(&mut lto_import_only_modules, Vec::new());
1858                     for (work, cost) in generate_lto_work(&cgcx, modules, import_only_modules) {
1859                         let insertion_index = work_items
1860                             .binary_search_by_key(&cost, |&(_, cost)| cost)
1861                             .unwrap_or_else(|e| e);
1862                         work_items.insert(insertion_index, (work, cost));
1863                         if !cgcx.opts.debugging_opts.no_parallel_llvm {
1864                             helper.request_token();
1865                         }
1866                     }
1867                 }
1868
1869                 // In this branch, we know that everything has been codegened,
1870                 // so it's just a matter of determining whether the implicit
1871                 // Token is free to use for LLVM work.
1872                 match main_thread_worker_state {
1873                     MainThreadWorkerState::Idle => {
1874                         if let Some((item, _)) = work_items.pop() {
1875                             let cgcx = CodegenContext {
1876                                 worker: get_worker_id(&mut free_worker_ids),
1877                                 .. cgcx.clone()
1878                             };
1879                             maybe_start_llvm_timer(cgcx.config(item.module_kind()),
1880                                                    &mut llvm_start_time);
1881                             main_thread_worker_state = MainThreadWorkerState::LLVMing;
1882                             spawn_work(cgcx, item);
1883                         } else {
1884                             // There is no unstarted work, so let the main thread
1885                             // take over for a running worker. Otherwise the
1886                             // implicit token would just go to waste.
1887                             // We reduce the `running` counter by one. The
1888                             // `tokens.truncate()` below will take care of
1889                             // giving the Token back.
1890                             debug_assert!(running > 0);
1891                             running -= 1;
1892                             main_thread_worker_state = MainThreadWorkerState::LLVMing;
1893                         }
1894                     }
1895                     MainThreadWorkerState::Codegenning => {
1896                         bug!("codegen worker should not be codegenning after \
1897                               codegen was already completed")
1898                     }
1899                     MainThreadWorkerState::LLVMing => {
1900                         // Already making good use of that token
1901                     }
1902                 }
1903             }
1904
1905             // Spin up what work we can, only doing this while we've got available
1906             // parallelism slots and work left to spawn.
1907             while !codegen_aborted && work_items.len() > 0 && running < tokens.len() {
1908                 let (item, _) = work_items.pop().unwrap();
1909
1910                 maybe_start_llvm_timer(cgcx.config(item.module_kind()),
1911                                        &mut llvm_start_time);
1912
1913                 let cgcx = CodegenContext {
1914                     worker: get_worker_id(&mut free_worker_ids),
1915                     .. cgcx.clone()
1916                 };
1917
1918                 spawn_work(cgcx, item);
1919                 running += 1;
1920             }
1921
1922             // Relinquish accidentally acquired extra tokens
1923             tokens.truncate(running);
1924
1925             let msg = coordinator_receive.recv().unwrap();
1926             match *msg.downcast::<Message>().ok().unwrap() {
1927                 // Save the token locally and the next turn of the loop will use
1928                 // this to spawn a new unit of work, or it may get dropped
1929                 // immediately if we have no more work to spawn.
1930                 Message::Token(token) => {
1931                     match token {
1932                         Ok(token) => {
1933                             tokens.push(token);
1934
1935                             if main_thread_worker_state == MainThreadWorkerState::LLVMing {
1936                                 // If the main thread token is used for LLVM work
1937                                 // at the moment, we turn that thread into a regular
1938                                 // LLVM worker thread, so the main thread is free
1939                                 // to react to codegen demand.
1940                                 main_thread_worker_state = MainThreadWorkerState::Idle;
1941                                 running += 1;
1942                             }
1943                         }
1944                         Err(e) => {
1945                             let msg = &format!("failed to acquire jobserver token: {}", e);
1946                             shared_emitter.fatal(msg);
1947                             // Exit the coordinator thread
1948                             panic!("{}", msg)
1949                         }
1950                     }
1951                 }
1952
1953                 Message::CodegenDone { llvm_work_item, cost } => {
1954                     // We keep the queue sorted by estimated processing cost,
1955                     // so that more expensive items are processed earlier. This
1956                     // is good for throughput as it gives the main thread more
1957                     // time to fill up the queue and it avoids scheduling
1958                     // expensive items to the end.
1959                     // Note, however, that this is not ideal for memory
1960                     // consumption, as LLVM module sizes are not evenly
1961                     // distributed.
1962                     let insertion_index =
1963                         work_items.binary_search_by_key(&cost, |&(_, cost)| cost);
1964                     let insertion_index = match insertion_index {
1965                         Ok(idx) | Err(idx) => idx
1966                     };
1967                     work_items.insert(insertion_index, (llvm_work_item, cost));
1968
1969                     if !cgcx.opts.debugging_opts.no_parallel_llvm {
1970                         helper.request_token();
1971                     }
1972                     assert!(!codegen_aborted);
1973                     assert_eq!(main_thread_worker_state,
1974                                MainThreadWorkerState::Codegenning);
1975                     main_thread_worker_state = MainThreadWorkerState::Idle;
1976                 }
1977
1978                 Message::CodegenComplete => {
1979                     codegen_done = true;
1980                     assert!(!codegen_aborted);
1981                     assert_eq!(main_thread_worker_state,
1982                                MainThreadWorkerState::Codegenning);
1983                     main_thread_worker_state = MainThreadWorkerState::Idle;
1984                 }
1985
1986                 // If codegen is aborted that means translation was aborted due
1987                 // to some normal-ish compiler error. In this situation we want
1988                 // to exit as soon as possible, but we want to make sure all
1989                 // existing work has finished. Flag codegen as being done, and
1990                 // then conditions above will ensure no more work is spawned but
1991                 // we'll keep executing this loop until `running` hits 0.
1992                 Message::CodegenAborted => {
1993                     assert!(!codegen_aborted);
1994                     codegen_done = true;
1995                     codegen_aborted = true;
1996                     assert_eq!(main_thread_worker_state,
1997                                MainThreadWorkerState::Codegenning);
1998                 }
1999
2000                 // If a thread exits successfully then we drop a token associated
2001                 // with that worker and update our `running` count. We may later
2002                 // re-acquire a token to continue running more work. We may also not
2003                 // actually drop a token here if the worker was running with an
2004                 // "ephemeral token"
2005                 //
2006                 // Note that if the thread failed that means it panicked, so we
2007                 // abort immediately.
2008                 Message::Done { result: Ok(compiled_module), worker_id } => {
2009                     if main_thread_worker_state == MainThreadWorkerState::LLVMing {
2010                         main_thread_worker_state = MainThreadWorkerState::Idle;
2011                     } else {
2012                         running -= 1;
2013                     }
2014
2015                     free_worker_ids.push(worker_id);
2016
2017                     match compiled_module.kind {
2018                         ModuleKind::Regular => {
2019                             compiled_modules.push(compiled_module);
2020                         }
2021                         ModuleKind::Metadata => {
2022                             assert!(compiled_metadata_module.is_none());
2023                             compiled_metadata_module = Some(compiled_module);
2024                         }
2025                         ModuleKind::Allocator => {
2026                             assert!(compiled_allocator_module.is_none());
2027                             compiled_allocator_module = Some(compiled_module);
2028                         }
2029                     }
2030                 }
2031                 Message::NeedsLTO { result, worker_id } => {
2032                     assert!(!started_lto);
2033                     if main_thread_worker_state == MainThreadWorkerState::LLVMing {
2034                         main_thread_worker_state = MainThreadWorkerState::Idle;
2035                     } else {
2036                         running -= 1;
2037                     }
2038                     free_worker_ids.push(worker_id);
2039                     needs_lto.push(result);
2040                 }
2041                 Message::AddImportOnlyModule { module_data, work_product } => {
2042                     assert!(!started_lto);
2043                     assert!(!codegen_done);
2044                     assert_eq!(main_thread_worker_state,
2045                                MainThreadWorkerState::Codegenning);
2046                     lto_import_only_modules.push((module_data, work_product));
2047                     main_thread_worker_state = MainThreadWorkerState::Idle;
2048                 }
2049                 Message::Done { result: Err(()), worker_id: _ } => {
2050                     bug!("worker thread panicked");
2051                 }
2052                 Message::CodegenItem => {
2053                     bug!("the coordinator should not receive codegen requests")
2054                 }
2055             }
2056         }
2057
2058         if let Some(llvm_start_time) = llvm_start_time {
2059             let total_llvm_time = Instant::now().duration_since(llvm_start_time);
2060             // This is the top-level timing for all of LLVM, set the time-depth
2061             // to zero.
2062             set_time_depth(0);
2063             print_time_passes_entry(cgcx.time_passes,
2064                                     "LLVM passes",
2065                                     total_llvm_time);
2066         }
2067
2068         // Regardless of what order these modules completed in, report them to
2069         // the backend in the same order every time to ensure that we're handing
2070         // out deterministic results.
2071         compiled_modules.sort_by(|a, b| a.name.cmp(&b.name));
2072
2073         let compiled_metadata_module = compiled_metadata_module
2074             .expect("Metadata module not compiled?");
2075
2076         Ok(CompiledModules {
2077             modules: compiled_modules,
2078             metadata_module: compiled_metadata_module,
2079             allocator_module: compiled_allocator_module,
2080         })
2081     });
2082
2083     // A heuristic that determines if we have enough LLVM WorkItems in the
2084     // queue so that the main thread can do LLVM work instead of codegen
2085     fn queue_full_enough(items_in_queue: usize,
2086                          workers_running: usize,
2087                          max_workers: usize) -> bool {
2088         // Tune me, plz.
2089         items_in_queue > 0 &&
2090         items_in_queue >= max_workers.saturating_sub(workers_running / 2)
2091     }
2092
2093     fn maybe_start_llvm_timer(config: &ModuleConfig,
2094                               llvm_start_time: &mut Option<Instant>) {
2095         // We keep track of the -Ztime-passes output manually,
2096         // since the closure-based interface does not fit well here.
2097         if config.time_passes {
2098             if llvm_start_time.is_none() {
2099                 *llvm_start_time = Some(Instant::now());
2100             }
2101         }
2102     }
2103 }
2104
2105 pub const CODEGEN_WORKER_ID: usize = ::std::usize::MAX;
2106 pub const CODEGEN_WORKER_TIMELINE: time_graph::TimelineId =
2107     time_graph::TimelineId(CODEGEN_WORKER_ID);
2108 pub const CODEGEN_WORK_PACKAGE_KIND: time_graph::WorkPackageKind =
2109     time_graph::WorkPackageKind(&["#DE9597", "#FED1D3", "#FDC5C7", "#B46668", "#88494B"]);
2110 const LLVM_WORK_PACKAGE_KIND: time_graph::WorkPackageKind =
2111     time_graph::WorkPackageKind(&["#7DB67A", "#C6EEC4", "#ACDAAA", "#579354", "#3E6F3C"]);
2112
2113 fn spawn_work(cgcx: CodegenContext, work: WorkItem) {
2114     let depth = time_depth();
2115
2116     thread::spawn(move || {
2117         set_time_depth(depth);
2118
2119         // Set up a destructor which will fire off a message that we're done as
2120         // we exit.
2121         struct Bomb {
2122             coordinator_send: Sender<Box<dyn Any + Send>>,
2123             result: Option<WorkItemResult>,
2124             worker_id: usize,
2125         }
2126         impl Drop for Bomb {
2127             fn drop(&mut self) {
2128                 let worker_id = self.worker_id;
2129                 let msg = match self.result.take() {
2130                     Some(WorkItemResult::Compiled(m)) => {
2131                         Message::Done { result: Ok(m), worker_id }
2132                     }
2133                     Some(WorkItemResult::NeedsLTO(m)) => {
2134                         Message::NeedsLTO { result: m, worker_id }
2135                     }
2136                     None => Message::Done { result: Err(()), worker_id }
2137                 };
2138                 drop(self.coordinator_send.send(Box::new(msg)));
2139             }
2140         }
2141
2142         let mut bomb = Bomb {
2143             coordinator_send: cgcx.coordinator_send.clone(),
2144             result: None,
2145             worker_id: cgcx.worker,
2146         };
2147
2148         // Execute the work itself, and if it finishes successfully then flag
2149         // ourselves as a success as well.
2150         //
2151         // Note that we ignore any `FatalError` coming out of `execute_work_item`,
2152         // as a diagnostic was already sent off to the main thread - just
2153         // surface that there was an error in this worker.
2154         bomb.result = {
2155             let timeline = cgcx.time_graph.as_ref().map(|tg| {
2156                 tg.start(time_graph::TimelineId(cgcx.worker),
2157                          LLVM_WORK_PACKAGE_KIND,
2158                          &work.name())
2159             });
2160             let mut timeline = timeline.unwrap_or(Timeline::noop());
2161             execute_work_item(&cgcx, work, &mut timeline).ok()
2162         };
2163     });
2164 }
2165
2166 pub fn run_assembler(cgcx: &CodegenContext, handler: &Handler, assembly: &Path, object: &Path) {
2167     let assembler = cgcx.assembler_cmd
2168         .as_ref()
2169         .expect("cgcx.assembler_cmd is missing?");
2170
2171     let pname = &assembler.name;
2172     let mut cmd = assembler.cmd.clone();
2173     cmd.arg("-c").arg("-o").arg(object).arg(assembly);
2174     debug!("{:?}", cmd);
2175
2176     match cmd.output() {
2177         Ok(prog) => {
2178             if !prog.status.success() {
2179                 let mut note = prog.stderr.clone();
2180                 note.extend_from_slice(&prog.stdout);
2181
2182                 handler.struct_err(&format!("linking with `{}` failed: {}",
2183                                             pname.display(),
2184                                             prog.status))
2185                     .note(&format!("{:?}", &cmd))
2186                     .note(str::from_utf8(&note[..]).unwrap())
2187                     .emit();
2188                 handler.abort_if_errors();
2189             }
2190         },
2191         Err(e) => {
2192             handler.err(&format!("could not exec the linker `{}`: {}", pname.display(), e));
2193             handler.abort_if_errors();
2194         }
2195     }
2196 }
2197
2198 pub unsafe fn with_llvm_pmb(llmod: &llvm::Module,
2199                             config: &ModuleConfig,
2200                             opt_level: llvm::CodeGenOptLevel,
2201                             prepare_for_thin_lto: bool,
2202                             f: &mut dyn FnMut(&llvm::PassManagerBuilder)) {
2203     use std::ptr;
2204
2205     // Create the PassManagerBuilder for LLVM. We configure it with
2206     // reasonable defaults and prepare it to actually populate the pass
2207     // manager.
2208     let builder = llvm::LLVMPassManagerBuilderCreate();
2209     let opt_size = config.opt_size.unwrap_or(llvm::CodeGenOptSizeNone);
2210     let inline_threshold = config.inline_threshold;
2211
2212     let pgo_gen_path = config.pgo_gen.as_ref().map(|s| {
2213         let s = if s.is_empty() { "default_%m.profraw" } else { s };
2214         CString::new(s.as_bytes()).unwrap()
2215     });
2216
2217     let pgo_use_path = if config.pgo_use.is_empty() {
2218         None
2219     } else {
2220         Some(CString::new(config.pgo_use.as_bytes()).unwrap())
2221     };
2222
2223     llvm::LLVMRustConfigurePassManagerBuilder(
2224         builder,
2225         opt_level,
2226         config.merge_functions,
2227         config.vectorize_slp,
2228         config.vectorize_loop,
2229         prepare_for_thin_lto,
2230         pgo_gen_path.as_ref().map_or(ptr::null(), |s| s.as_ptr()),
2231         pgo_use_path.as_ref().map_or(ptr::null(), |s| s.as_ptr()),
2232     );
2233
2234     llvm::LLVMPassManagerBuilderSetSizeLevel(builder, opt_size as u32);
2235
2236     if opt_size != llvm::CodeGenOptSizeNone {
2237         llvm::LLVMPassManagerBuilderSetDisableUnrollLoops(builder, 1);
2238     }
2239
2240     llvm::LLVMRustAddBuilderLibraryInfo(builder, llmod, config.no_builtins);
2241
2242     // Here we match what clang does (kinda). For O0 we only inline
2243     // always-inline functions (but don't add lifetime intrinsics), at O1 we
2244     // inline with lifetime intrinsics, and O2+ we add an inliner with a
2245     // thresholds copied from clang.
2246     match (opt_level, opt_size, inline_threshold) {
2247         (.., Some(t)) => {
2248             llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, t as u32);
2249         }
2250         (llvm::CodeGenOptLevel::Aggressive, ..) => {
2251             llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 275);
2252         }
2253         (_, llvm::CodeGenOptSizeDefault, _) => {
2254             llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 75);
2255         }
2256         (_, llvm::CodeGenOptSizeAggressive, _) => {
2257             llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 25);
2258         }
2259         (llvm::CodeGenOptLevel::None, ..) => {
2260             llvm::LLVMRustAddAlwaysInlinePass(builder, false);
2261         }
2262         (llvm::CodeGenOptLevel::Less, ..) => {
2263             llvm::LLVMRustAddAlwaysInlinePass(builder, true);
2264         }
2265         (llvm::CodeGenOptLevel::Default, ..) => {
2266             llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 225);
2267         }
2268         (llvm::CodeGenOptLevel::Other, ..) => {
2269             bug!("CodeGenOptLevel::Other selected")
2270         }
2271     }
2272
2273     f(builder);
2274     llvm::LLVMPassManagerBuilderDispose(builder);
2275 }
2276
2277
2278 enum SharedEmitterMessage {
2279     Diagnostic(Diagnostic),
2280     InlineAsmError(u32, String),
2281     AbortIfErrors,
2282     Fatal(String),
2283 }
2284
2285 #[derive(Clone)]
2286 pub struct SharedEmitter {
2287     sender: Sender<SharedEmitterMessage>,
2288 }
2289
2290 pub struct SharedEmitterMain {
2291     receiver: Receiver<SharedEmitterMessage>,
2292 }
2293
2294 impl SharedEmitter {
2295     pub fn new() -> (SharedEmitter, SharedEmitterMain) {
2296         let (sender, receiver) = channel();
2297
2298         (SharedEmitter { sender }, SharedEmitterMain { receiver })
2299     }
2300
2301     fn inline_asm_error(&self, cookie: u32, msg: String) {
2302         drop(self.sender.send(SharedEmitterMessage::InlineAsmError(cookie, msg)));
2303     }
2304
2305     fn fatal(&self, msg: &str) {
2306         drop(self.sender.send(SharedEmitterMessage::Fatal(msg.to_string())));
2307     }
2308 }
2309
2310 impl Emitter for SharedEmitter {
2311     fn emit(&mut self, db: &DiagnosticBuilder) {
2312         drop(self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
2313             msg: db.message(),
2314             code: db.code.clone(),
2315             lvl: db.level,
2316         })));
2317         for child in &db.children {
2318             drop(self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
2319                 msg: child.message(),
2320                 code: None,
2321                 lvl: child.level,
2322             })));
2323         }
2324         drop(self.sender.send(SharedEmitterMessage::AbortIfErrors));
2325     }
2326 }
2327
2328 impl SharedEmitterMain {
2329     pub fn check(&self, sess: &Session, blocking: bool) {
2330         loop {
2331             let message = if blocking {
2332                 match self.receiver.recv() {
2333                     Ok(message) => Ok(message),
2334                     Err(_) => Err(()),
2335                 }
2336             } else {
2337                 match self.receiver.try_recv() {
2338                     Ok(message) => Ok(message),
2339                     Err(_) => Err(()),
2340                 }
2341             };
2342
2343             match message {
2344                 Ok(SharedEmitterMessage::Diagnostic(diag)) => {
2345                     let handler = sess.diagnostic();
2346                     match diag.code {
2347                         Some(ref code) => {
2348                             handler.emit_with_code(&MultiSpan::new(),
2349                                                    &diag.msg,
2350                                                    code.clone(),
2351                                                    diag.lvl);
2352                         }
2353                         None => {
2354                             handler.emit(&MultiSpan::new(),
2355                                          &diag.msg,
2356                                          diag.lvl);
2357                         }
2358                     }
2359                 }
2360                 Ok(SharedEmitterMessage::InlineAsmError(cookie, msg)) => {
2361                     match Mark::from_u32(cookie).expn_info() {
2362                         Some(ei) => sess.span_err(ei.call_site, &msg),
2363                         None     => sess.err(&msg),
2364                     }
2365                 }
2366                 Ok(SharedEmitterMessage::AbortIfErrors) => {
2367                     sess.abort_if_errors();
2368                 }
2369                 Ok(SharedEmitterMessage::Fatal(msg)) => {
2370                     sess.fatal(&msg);
2371                 }
2372                 Err(_) => {
2373                     break;
2374                 }
2375             }
2376
2377         }
2378     }
2379 }
2380
2381 pub struct OngoingCodegen {
2382     crate_name: Symbol,
2383     crate_hash: Svh,
2384     metadata: EncodedMetadata,
2385     windows_subsystem: Option<String>,
2386     linker_info: LinkerInfo,
2387     crate_info: CrateInfo,
2388     time_graph: Option<TimeGraph>,
2389     coordinator_send: Sender<Box<dyn Any + Send>>,
2390     codegen_worker_receive: Receiver<Message>,
2391     shared_emitter_main: SharedEmitterMain,
2392     future: thread::JoinHandle<Result<CompiledModules, ()>>,
2393     output_filenames: Arc<OutputFilenames>,
2394 }
2395
2396 impl OngoingCodegen {
2397     pub(crate) fn join(
2398         self,
2399         sess: &Session
2400     ) -> (CodegenResults, FxHashMap<WorkProductId, WorkProduct>) {
2401         self.shared_emitter_main.check(sess, true);
2402         let compiled_modules = match self.future.join() {
2403             Ok(Ok(compiled_modules)) => compiled_modules,
2404             Ok(Err(())) => {
2405                 sess.abort_if_errors();
2406                 panic!("expected abort due to worker thread errors")
2407             },
2408             Err(_) => {
2409                 bug!("panic during codegen/LLVM phase");
2410             }
2411         };
2412
2413         sess.cgu_reuse_tracker.check_expected_reuse(sess);
2414
2415         sess.abort_if_errors();
2416
2417         if let Some(time_graph) = self.time_graph {
2418             time_graph.dump(&format!("{}-timings", self.crate_name));
2419         }
2420
2421         let work_products =
2422             copy_all_cgu_workproducts_to_incr_comp_cache_dir(sess,
2423                                                              &compiled_modules);
2424         produce_final_output_artifacts(sess,
2425                                        &compiled_modules,
2426                                        &self.output_filenames);
2427
2428         // FIXME: time_llvm_passes support - does this use a global context or
2429         // something?
2430         if sess.codegen_units() == 1 && sess.time_llvm_passes() {
2431             unsafe { llvm::LLVMRustPrintPassTimings(); }
2432         }
2433
2434         (CodegenResults {
2435             crate_name: self.crate_name,
2436             crate_hash: self.crate_hash,
2437             metadata: self.metadata,
2438             windows_subsystem: self.windows_subsystem,
2439             linker_info: self.linker_info,
2440             crate_info: self.crate_info,
2441
2442             modules: compiled_modules.modules,
2443             allocator_module: compiled_modules.allocator_module,
2444             metadata_module: compiled_modules.metadata_module,
2445         }, work_products)
2446     }
2447
2448     pub(crate) fn submit_pre_codegened_module_to_llvm(&self,
2449                                                        tcx: TyCtxt,
2450                                                        module: ModuleCodegen) {
2451         self.wait_for_signal_to_codegen_item();
2452         self.check_for_errors(tcx.sess);
2453
2454         // These are generally cheap and won't through off scheduling.
2455         let cost = 0;
2456         submit_codegened_module_to_llvm(tcx, module, cost);
2457     }
2458
2459     pub fn codegen_finished(&self, tcx: TyCtxt) {
2460         self.wait_for_signal_to_codegen_item();
2461         self.check_for_errors(tcx.sess);
2462         drop(self.coordinator_send.send(Box::new(Message::CodegenComplete)));
2463     }
2464
2465     /// Consume this context indicating that codegen was entirely aborted, and
2466     /// we need to exit as quickly as possible.
2467     ///
2468     /// This method blocks the current thread until all worker threads have
2469     /// finished, and all worker threads should have exited or be real close to
2470     /// exiting at this point.
2471     pub fn codegen_aborted(self) {
2472         // Signal to the coordinator it should spawn no more work and start
2473         // shutdown.
2474         drop(self.coordinator_send.send(Box::new(Message::CodegenAborted)));
2475         drop(self.future.join());
2476     }
2477
2478     pub fn check_for_errors(&self, sess: &Session) {
2479         self.shared_emitter_main.check(sess, false);
2480     }
2481
2482     pub fn wait_for_signal_to_codegen_item(&self) {
2483         match self.codegen_worker_receive.recv() {
2484             Ok(Message::CodegenItem) => {
2485                 // Nothing to do
2486             }
2487             Ok(_) => panic!("unexpected message"),
2488             Err(_) => {
2489                 // One of the LLVM threads must have panicked, fall through so
2490                 // error handling can be reached.
2491             }
2492         }
2493     }
2494 }
2495
2496 // impl Drop for OngoingCodegen {
2497 //     fn drop(&mut self) {
2498 //     }
2499 // }
2500
2501 pub(crate) fn submit_codegened_module_to_llvm(tcx: TyCtxt,
2502                                               module: ModuleCodegen,
2503                                               cost: u64) {
2504     let llvm_work_item = WorkItem::Optimize(module);
2505     drop(tcx.tx_to_llvm_workers.lock().send(Box::new(Message::CodegenDone {
2506         llvm_work_item,
2507         cost,
2508     })));
2509 }
2510
2511 pub(crate) fn submit_post_lto_module_to_llvm(tcx: TyCtxt,
2512                                              module: CachedModuleCodegen) {
2513     let llvm_work_item = WorkItem::CopyPostLtoArtifacts(module);
2514     drop(tcx.tx_to_llvm_workers.lock().send(Box::new(Message::CodegenDone {
2515         llvm_work_item,
2516         cost: 0,
2517     })));
2518 }
2519
2520 pub(crate) fn submit_pre_lto_module_to_llvm(tcx: TyCtxt,
2521                                             module: CachedModuleCodegen) {
2522     let filename = pre_lto_bitcode_filename(&module.name);
2523     let bc_path = in_incr_comp_dir_sess(tcx.sess, &filename);
2524     let file = fs::File::open(&bc_path).unwrap_or_else(|e| {
2525         panic!("failed to open bitcode file `{}`: {}", bc_path.display(), e)
2526     });
2527
2528     let mmap = unsafe {
2529         memmap::Mmap::map(&file).unwrap_or_else(|e| {
2530             panic!("failed to mmap bitcode file `{}`: {}", bc_path.display(), e)
2531         })
2532     };
2533
2534     // Schedule the module to be loaded
2535     drop(tcx.tx_to_llvm_workers.lock().send(Box::new(Message::AddImportOnlyModule {
2536         module_data: SerializedModule::FromUncompressedFile(mmap),
2537         work_product: module.source,
2538     })));
2539 }
2540
2541 pub(super) fn pre_lto_bitcode_filename(module_name: &str) -> String {
2542     format!("{}.{}", module_name, PRE_THIN_LTO_BC_EXT)
2543 }
2544
2545 fn msvc_imps_needed(tcx: TyCtxt) -> bool {
2546     // This should never be true (because it's not supported). If it is true,
2547     // something is wrong with commandline arg validation.
2548     assert!(!(tcx.sess.opts.debugging_opts.cross_lang_lto.enabled() &&
2549               tcx.sess.target.target.options.is_like_msvc &&
2550               tcx.sess.opts.cg.prefer_dynamic));
2551
2552     tcx.sess.target.target.options.is_like_msvc &&
2553         tcx.sess.crate_types.borrow().iter().any(|ct| *ct == config::CrateType::Rlib) &&
2554     // ThinLTO can't handle this workaround in all cases, so we don't
2555     // emit the `__imp_` symbols. Instead we make them unnecessary by disallowing
2556     // dynamic linking when cross-language LTO is enabled.
2557     !tcx.sess.opts.debugging_opts.cross_lang_lto.enabled()
2558 }
2559
2560 // Create a `__imp_<symbol> = &symbol` global for every public static `symbol`.
2561 // This is required to satisfy `dllimport` references to static data in .rlibs
2562 // when using MSVC linker.  We do this only for data, as linker can fix up
2563 // code references on its own.
2564 // See #26591, #27438
2565 fn create_msvc_imps(cgcx: &CodegenContext, llcx: &llvm::Context, llmod: &llvm::Module) {
2566     if !cgcx.msvc_imps_needed {
2567         return
2568     }
2569     // The x86 ABI seems to require that leading underscores are added to symbol
2570     // names, so we need an extra underscore on 32-bit. There's also a leading
2571     // '\x01' here which disables LLVM's symbol mangling (e.g. no extra
2572     // underscores added in front).
2573     let prefix = if cgcx.target_pointer_width == "32" {
2574         "\x01__imp__"
2575     } else {
2576         "\x01__imp_"
2577     };
2578     unsafe {
2579         let i8p_ty = Type::i8p_llcx(llcx);
2580         let globals = base::iter_globals(llmod)
2581             .filter(|&val| {
2582                 llvm::LLVMRustGetLinkage(val) == llvm::Linkage::ExternalLinkage &&
2583                     llvm::LLVMIsDeclaration(val) == 0
2584             })
2585             .map(move |val| {
2586                 let name = CStr::from_ptr(llvm::LLVMGetValueName(val));
2587                 let mut imp_name = prefix.as_bytes().to_vec();
2588                 imp_name.extend(name.to_bytes());
2589                 let imp_name = CString::new(imp_name).unwrap();
2590                 (imp_name, val)
2591             })
2592             .collect::<Vec<_>>();
2593         for (imp_name, val) in globals {
2594             let imp = llvm::LLVMAddGlobal(llmod,
2595                                           i8p_ty,
2596                                           imp_name.as_ptr() as *const _);
2597             llvm::LLVMSetInitializer(imp, consts::ptrcast(val, i8p_ty));
2598             llvm::LLVMRustSetLinkage(imp, llvm::Linkage::ExternalLinkage);
2599         }
2600     }
2601 }