]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/back/write.rs
rustc: Implement the #[global_allocator] attribute
[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 back::lto;
12 use back::link::{self, get_linker, remove};
13 use back::symbol_export::ExportedSymbols;
14 use rustc_incremental::{save_trans_partition, in_incr_comp_dir};
15 use rustc::session::config::{self, OutputFilenames, OutputType, OutputTypes, Passes, SomePasses,
16                              AllPasses, Sanitizer};
17 use rustc::session::Session;
18 use llvm;
19 use llvm::{ModuleRef, TargetMachineRef, PassManagerRef, DiagnosticInfoRef, ContextRef};
20 use llvm::SMDiagnosticRef;
21 use {CrateTranslation, ModuleLlvm, ModuleSource, ModuleTranslation};
22 use rustc::hir::def_id::CrateNum;
23 use rustc::util::common::{time, time_depth, set_time_depth, path2cstr};
24 use rustc::util::fs::link_or_copy;
25 use errors::{self, Handler, Level, DiagnosticBuilder, FatalError};
26 use errors::emitter::Emitter;
27 use syntax::ext::hygiene::Mark;
28 use syntax_pos::MultiSpan;
29 use context::{is_pie_binary, get_reloc_model};
30 use jobserver::{Client, Acquired};
31 use crossbeam::{scope, Scope};
32 use rustc_demangle;
33
34 use std::cmp;
35 use std::ffi::CString;
36 use std::fs;
37 use std::io;
38 use std::io::Write;
39 use std::path::{Path, PathBuf};
40 use std::str;
41 use std::sync::mpsc::{channel, Sender};
42 use std::slice;
43 use libc::{c_uint, c_void, c_char, size_t};
44
45 pub const RELOC_MODEL_ARGS : [(&'static str, llvm::RelocMode); 7] = [
46     ("pic", llvm::RelocMode::PIC),
47     ("static", llvm::RelocMode::Static),
48     ("default", llvm::RelocMode::Default),
49     ("dynamic-no-pic", llvm::RelocMode::DynamicNoPic),
50     ("ropi", llvm::RelocMode::ROPI),
51     ("rwpi", llvm::RelocMode::RWPI),
52     ("ropi-rwpi", llvm::RelocMode::ROPI_RWPI),
53 ];
54
55 pub const CODE_GEN_MODEL_ARGS : [(&'static str, llvm::CodeModel); 5] = [
56     ("default", llvm::CodeModel::Default),
57     ("small", llvm::CodeModel::Small),
58     ("kernel", llvm::CodeModel::Kernel),
59     ("medium", llvm::CodeModel::Medium),
60     ("large", llvm::CodeModel::Large),
61 ];
62
63 pub fn llvm_err(handler: &errors::Handler, msg: String) -> FatalError {
64     match llvm::last_error() {
65         Some(err) => handler.fatal(&format!("{}: {}", msg, err)),
66         None => handler.fatal(&msg),
67     }
68 }
69
70 pub fn write_output_file(
71         handler: &errors::Handler,
72         target: llvm::TargetMachineRef,
73         pm: llvm::PassManagerRef,
74         m: ModuleRef,
75         output: &Path,
76         file_type: llvm::FileType) -> Result<(), FatalError> {
77     unsafe {
78         let output_c = path2cstr(output);
79         let result = llvm::LLVMRustWriteOutputFile(
80                 target, pm, m, output_c.as_ptr(), file_type);
81         if result.into_result().is_err() {
82             let msg = format!("could not write output to {}", output.display());
83             Err(llvm_err(handler, msg))
84         } else {
85             Ok(())
86         }
87     }
88 }
89
90 // On android, we by default compile for armv7 processors. This enables
91 // things like double word CAS instructions (rather than emulating them)
92 // which are *far* more efficient. This is obviously undesirable in some
93 // cases, so if any sort of target feature is specified we don't append v7
94 // to the feature list.
95 //
96 // On iOS only armv7 and newer are supported. So it is useful to
97 // get all hardware potential via VFP3 (hardware floating point)
98 // and NEON (SIMD) instructions supported by LLVM.
99 // Note that without those flags various linking errors might
100 // arise as some of intrinsics are converted into function calls
101 // and nobody provides implementations those functions
102 fn target_feature(sess: &Session) -> String {
103     let rustc_features = [
104         "crt-static",
105     ];
106     let requested_features = sess.opts.cg.target_feature.split(',');
107     let llvm_features = requested_features.filter(|f| {
108         !rustc_features.iter().any(|s| f.contains(s))
109     });
110     format!("{},{}",
111             sess.target.target.options.features,
112             llvm_features.collect::<Vec<_>>().join(","))
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) -> TargetMachineRef {
134     let reloc_model = get_reloc_model(sess);
135
136     let opt_level = get_llvm_opt_level(sess.opts.optimize);
137     let use_softfp = sess.opts.cg.soft_float;
138
139     let ffunction_sections = sess.target.target.options.function_sections;
140     let fdata_sections = ffunction_sections;
141
142     let code_model_arg = match sess.opts.cg.code_model {
143         Some(ref s) => &s,
144         None => &sess.target.target.options.code_model,
145     };
146
147     let code_model = match CODE_GEN_MODEL_ARGS.iter().find(
148         |&&arg| arg.0 == code_model_arg) {
149         Some(x) => x.1,
150         _ => {
151             sess.err(&format!("{:?} is not a valid code model",
152                              sess.opts
153                                  .cg
154                                  .code_model));
155             sess.abort_if_errors();
156             bug!();
157         }
158     };
159
160     let triple = &sess.target.target.llvm_target;
161
162     let tm = unsafe {
163         let triple = CString::new(triple.as_bytes()).unwrap();
164         let cpu = match sess.opts.cg.target_cpu {
165             Some(ref s) => &**s,
166             None => &*sess.target.target.options.cpu
167         };
168         let cpu = CString::new(cpu.as_bytes()).unwrap();
169         let features = CString::new(target_feature(sess).as_bytes()).unwrap();
170         llvm::LLVMRustCreateTargetMachine(
171             triple.as_ptr(), cpu.as_ptr(), features.as_ptr(),
172             code_model,
173             reloc_model,
174             opt_level,
175             use_softfp,
176             is_pie_binary(sess),
177             ffunction_sections,
178             fdata_sections,
179         )
180     };
181
182     if tm.is_null() {
183         let msg = format!("Could not create LLVM TargetMachine for triple: {}",
184                           triple);
185         panic!(llvm_err(sess.diagnostic(), msg));
186     } else {
187         return tm;
188     };
189 }
190
191
192 /// Module-specific configuration for `optimize_and_codegen`.
193 #[derive(Clone)]
194 pub struct ModuleConfig {
195     /// LLVM TargetMachine to use for codegen.
196     tm: TargetMachineRef,
197     /// Names of additional optimization passes to run.
198     passes: Vec<String>,
199     /// Some(level) to optimize at a certain level, or None to run
200     /// absolutely no optimizations (used for the metadata module).
201     opt_level: Option<llvm::CodeGenOptLevel>,
202
203     /// Some(level) to optimize binary size, or None to not affect program size.
204     opt_size: Option<llvm::CodeGenOptSize>,
205
206     // Flags indicating which outputs to produce.
207     emit_no_opt_bc: bool,
208     emit_bc: bool,
209     emit_lto_bc: bool,
210     emit_ir: bool,
211     emit_asm: bool,
212     emit_obj: bool,
213     // Miscellaneous flags.  These are mostly copied from command-line
214     // options.
215     no_verify: bool,
216     no_prepopulate_passes: bool,
217     no_builtins: bool,
218     time_passes: bool,
219     vectorize_loop: bool,
220     vectorize_slp: bool,
221     merge_functions: bool,
222     inline_threshold: Option<usize>,
223     // Instead of creating an object file by doing LLVM codegen, just
224     // make the object file bitcode. Provides easy compatibility with
225     // emscripten's ecc compiler, when used as the linker.
226     obj_is_bitcode: bool,
227 }
228
229 unsafe impl Send for ModuleConfig { }
230
231 impl ModuleConfig {
232     fn new(tm: TargetMachineRef, passes: Vec<String>) -> ModuleConfig {
233         ModuleConfig {
234             tm: tm,
235             passes: passes,
236             opt_level: None,
237             opt_size: None,
238
239             emit_no_opt_bc: false,
240             emit_bc: false,
241             emit_lto_bc: false,
242             emit_ir: false,
243             emit_asm: false,
244             emit_obj: false,
245             obj_is_bitcode: false,
246
247             no_verify: false,
248             no_prepopulate_passes: false,
249             no_builtins: false,
250             time_passes: false,
251             vectorize_loop: false,
252             vectorize_slp: false,
253             merge_functions: false,
254             inline_threshold: None
255         }
256     }
257
258     fn set_flags(&mut self, sess: &Session, trans: &CrateTranslation) {
259         self.no_verify = sess.no_verify();
260         self.no_prepopulate_passes = sess.opts.cg.no_prepopulate_passes;
261         self.no_builtins = trans.no_builtins;
262         self.time_passes = sess.time_passes();
263         self.inline_threshold = sess.opts.cg.inline_threshold;
264         self.obj_is_bitcode = sess.target.target.options.obj_is_bitcode;
265
266         // Copy what clang does by turning on loop vectorization at O2 and
267         // slp vectorization at O3. Otherwise configure other optimization aspects
268         // of this pass manager builder.
269         // Turn off vectorization for emscripten, as it's not very well supported.
270         self.vectorize_loop = !sess.opts.cg.no_vectorize_loops &&
271                              (sess.opts.optimize == config::OptLevel::Default ||
272                               sess.opts.optimize == config::OptLevel::Aggressive) &&
273                              !sess.target.target.options.is_like_emscripten;
274
275         self.vectorize_slp = !sess.opts.cg.no_vectorize_slp &&
276                             sess.opts.optimize == config::OptLevel::Aggressive &&
277                             !sess.target.target.options.is_like_emscripten;
278
279         self.merge_functions = sess.opts.optimize == config::OptLevel::Default ||
280                                sess.opts.optimize == config::OptLevel::Aggressive;
281     }
282 }
283
284 /// Additional resources used by optimize_and_codegen (not module specific)
285 pub struct CodegenContext<'a> {
286     // Resouces needed when running LTO
287     pub time_passes: bool,
288     pub lto: bool,
289     pub no_landing_pads: bool,
290     pub exported_symbols: &'a ExportedSymbols,
291     pub opts: &'a config::Options,
292     pub crate_types: Vec<config::CrateType>,
293     pub each_linked_rlib_for_lto: Vec<(CrateNum, PathBuf)>,
294     // Handler to use for diagnostics produced during codegen.
295     pub handler: &'a Handler,
296     // LLVM passes added by plugins.
297     pub plugin_passes: Vec<String>,
298     // LLVM optimizations for which we want to print remarks.
299     pub remark: Passes,
300     // Worker thread number
301     pub worker: usize,
302     // The incremental compilation session directory, or None if we are not
303     // compiling incrementally
304     pub incr_comp_session_dir: Option<PathBuf>,
305     // Channel back to the main control thread to send messages to
306     pub tx: Sender<Message>,
307 }
308
309 struct HandlerFreeVars<'a> {
310     llcx: ContextRef,
311     cgcx: &'a CodegenContext<'a>,
312 }
313
314 unsafe extern "C" fn report_inline_asm<'a, 'b>(cgcx: &'a CodegenContext<'a>,
315                                                msg: &'b str,
316                                                cookie: c_uint) {
317     drop(cgcx.tx.send(Message::InlineAsmError(cookie as u32, msg.to_string())));
318 }
319
320 unsafe extern "C" fn inline_asm_handler(diag: SMDiagnosticRef,
321                                         user: *const c_void,
322                                         cookie: c_uint) {
323     let HandlerFreeVars { cgcx, .. } = *(user as *const HandlerFreeVars);
324
325     let msg = llvm::build_string(|s| llvm::LLVMRustWriteSMDiagnosticToString(diag, s))
326         .expect("non-UTF8 SMDiagnostic");
327
328     report_inline_asm(cgcx, &msg, cookie);
329 }
330
331 unsafe extern "C" fn diagnostic_handler(info: DiagnosticInfoRef, user: *mut c_void) {
332     let HandlerFreeVars { llcx, cgcx } = *(user as *const HandlerFreeVars);
333
334     match llvm::diagnostic::Diagnostic::unpack(info) {
335         llvm::diagnostic::InlineAsm(inline) => {
336             report_inline_asm(cgcx,
337                               &llvm::twine_to_string(inline.message),
338                               inline.cookie);
339         }
340
341         llvm::diagnostic::Optimization(opt) => {
342             let enabled = match cgcx.remark {
343                 AllPasses => true,
344                 SomePasses(ref v) => v.iter().any(|s| *s == opt.pass_name),
345             };
346
347             if enabled {
348                 let loc = llvm::debug_loc_to_string(llcx, opt.debug_loc);
349                 cgcx.handler.note_without_error(&format!("optimization {} for {} at {}: {}",
350                                                 opt.kind.describe(),
351                                                 opt.pass_name,
352                                                 if loc.is_empty() { "[unknown]" } else { &*loc },
353                                                 opt.message));
354             }
355         }
356
357         _ => (),
358     }
359 }
360
361 // Unsafe due to LLVM calls.
362 unsafe fn optimize_and_codegen(cgcx: &CodegenContext,
363                                mtrans: ModuleTranslation,
364                                mllvm: ModuleLlvm,
365                                config: ModuleConfig,
366                                output_names: OutputFilenames)
367     -> Result<(), FatalError>
368 {
369     let llmod = mllvm.llmod;
370     let llcx = mllvm.llcx;
371     let tm = config.tm;
372
373     // llcx doesn't outlive this function, so we can put this on the stack.
374     let fv = HandlerFreeVars {
375         llcx: llcx,
376         cgcx: cgcx,
377     };
378     let fv = &fv as *const HandlerFreeVars as *mut c_void;
379
380     llvm::LLVMRustSetInlineAsmDiagnosticHandler(llcx, inline_asm_handler, fv);
381     llvm::LLVMContextSetDiagnosticHandler(llcx, diagnostic_handler, fv);
382
383     let module_name = Some(&mtrans.name[..]);
384
385     if config.emit_no_opt_bc {
386         let out = output_names.temp_path_ext("no-opt.bc", module_name);
387         let out = path2cstr(&out);
388         llvm::LLVMWriteBitcodeToFile(llmod, out.as_ptr());
389     }
390
391     if config.opt_level.is_some() {
392         // Create the two optimizing pass managers. These mirror what clang
393         // does, and are by populated by LLVM's default PassManagerBuilder.
394         // Each manager has a different set of passes, but they also share
395         // some common passes.
396         let fpm = llvm::LLVMCreateFunctionPassManagerForModule(llmod);
397         let mpm = llvm::LLVMCreatePassManager();
398
399         // If we're verifying or linting, add them to the function pass
400         // manager.
401         let addpass = |pass_name: &str| {
402             let pass_name = CString::new(pass_name).unwrap();
403             let pass = llvm::LLVMRustFindAndCreatePass(pass_name.as_ptr());
404             if pass.is_null() {
405                 return false;
406             }
407             let pass_manager = match llvm::LLVMRustPassKind(pass) {
408                 llvm::PassKind::Function => fpm,
409                 llvm::PassKind::Module => mpm,
410                 llvm::PassKind::Other => {
411                     cgcx.handler.err("Encountered LLVM pass kind we can't handle");
412                     return true
413                 },
414             };
415             llvm::LLVMRustAddPass(pass_manager, pass);
416             true
417         };
418
419         if !config.no_verify { assert!(addpass("verify")); }
420         if !config.no_prepopulate_passes {
421             llvm::LLVMRustAddAnalysisPasses(tm, fpm, llmod);
422             llvm::LLVMRustAddAnalysisPasses(tm, mpm, llmod);
423             with_llvm_pmb(llmod, &config, &mut |b| {
424                 llvm::LLVMPassManagerBuilderPopulateFunctionPassManager(b, fpm);
425                 llvm::LLVMPassManagerBuilderPopulateModulePassManager(b, mpm);
426             })
427         }
428
429         for pass in &config.passes {
430             if !addpass(pass) {
431                 cgcx.handler.warn(&format!("unknown pass `{}`, ignoring",
432                                            pass));
433             }
434         }
435
436         for pass in &cgcx.plugin_passes {
437             if !addpass(pass) {
438                 cgcx.handler.err(&format!("a plugin asked for LLVM pass \
439                                            `{}` but LLVM does not \
440                                            recognize it", pass));
441             }
442         }
443
444         cgcx.handler.abort_if_errors();
445
446         // Finally, run the actual optimization passes
447         time(config.time_passes, &format!("llvm function passes [{}]", cgcx.worker), ||
448              llvm::LLVMRustRunFunctionPassManager(fpm, llmod));
449         time(config.time_passes, &format!("llvm module passes [{}]", cgcx.worker), ||
450              llvm::LLVMRunPassManager(mpm, llmod));
451
452         // Deallocate managers that we're now done with
453         llvm::LLVMDisposePassManager(fpm);
454         llvm::LLVMDisposePassManager(mpm);
455
456         if cgcx.lto {
457             time(cgcx.time_passes, "all lto passes", || {
458                 let temp_no_opt_bc_filename =
459                     output_names.temp_path_ext("no-opt.lto.bc", module_name);
460                 lto::run(cgcx,
461                          llmod,
462                          tm,
463                          &config,
464                          &temp_no_opt_bc_filename)
465             })?;
466             if config.emit_lto_bc {
467                 let out = output_names.temp_path_ext("lto.bc", module_name);
468                 let out = path2cstr(&out);
469                 llvm::LLVMWriteBitcodeToFile(llmod, out.as_ptr());
470             }
471         }
472     }
473
474     // A codegen-specific pass manager is used to generate object
475     // files for an LLVM module.
476     //
477     // Apparently each of these pass managers is a one-shot kind of
478     // thing, so we create a new one for each type of output. The
479     // pass manager passed to the closure should be ensured to not
480     // escape the closure itself, and the manager should only be
481     // used once.
482     unsafe fn with_codegen<F, R>(tm: TargetMachineRef,
483                                  llmod: ModuleRef,
484                                  no_builtins: bool,
485                                  f: F) -> R
486         where F: FnOnce(PassManagerRef) -> R,
487     {
488         let cpm = llvm::LLVMCreatePassManager();
489         llvm::LLVMRustAddAnalysisPasses(tm, cpm, llmod);
490         llvm::LLVMRustAddLibraryInfo(cpm, llmod, no_builtins);
491         f(cpm)
492     }
493
494     // Change what we write and cleanup based on whether obj files are
495     // just llvm bitcode. In that case write bitcode, and possibly
496     // delete the bitcode if it wasn't requested. Don't generate the
497     // machine code, instead copy the .o file from the .bc
498     let write_bc = config.emit_bc || config.obj_is_bitcode;
499     let rm_bc = !config.emit_bc && config.obj_is_bitcode;
500     let write_obj = config.emit_obj && !config.obj_is_bitcode;
501     let copy_bc_to_obj = config.emit_obj && config.obj_is_bitcode;
502
503     let bc_out = output_names.temp_path(OutputType::Bitcode, module_name);
504     let obj_out = output_names.temp_path(OutputType::Object, module_name);
505
506     if write_bc {
507         let bc_out_c = path2cstr(&bc_out);
508         llvm::LLVMWriteBitcodeToFile(llmod, bc_out_c.as_ptr());
509     }
510
511     time(config.time_passes, &format!("codegen passes [{}]", cgcx.worker),
512          || -> Result<(), FatalError> {
513         if config.emit_ir {
514             let out = output_names.temp_path(OutputType::LlvmAssembly, module_name);
515             let out = path2cstr(&out);
516
517             extern "C" fn demangle_callback(input_ptr: *const c_char,
518                                             input_len: size_t,
519                                             output_ptr: *mut c_char,
520                                             output_len: size_t) -> size_t {
521                 let input = unsafe {
522                     slice::from_raw_parts(input_ptr as *const u8, input_len as usize)
523                 };
524
525                 let input = match str::from_utf8(input) {
526                     Ok(s) => s,
527                     Err(_) => return 0,
528                 };
529
530                 let output = unsafe {
531                     slice::from_raw_parts_mut(output_ptr as *mut u8, output_len as usize)
532                 };
533                 let mut cursor = io::Cursor::new(output);
534
535                 let demangled = match rustc_demangle::try_demangle(input) {
536                     Ok(d) => d,
537                     Err(_) => return 0,
538                 };
539
540                 if let Err(_) = write!(cursor, "{:#}", demangled) {
541                     // Possible only if provided buffer is not big enough
542                     return 0;
543                 }
544
545                 cursor.position() as size_t
546             }
547
548             with_codegen(tm, llmod, config.no_builtins, |cpm| {
549                 llvm::LLVMRustPrintModule(cpm, llmod, out.as_ptr(), demangle_callback);
550                 llvm::LLVMDisposePassManager(cpm);
551             })
552         }
553
554         if config.emit_asm {
555             let path = output_names.temp_path(OutputType::Assembly, module_name);
556
557             // We can't use the same module for asm and binary output, because that triggers
558             // various errors like invalid IR or broken binaries, so we might have to clone the
559             // module to produce the asm output
560             let llmod = if config.emit_obj {
561                 llvm::LLVMCloneModule(llmod)
562             } else {
563                 llmod
564             };
565             with_codegen(tm, llmod, config.no_builtins, |cpm| {
566                 write_output_file(cgcx.handler, tm, cpm, llmod, &path,
567                                   llvm::FileType::AssemblyFile)
568             })?;
569             if config.emit_obj {
570                 llvm::LLVMDisposeModule(llmod);
571             }
572         }
573
574         if write_obj {
575             with_codegen(tm, llmod, config.no_builtins, |cpm| {
576                 write_output_file(cgcx.handler, tm, cpm, llmod, &obj_out,
577                                   llvm::FileType::ObjectFile)
578             })?;
579         }
580
581         Ok(())
582     })?;
583
584     if copy_bc_to_obj {
585         debug!("copying bitcode {:?} to obj {:?}", bc_out, obj_out);
586         if let Err(e) = link_or_copy(&bc_out, &obj_out) {
587             cgcx.handler.err(&format!("failed to copy bitcode to object file: {}", e));
588         }
589     }
590
591     if rm_bc {
592         debug!("removing_bitcode {:?}", bc_out);
593         if let Err(e) = fs::remove_file(&bc_out) {
594             cgcx.handler.err(&format!("failed to remove bitcode: {}", e));
595         }
596     }
597
598     llvm::LLVMRustDisposeTargetMachine(tm);
599     Ok(())
600 }
601
602
603 pub fn cleanup_llvm(trans: &CrateTranslation) {
604     for module in trans.modules.iter() {
605         unsafe {
606             match module.source {
607                 ModuleSource::Translated(llvm) => {
608                     llvm::LLVMDisposeModule(llvm.llmod);
609                     llvm::LLVMContextDispose(llvm.llcx);
610                 }
611                 ModuleSource::Preexisting(_) => {
612                 }
613             }
614         }
615     }
616 }
617
618 pub fn run_passes(sess: &Session,
619                   trans: &CrateTranslation,
620                   output_types: &OutputTypes,
621                   crate_output: &OutputFilenames) {
622     // It's possible that we have `codegen_units > 1` but only one item in
623     // `trans.modules`.  We could theoretically proceed and do LTO in that
624     // case, but it would be confusing to have the validity of
625     // `-Z lto -C codegen-units=2` depend on details of the crate being
626     // compiled, so we complain regardless.
627     if sess.lto() && sess.opts.cg.codegen_units > 1 {
628         // This case is impossible to handle because LTO expects to be able
629         // to combine the entire crate and all its dependencies into a
630         // single compilation unit, but each codegen unit is in a separate
631         // LLVM context, so they can't easily be combined.
632         sess.fatal("can't perform LTO when using multiple codegen units");
633     }
634
635     // Sanity check
636     assert!(trans.modules.len() == sess.opts.cg.codegen_units ||
637             sess.opts.debugging_opts.incremental.is_some() ||
638             !sess.opts.output_types.should_trans() ||
639             sess.opts.debugging_opts.no_trans);
640
641     let tm = create_target_machine(sess);
642
643     // Figure out what we actually need to build.
644
645     let mut modules_config = ModuleConfig::new(tm, sess.opts.cg.passes.clone());
646     let mut metadata_config = ModuleConfig::new(tm, vec![]);
647     let mut allocator_config = ModuleConfig::new(tm, vec![]);
648
649     if let Some(ref sanitizer) = sess.opts.debugging_opts.sanitizer {
650         match *sanitizer {
651             Sanitizer::Address => {
652                 modules_config.passes.push("asan".to_owned());
653                 modules_config.passes.push("asan-module".to_owned());
654             }
655             Sanitizer::Memory => {
656                 modules_config.passes.push("msan".to_owned())
657             }
658             Sanitizer::Thread => {
659                 modules_config.passes.push("tsan".to_owned())
660             }
661             _ => {}
662         }
663     }
664
665     if sess.opts.debugging_opts.profile {
666         modules_config.passes.push("insert-gcov-profiling".to_owned())
667     }
668
669     modules_config.opt_level = Some(get_llvm_opt_level(sess.opts.optimize));
670     modules_config.opt_size = Some(get_llvm_opt_size(sess.opts.optimize));
671
672     // Save all versions of the bytecode if we're saving our temporaries.
673     if sess.opts.cg.save_temps {
674         modules_config.emit_no_opt_bc = true;
675         modules_config.emit_bc = true;
676         modules_config.emit_lto_bc = true;
677         metadata_config.emit_bc = true;
678         allocator_config.emit_bc = true;
679     }
680
681     // Emit bitcode files for the crate if we're emitting an rlib.
682     // Whenever an rlib is created, the bitcode is inserted into the
683     // archive in order to allow LTO against it.
684     let needs_crate_bitcode =
685             sess.crate_types.borrow().contains(&config::CrateTypeRlib) &&
686             sess.opts.output_types.contains_key(&OutputType::Exe);
687     let needs_crate_object =
688             sess.opts.output_types.contains_key(&OutputType::Exe);
689     if needs_crate_bitcode {
690         modules_config.emit_bc = true;
691     }
692
693     for output_type in output_types.keys() {
694         match *output_type {
695             OutputType::Bitcode => { modules_config.emit_bc = true; }
696             OutputType::LlvmAssembly => { modules_config.emit_ir = true; }
697             OutputType::Assembly => {
698                 modules_config.emit_asm = true;
699                 // If we're not using the LLVM assembler, this function
700                 // could be invoked specially with output_type_assembly, so
701                 // in this case we still want the metadata object file.
702                 if !sess.opts.output_types.contains_key(&OutputType::Assembly) {
703                     metadata_config.emit_obj = true;
704                     allocator_config.emit_obj = true;
705                 }
706             }
707             OutputType::Object => { modules_config.emit_obj = true; }
708             OutputType::Metadata => { metadata_config.emit_obj = true; }
709             OutputType::Exe => {
710                 modules_config.emit_obj = true;
711                 metadata_config.emit_obj = true;
712                 allocator_config.emit_obj = true;
713             },
714             OutputType::Mir => {}
715             OutputType::DepInfo => {}
716         }
717     }
718
719     modules_config.set_flags(sess, trans);
720     metadata_config.set_flags(sess, trans);
721     allocator_config.set_flags(sess, trans);
722
723
724     // Populate a buffer with a list of codegen threads.  Items are processed in
725     // LIFO order, just because it's a tiny bit simpler that way.  (The order
726     // doesn't actually matter.)
727     let mut work_items = Vec::with_capacity(1 + trans.modules.len());
728
729     {
730         let work = build_work_item(sess,
731                                    trans.metadata_module.clone(),
732                                    metadata_config.clone(),
733                                    crate_output.clone());
734         work_items.push(work);
735     }
736
737     if let Some(allocator) = trans.allocator_module.clone() {
738         let work = build_work_item(sess,
739                                    allocator,
740                                    allocator_config.clone(),
741                                    crate_output.clone());
742         work_items.push(work);
743     }
744
745     for mtrans in trans.modules.iter() {
746         let work = build_work_item(sess,
747                                    mtrans.clone(),
748                                    modules_config.clone(),
749                                    crate_output.clone());
750         work_items.push(work);
751     }
752
753     if sess.opts.debugging_opts.incremental_info {
754         dump_incremental_data(&trans);
755     }
756
757     let client = sess.jobserver_from_env.clone().unwrap_or_else(|| {
758         // Pick a "reasonable maximum" if we don't otherwise have a jobserver in
759         // our environment, capping out at 32 so we don't take everything down
760         // by hogging the process run queue.
761         let num_workers = cmp::min(work_items.len() - 1, 32);
762         Client::new(num_workers).expect("failed to create jobserver")
763     });
764     scope(|scope| {
765         execute_work(sess, work_items, client, &trans.exported_symbols, scope);
766     });
767
768     // If in incr. comp. mode, preserve the `.o` files for potential re-use
769     for mtrans in trans.modules.iter() {
770         let mut files = vec![];
771
772         if modules_config.emit_obj {
773             let path = crate_output.temp_path(OutputType::Object, Some(&mtrans.name));
774             files.push((OutputType::Object, path));
775         }
776
777         if modules_config.emit_bc {
778             let path = crate_output.temp_path(OutputType::Bitcode, Some(&mtrans.name));
779             files.push((OutputType::Bitcode, path));
780         }
781
782         save_trans_partition(sess, &mtrans.name, mtrans.symbol_name_hash, &files);
783     }
784
785     // All codegen is finished.
786     unsafe {
787         llvm::LLVMRustDisposeTargetMachine(tm);
788     }
789
790     // Produce final compile outputs.
791     let copy_gracefully = |from: &Path, to: &Path| {
792         if let Err(e) = fs::copy(from, to) {
793             sess.err(&format!("could not copy {:?} to {:?}: {}", from, to, e));
794         }
795     };
796
797     let copy_if_one_unit = |output_type: OutputType,
798                             keep_numbered: bool| {
799         if trans.modules.len() == 1 {
800             // 1) Only one codegen unit.  In this case it's no difficulty
801             //    to copy `foo.0.x` to `foo.x`.
802             let module_name = Some(&trans.modules[0].name[..]);
803             let path = crate_output.temp_path(output_type, module_name);
804             copy_gracefully(&path,
805                             &crate_output.path(output_type));
806             if !sess.opts.cg.save_temps && !keep_numbered {
807                 // The user just wants `foo.x`, not `foo.#module-name#.x`.
808                 remove(sess, &path);
809             }
810         } else {
811             let ext = crate_output.temp_path(output_type, None)
812                                   .extension()
813                                   .unwrap()
814                                   .to_str()
815                                   .unwrap()
816                                   .to_owned();
817
818             if crate_output.outputs.contains_key(&output_type) {
819                 // 2) Multiple codegen units, with `--emit foo=some_name`.  We have
820                 //    no good solution for this case, so warn the user.
821                 sess.warn(&format!("ignoring emit path because multiple .{} files \
822                                     were produced", ext));
823             } else if crate_output.single_output_file.is_some() {
824                 // 3) Multiple codegen units, with `-o some_name`.  We have
825                 //    no good solution for this case, so warn the user.
826                 sess.warn(&format!("ignoring -o because multiple .{} files \
827                                     were produced", ext));
828             } else {
829                 // 4) Multiple codegen units, but no explicit name.  We
830                 //    just leave the `foo.0.x` files in place.
831                 // (We don't have to do any work in this case.)
832             }
833         }
834     };
835
836     // Flag to indicate whether the user explicitly requested bitcode.
837     // Otherwise, we produced it only as a temporary output, and will need
838     // to get rid of it.
839     let mut user_wants_bitcode = false;
840     let mut user_wants_objects = false;
841     for output_type in output_types.keys() {
842         match *output_type {
843             OutputType::Bitcode => {
844                 user_wants_bitcode = true;
845                 // Copy to .bc, but always keep the .0.bc.  There is a later
846                 // check to figure out if we should delete .0.bc files, or keep
847                 // them for making an rlib.
848                 copy_if_one_unit(OutputType::Bitcode, true);
849             }
850             OutputType::LlvmAssembly => {
851                 copy_if_one_unit(OutputType::LlvmAssembly, false);
852             }
853             OutputType::Assembly => {
854                 copy_if_one_unit(OutputType::Assembly, false);
855             }
856             OutputType::Object => {
857                 user_wants_objects = true;
858                 copy_if_one_unit(OutputType::Object, true);
859             }
860             OutputType::Mir |
861             OutputType::Metadata |
862             OutputType::Exe |
863             OutputType::DepInfo => {}
864         }
865     }
866     let user_wants_bitcode = user_wants_bitcode;
867
868     // Clean up unwanted temporary files.
869
870     // We create the following files by default:
871     //  - #crate#.#module-name#.bc
872     //  - #crate#.#module-name#.o
873     //  - #crate#.crate.metadata.bc
874     //  - #crate#.crate.metadata.o
875     //  - #crate#.o (linked from crate.##.o)
876     //  - #crate#.bc (copied from crate.##.bc)
877     // We may create additional files if requested by the user (through
878     // `-C save-temps` or `--emit=` flags).
879
880     if !sess.opts.cg.save_temps {
881         // Remove the temporary .#module-name#.o objects.  If the user didn't
882         // explicitly request bitcode (with --emit=bc), and the bitcode is not
883         // needed for building an rlib, then we must remove .#module-name#.bc as
884         // well.
885
886         // Specific rules for keeping .#module-name#.bc:
887         //  - If we're building an rlib (`needs_crate_bitcode`), then keep
888         //    it.
889         //  - If the user requested bitcode (`user_wants_bitcode`), and
890         //    codegen_units > 1, then keep it.
891         //  - If the user requested bitcode but codegen_units == 1, then we
892         //    can toss .#module-name#.bc because we copied it to .bc earlier.
893         //  - If we're not building an rlib and the user didn't request
894         //    bitcode, then delete .#module-name#.bc.
895         // If you change how this works, also update back::link::link_rlib,
896         // where .#module-name#.bc files are (maybe) deleted after making an
897         // rlib.
898         let keep_numbered_bitcode = needs_crate_bitcode ||
899                 (user_wants_bitcode && sess.opts.cg.codegen_units > 1);
900
901         let keep_numbered_objects = needs_crate_object ||
902                 (user_wants_objects && sess.opts.cg.codegen_units > 1);
903
904         for module_name in trans.modules.iter().map(|m| Some(&m.name[..])) {
905             if modules_config.emit_obj && !keep_numbered_objects {
906                 let path = crate_output.temp_path(OutputType::Object, module_name);
907                 remove(sess, &path);
908             }
909
910             if modules_config.emit_bc && !keep_numbered_bitcode {
911                 let path = crate_output.temp_path(OutputType::Bitcode, module_name);
912                 remove(sess, &path);
913             }
914         }
915
916         if metadata_config.emit_bc && !user_wants_bitcode {
917             let path = crate_output.temp_path(OutputType::Bitcode,
918                                               Some(&trans.metadata_module.name));
919             remove(sess, &path);
920         }
921         if allocator_config.emit_bc && !user_wants_bitcode {
922             if let Some(ref module) = trans.allocator_module {
923                 let path = crate_output.temp_path(OutputType::Bitcode,
924                                                   Some(&module.name));
925                 remove(sess, &path);
926             }
927         }
928     }
929
930     // We leave the following files around by default:
931     //  - #crate#.o
932     //  - #crate#.crate.metadata.o
933     //  - #crate#.bc
934     // These are used in linking steps and will be cleaned up afterward.
935
936     // FIXME: time_llvm_passes support - does this use a global context or
937     // something?
938     if sess.opts.cg.codegen_units == 1 && sess.time_llvm_passes() {
939         unsafe { llvm::LLVMRustPrintPassTimings(); }
940     }
941 }
942
943 fn dump_incremental_data(trans: &CrateTranslation) {
944     let mut reuse = 0;
945     for mtrans in trans.modules.iter() {
946         match mtrans.source {
947             ModuleSource::Preexisting(..) => reuse += 1,
948             ModuleSource::Translated(..) => (),
949         }
950     }
951     eprintln!("incremental: re-using {} out of {} modules", reuse, trans.modules.len());
952 }
953
954 struct WorkItem {
955     mtrans: ModuleTranslation,
956     config: ModuleConfig,
957     output_names: OutputFilenames
958 }
959
960 fn build_work_item(sess: &Session,
961                    mtrans: ModuleTranslation,
962                    config: ModuleConfig,
963                    output_names: OutputFilenames)
964                    -> WorkItem
965 {
966     let mut config = config;
967     config.tm = create_target_machine(sess);
968     WorkItem {
969         mtrans: mtrans,
970         config: config,
971         output_names: output_names
972     }
973 }
974
975 fn execute_work_item(cgcx: &CodegenContext, work_item: WorkItem)
976     -> Result<(), FatalError>
977 {
978     unsafe {
979         match work_item.mtrans.source {
980             ModuleSource::Translated(mllvm) => {
981                 debug!("llvm-optimizing {:?}", work_item.mtrans.name);
982                 optimize_and_codegen(cgcx,
983                                      work_item.mtrans,
984                                      mllvm,
985                                      work_item.config,
986                                      work_item.output_names)?;
987             }
988             ModuleSource::Preexisting(wp) => {
989                 let incr_comp_session_dir = cgcx.incr_comp_session_dir
990                                                 .as_ref()
991                                                 .unwrap();
992                 let name = &work_item.mtrans.name;
993                 for (kind, saved_file) in wp.saved_files {
994                     let obj_out = work_item.output_names.temp_path(kind, Some(name));
995                     let source_file = in_incr_comp_dir(&incr_comp_session_dir,
996                                                        &saved_file);
997                     debug!("copying pre-existing module `{}` from {:?} to {}",
998                            work_item.mtrans.name,
999                            source_file,
1000                            obj_out.display());
1001                     match link_or_copy(&source_file, &obj_out) {
1002                         Ok(_) => { }
1003                         Err(err) => {
1004                             cgcx.handler.err(&format!("unable to copy {} to {}: {}",
1005                                                       source_file.display(),
1006                                                       obj_out.display(),
1007                                                       err));
1008                         }
1009                     }
1010                 }
1011             }
1012         }
1013     }
1014
1015     Ok(())
1016 }
1017
1018 pub enum Message {
1019     Token(io::Result<Acquired>),
1020     Diagnostic(Diagnostic),
1021     Done { success: bool },
1022     InlineAsmError(u32, String),
1023     AbortIfErrors,
1024 }
1025
1026 pub struct Diagnostic {
1027     msg: String,
1028     code: Option<String>,
1029     lvl: Level,
1030 }
1031
1032 fn execute_work<'a>(sess: &'a Session,
1033                     mut work_items: Vec<WorkItem>,
1034                     jobserver: Client,
1035                     exported_symbols: &'a ExportedSymbols,
1036                     scope: &Scope<'a>) {
1037     let (tx, rx) = channel();
1038     let tx2 = tx.clone();
1039
1040     // First up, convert our jobserver into a helper thread so we can use normal
1041     // mpsc channels to manage our messages and such. Once we've got the helper
1042     // thread then request `n-1` tokens because all of our work items are ready
1043     // to go.
1044     //
1045     // Note that the `n-1` is here because we ourselves have a token (our
1046     // process) and we'll use that token to execute at least one unit of work.
1047     //
1048     // After we've requested all these tokens then we'll, when we can, get
1049     // tokens on `rx` above which will get managed in the main loop below.
1050     let helper = jobserver.into_helper_thread(move |token| {
1051         drop(tx2.send(Message::Token(token)));
1052     }).expect("failed to spawn helper thread");
1053     for _ in 0..work_items.len() - 1 {
1054         helper.request_token();
1055     }
1056
1057     // This is the "main loop" of parallel work happening for parallel codegen.
1058     // It's here that we manage parallelism, schedule work, and work with
1059     // messages coming from clients.
1060     //
1061     // Our channel `rx` created above is a channel of messages coming from our
1062     // various worker threads. This includes the jobserver helper thread above
1063     // as well as the work we'll spawn off here. Each turn of this loop starts
1064     // off by trying to spawn as much work as possible. After we've done that we
1065     // then wait for an event and dispatch accordingly once the event is
1066     // received. We're only done once all our work items have been drained and
1067     // nothing is running, at which point we return back up the stack.
1068     //
1069     // ## Parallelism management
1070     //
1071     // It's worth also touching on the management of parallelism here. We don't
1072     // want to just spawn a thread per work item because while that's optimal
1073     // parallelism it may overload a system with too many threads or violate our
1074     // configuration for the maximum amount of cpu to use for this process. To
1075     // manage this we use the `jobserver` crate.
1076     //
1077     // Job servers are an artifact of GNU make and are used to manage
1078     // parallelism between processes. A jobserver is a glorified IPC semaphore
1079     // basically. Whenever we want to run some work we acquire the semaphore,
1080     // and whenever we're done with that work we release the semaphore. In this
1081     // manner we can ensure that the maximum number of parallel workers is
1082     // capped at any one point in time.
1083     //
1084     // The jobserver protocol is a little unique, however. We, as a running
1085     // process, already have an ephemeral token assigned to us. We're not going
1086     // to be doing any productive work in this thread though so we're going to
1087     // give this token to a worker thread (there's no actual token to give, this
1088     // is just conceptually). As a result you'll see a few `+1` and `-1`
1089     // instances below, and it's about working with this ephemeral token.
1090     //
1091     // To acquire tokens we have our `helper` thread above which is just in a
1092     // loop acquiring tokens and sending them to us. We then store all tokens
1093     // locally in a `tokens` vector once they're acquired. Currently we don't
1094     // literally send a token to a worker thread to assist with management of
1095     // our "ephemeral token".
1096     //
1097     // As a result, our "spawn as much work as possible" basically means that we
1098     // fill up the `running` counter up to the limit of the `tokens` list.
1099     // Whenever we get a new token this'll mean a new unit of work is spawned,
1100     // and then whenever a unit of work finishes we relinquish a token, if we
1101     // had one, to maybe get re-acquired later.
1102     //
1103     // Note that there's a race which may mean that we acquire more tokens than
1104     // we originally anticipated. For example let's say we have 2 units of work.
1105     // First we request one token from the helper thread and then we
1106     // immediately spawn one unit of work with our ephemeral token after. We may
1107     // then finish the first piece of work before the token is acquired, but we
1108     // can continue to spawn the second piece of work with our ephemeral token.
1109     // Before that work finishes, however, we may acquire a token. In that case
1110     // we actually wastefully acquired the token, so we relinquish it back to
1111     // the jobserver.
1112     let mut tokens = Vec::new();
1113     let mut running = 0;
1114     while work_items.len() > 0 || running > 0 {
1115
1116         // Spin up what work we can, only doing this while we've got available
1117         // parallelism slots and work left to spawn.
1118         while work_items.len() > 0 && running < tokens.len() + 1 {
1119             let item = work_items.pop().unwrap();
1120             let index = work_items.len();
1121             spawn_work(sess, exported_symbols, scope, tx.clone(), item, index);
1122             running += 1;
1123         }
1124
1125         // Relinquish accidentally acquired extra tokens
1126         tokens.truncate(running.saturating_sub(1));
1127
1128         match rx.recv().unwrap() {
1129             // Save the token locally and the next turn of the loop will use
1130             // this to spawn a new unit of work, or it may get dropped
1131             // immediately if we have no more work to spawn.
1132             Message::Token(token) => {
1133                 tokens.push(token.expect("failed to acquire jobserver token"));
1134             }
1135
1136             // If a thread exits successfully then we drop a token associated
1137             // with that worker and update our `running` count. We may later
1138             // re-acquire a token to continue running more work. We may also not
1139             // actually drop a token here if the worker was running with an
1140             // "ephemeral token"
1141             //
1142             // Note that if the thread failed that means it panicked, so we
1143             // abort immediately.
1144             Message::Done { success: true } => {
1145                 drop(tokens.pop());
1146                 running -= 1;
1147             }
1148             Message::Done { success: false } => {
1149                 sess.fatal("aborting due to worker thread panic");
1150             }
1151
1152             // Our worker wants us to emit an error message, so get ahold of our
1153             // `sess` and print it out
1154             Message::Diagnostic(diag) => {
1155                 let handler = sess.diagnostic();
1156                 match diag.code {
1157                     Some(ref code) => {
1158                         handler.emit_with_code(&MultiSpan::new(),
1159                                                &diag.msg,
1160                                                &code,
1161                                                diag.lvl);
1162                     }
1163                     None => {
1164                         handler.emit(&MultiSpan::new(),
1165                                      &diag.msg,
1166                                      diag.lvl);
1167                     }
1168                 }
1169             }
1170             Message::InlineAsmError(cookie, msg) => {
1171                 match Mark::from_u32(cookie).expn_info() {
1172                     Some(ei) => sess.span_err(ei.call_site, &msg),
1173                     None     => sess.err(&msg),
1174                 }
1175             }
1176
1177             // Sent to us after a worker sends us a batch of error messages, and
1178             // it's the point at which we check for errors.
1179             Message::AbortIfErrors => sess.diagnostic().abort_if_errors(),
1180         }
1181     }
1182
1183     // Just in case, check this on the way out.
1184     sess.diagnostic().abort_if_errors();
1185 }
1186
1187 struct SharedEmitter {
1188     tx: Sender<Message>,
1189 }
1190
1191 impl Emitter for SharedEmitter {
1192     fn emit(&mut self, db: &DiagnosticBuilder) {
1193         drop(self.tx.send(Message::Diagnostic(Diagnostic {
1194             msg: db.message(),
1195             code: db.code.clone(),
1196             lvl: db.level,
1197         })));
1198         for child in &db.children {
1199             drop(self.tx.send(Message::Diagnostic(Diagnostic {
1200                 msg: child.message(),
1201                 code: None,
1202                 lvl: child.level,
1203             })));
1204         }
1205         drop(self.tx.send(Message::AbortIfErrors));
1206     }
1207 }
1208
1209 fn spawn_work<'a>(sess: &'a Session,
1210                   exported_symbols: &'a ExportedSymbols,
1211                   scope: &Scope<'a>,
1212                   tx: Sender<Message>,
1213                   work: WorkItem,
1214                   idx: usize) {
1215     let plugin_passes = sess.plugin_llvm_passes.borrow().clone();
1216     let remark = sess.opts.cg.remark.clone();
1217     let incr_comp_session_dir = sess.incr_comp_session_dir_opt().map(|r| r.clone());
1218     let depth = time_depth();
1219     let lto = sess.lto();
1220     let crate_types = sess.crate_types.borrow().clone();
1221     let mut each_linked_rlib_for_lto = Vec::new();
1222     drop(link::each_linked_rlib(sess, &mut |cnum, path| {
1223         // `#![no_builtins]` crates don't participate in LTO.
1224         if sess.cstore.is_no_builtins(cnum) {
1225             return
1226         }
1227         each_linked_rlib_for_lto.push((cnum, path.to_path_buf()));
1228     }));
1229     let time_passes = sess.time_passes();
1230     let no_landing_pads = sess.no_landing_pads();
1231     let opts = &sess.opts;
1232
1233     scope.spawn(move || {
1234         set_time_depth(depth);
1235
1236         // Set up a destructor which will fire off a message that we're done as
1237         // we exit.
1238         struct Bomb {
1239             tx: Sender<Message>,
1240             success: bool,
1241         }
1242         impl Drop for Bomb {
1243             fn drop(&mut self) {
1244                 drop(self.tx.send(Message::Done { success: self.success }));
1245             }
1246         }
1247         let mut bomb = Bomb {
1248             tx: tx.clone(),
1249             success: false,
1250         };
1251
1252         // Set up our non-`Send` `CodegenContext` now that we're in a helper
1253         // thread and have all our info available to us.
1254         let emitter = SharedEmitter { tx: tx.clone() };
1255         let diag_handler = Handler::with_emitter(true, false, Box::new(emitter));
1256
1257         let cgcx = CodegenContext {
1258             crate_types: crate_types,
1259             each_linked_rlib_for_lto: each_linked_rlib_for_lto,
1260             lto: lto,
1261             no_landing_pads: no_landing_pads,
1262             opts: opts,
1263             time_passes: time_passes,
1264             exported_symbols: exported_symbols,
1265             handler: &diag_handler,
1266             plugin_passes: plugin_passes,
1267             remark: remark,
1268             worker: idx,
1269             incr_comp_session_dir: incr_comp_session_dir,
1270             tx: tx.clone(),
1271         };
1272
1273         // Execute the work itself, and if it finishes successfully then flag
1274         // ourselves as a success as well.
1275         //
1276         // Note that we ignore the result coming out of `execute_work_item`
1277         // which will tell us if the worker failed with a `FatalError`. If that
1278         // has happened, however, then a diagnostic was sent off to the main
1279         // thread, along with an `AbortIfErrors` message. In that case the main
1280         // thread is already exiting anyway most likely.
1281         //
1282         // In any case, there's no need for us to take further action here, so
1283         // we just ignore the result and then send off our message saying that
1284         // we're done, which if `execute_work_item` failed is unlikely to be
1285         // seen by the main thread, but hey we might as well try anyway.
1286         drop(execute_work_item(&cgcx, work).is_err());
1287         bomb.success = true;
1288     });
1289 }
1290
1291 pub fn run_assembler(sess: &Session, outputs: &OutputFilenames) {
1292     let (pname, mut cmd, _) = get_linker(sess);
1293
1294     for arg in &sess.target.target.options.asm_args {
1295         cmd.arg(arg);
1296     }
1297
1298     cmd.arg("-c").arg("-o").arg(&outputs.path(OutputType::Object))
1299                            .arg(&outputs.temp_path(OutputType::Assembly, None));
1300     debug!("{:?}", cmd);
1301
1302     match cmd.output() {
1303         Ok(prog) => {
1304             if !prog.status.success() {
1305                 let mut note = prog.stderr.clone();
1306                 note.extend_from_slice(&prog.stdout);
1307
1308                 sess.struct_err(&format!("linking with `{}` failed: {}",
1309                                          pname,
1310                                          prog.status))
1311                     .note(&format!("{:?}", &cmd))
1312                     .note(str::from_utf8(&note[..]).unwrap())
1313                     .emit();
1314                 sess.abort_if_errors();
1315             }
1316         },
1317         Err(e) => {
1318             sess.err(&format!("could not exec the linker `{}`: {}", pname, e));
1319             sess.abort_if_errors();
1320         }
1321     }
1322 }
1323
1324 pub unsafe fn with_llvm_pmb(llmod: ModuleRef,
1325                             config: &ModuleConfig,
1326                             f: &mut FnMut(llvm::PassManagerBuilderRef)) {
1327     // Create the PassManagerBuilder for LLVM. We configure it with
1328     // reasonable defaults and prepare it to actually populate the pass
1329     // manager.
1330     let builder = llvm::LLVMPassManagerBuilderCreate();
1331     let opt_level = config.opt_level.unwrap_or(llvm::CodeGenOptLevel::None);
1332     let opt_size = config.opt_size.unwrap_or(llvm::CodeGenOptSizeNone);
1333     let inline_threshold = config.inline_threshold;
1334
1335     llvm::LLVMRustConfigurePassManagerBuilder(builder, opt_level,
1336                                               config.merge_functions,
1337                                               config.vectorize_slp,
1338                                               config.vectorize_loop);
1339     llvm::LLVMPassManagerBuilderSetSizeLevel(builder, opt_size as u32);
1340
1341     if opt_size != llvm::CodeGenOptSizeNone {
1342         llvm::LLVMPassManagerBuilderSetDisableUnrollLoops(builder, 1);
1343     }
1344
1345     llvm::LLVMRustAddBuilderLibraryInfo(builder, llmod, config.no_builtins);
1346
1347     // Here we match what clang does (kinda). For O0 we only inline
1348     // always-inline functions (but don't add lifetime intrinsics), at O1 we
1349     // inline with lifetime intrinsics, and O2+ we add an inliner with a
1350     // thresholds copied from clang.
1351     match (opt_level, opt_size, inline_threshold) {
1352         (.., Some(t)) => {
1353             llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, t as u32);
1354         }
1355         (llvm::CodeGenOptLevel::Aggressive, ..) => {
1356             llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 275);
1357         }
1358         (_, llvm::CodeGenOptSizeDefault, _) => {
1359             llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 75);
1360         }
1361         (_, llvm::CodeGenOptSizeAggressive, _) => {
1362             llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 25);
1363         }
1364         (llvm::CodeGenOptLevel::None, ..) => {
1365             llvm::LLVMRustAddAlwaysInlinePass(builder, false);
1366         }
1367         (llvm::CodeGenOptLevel::Less, ..) => {
1368             llvm::LLVMRustAddAlwaysInlinePass(builder, true);
1369         }
1370         (llvm::CodeGenOptLevel::Default, ..) => {
1371             llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 225);
1372         }
1373         (llvm::CodeGenOptLevel::Other, ..) => {
1374             bug!("CodeGenOptLevel::Other selected")
1375         }
1376     }
1377
1378     f(builder);
1379     llvm::LLVMPassManagerBuilderDispose(builder);
1380 }