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