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