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