]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/back/write.rs
Auto merge of #35365 - GuillaumeGomez:rollup, r=GuillaumeGomez
[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::{get_linker, remove};
13 use rustc_incremental::save_trans_partition;
14 use session::config::{OutputFilenames, Passes, SomePasses, AllPasses};
15 use session::Session;
16 use session::config::{self, OutputType};
17 use llvm;
18 use llvm::{ModuleRef, TargetMachineRef, PassManagerRef, DiagnosticInfoRef, ContextRef};
19 use llvm::SMDiagnosticRef;
20 use {CrateTranslation, ModuleLlvm, ModuleSource, ModuleTranslation};
21 use util::common::time;
22 use util::common::path2cstr;
23 use util::fs::link_or_copy;
24 use errors::{self, Handler, Level, DiagnosticBuilder};
25 use errors::emitter::Emitter;
26 use syntax_pos::MultiSpan;
27 use context::{is_pie_binary, get_reloc_model};
28
29 use std::collections::HashMap;
30 use std::ffi::{CStr, CString};
31 use std::fs;
32 use std::path::{Path, PathBuf};
33 use std::str;
34 use std::sync::{Arc, Mutex};
35 use std::sync::mpsc::channel;
36 use std::thread;
37 use libc::{c_uint, c_void};
38
39 pub fn llvm_err(handler: &errors::Handler, msg: String) -> ! {
40     match llvm::last_error() {
41         Some(err) => panic!(handler.fatal(&format!("{}: {}", msg, err))),
42         None => panic!(handler.fatal(&msg)),
43     }
44 }
45
46 pub fn write_output_file(
47         handler: &errors::Handler,
48         target: llvm::TargetMachineRef,
49         pm: llvm::PassManagerRef,
50         m: ModuleRef,
51         output: &Path,
52         file_type: llvm::FileType) {
53     unsafe {
54         let output_c = path2cstr(output);
55         let result = llvm::LLVMRustWriteOutputFile(
56                 target, pm, m, output_c.as_ptr(), file_type);
57         if result.into_result().is_err() {
58             llvm_err(handler, format!("could not write output to {}", output.display()));
59         }
60     }
61 }
62
63
64 struct Diagnostic {
65     msg: String,
66     code: Option<String>,
67     lvl: Level,
68 }
69
70 // We use an Arc instead of just returning a list of diagnostics from the
71 // child thread because we need to make sure that the messages are seen even
72 // if the child thread panics (for example, when `fatal` is called).
73 #[derive(Clone)]
74 struct SharedEmitter {
75     buffer: Arc<Mutex<Vec<Diagnostic>>>,
76 }
77
78 impl SharedEmitter {
79     fn new() -> SharedEmitter {
80         SharedEmitter {
81             buffer: Arc::new(Mutex::new(Vec::new())),
82         }
83     }
84
85     fn dump(&mut self, handler: &Handler) {
86         let mut buffer = self.buffer.lock().unwrap();
87         for diag in &*buffer {
88             match diag.code {
89                 Some(ref code) => {
90                     handler.emit_with_code(&MultiSpan::new(),
91                                            &diag.msg,
92                                            &code[..],
93                                            diag.lvl);
94                 },
95                 None => {
96                     handler.emit(&MultiSpan::new(),
97                                  &diag.msg,
98                                  diag.lvl);
99                 },
100             }
101         }
102         buffer.clear();
103     }
104 }
105
106 impl Emitter for SharedEmitter {
107     fn emit(&mut self, db: &DiagnosticBuilder) {
108         self.buffer.lock().unwrap().push(Diagnostic {
109             msg: db.message.to_string(),
110             code: db.code.clone(),
111             lvl: db.level,
112         });
113         for child in &db.children {
114             self.buffer.lock().unwrap().push(Diagnostic {
115                 msg: child.message.to_string(),
116                 code: None,
117                 lvl: child.level,
118             });
119         }
120     }
121 }
122
123 // On android, we by default compile for armv7 processors. This enables
124 // things like double word CAS instructions (rather than emulating them)
125 // which are *far* more efficient. This is obviously undesirable in some
126 // cases, so if any sort of target feature is specified we don't append v7
127 // to the feature list.
128 //
129 // On iOS only armv7 and newer are supported. So it is useful to
130 // get all hardware potential via VFP3 (hardware floating point)
131 // and NEON (SIMD) instructions supported by LLVM.
132 // Note that without those flags various linking errors might
133 // arise as some of intrinsics are converted into function calls
134 // and nobody provides implementations those functions
135 fn target_feature(sess: &Session) -> String {
136     format!("{},{}", sess.target.target.options.features, sess.opts.cg.target_feature)
137 }
138
139 fn get_llvm_opt_level(optimize: config::OptLevel) -> llvm::CodeGenOptLevel {
140     match optimize {
141       config::OptLevel::No => llvm::CodeGenOptLevel::None,
142       config::OptLevel::Less => llvm::CodeGenOptLevel::Less,
143       config::OptLevel::Default => llvm::CodeGenOptLevel::Default,
144       config::OptLevel::Aggressive => llvm::CodeGenOptLevel::Aggressive,
145       _ => llvm::CodeGenOptLevel::Default,
146     }
147 }
148
149 fn get_llvm_opt_size(optimize: config::OptLevel) -> llvm::CodeGenOptSize {
150     match optimize {
151       config::OptLevel::Size => llvm::CodeGenOptSizeDefault,
152       config::OptLevel::SizeMin => llvm::CodeGenOptSizeAggressive,
153       _ => llvm::CodeGenOptSizeNone,
154     }
155 }
156
157 pub fn create_target_machine(sess: &Session) -> TargetMachineRef {
158     let reloc_model = get_reloc_model(sess);
159
160     let opt_level = get_llvm_opt_level(sess.opts.optimize);
161     let use_softfp = sess.opts.cg.soft_float;
162
163     let ffunction_sections = sess.target.target.options.function_sections;
164     let fdata_sections = ffunction_sections;
165
166     let code_model_arg = match sess.opts.cg.code_model {
167         Some(ref s) => &s[..],
168         None => &sess.target.target.options.code_model[..],
169     };
170
171     let code_model = match code_model_arg {
172         "default" => llvm::CodeModel::Default,
173         "small" => llvm::CodeModel::Small,
174         "kernel" => llvm::CodeModel::Kernel,
175         "medium" => llvm::CodeModel::Medium,
176         "large" => llvm::CodeModel::Large,
177         _ => {
178             sess.err(&format!("{:?} is not a valid code model",
179                              sess.opts
180                                  .cg
181                                  .code_model));
182             sess.abort_if_errors();
183             bug!();
184         }
185     };
186
187     let triple = &sess.target.target.llvm_target;
188
189     let tm = unsafe {
190         let triple = CString::new(triple.as_bytes()).unwrap();
191         let cpu = match sess.opts.cg.target_cpu {
192             Some(ref s) => &**s,
193             None => &*sess.target.target.options.cpu
194         };
195         let cpu = CString::new(cpu.as_bytes()).unwrap();
196         let features = CString::new(target_feature(sess).as_bytes()).unwrap();
197         llvm::LLVMRustCreateTargetMachine(
198             triple.as_ptr(), cpu.as_ptr(), features.as_ptr(),
199             code_model,
200             reloc_model,
201             opt_level,
202             use_softfp,
203             is_pie_binary(sess),
204             ffunction_sections,
205             fdata_sections,
206         )
207     };
208
209     if tm.is_null() {
210         llvm_err(sess.diagnostic(),
211                  format!("Could not create LLVM TargetMachine for triple: {}",
212                          triple).to_string());
213     } else {
214         return tm;
215     };
216 }
217
218
219 /// Module-specific configuration for `optimize_and_codegen`.
220 #[derive(Clone)]
221 pub struct ModuleConfig {
222     /// LLVM TargetMachine to use for codegen.
223     tm: TargetMachineRef,
224     /// Names of additional optimization passes to run.
225     passes: Vec<String>,
226     /// Some(level) to optimize at a certain level, or None to run
227     /// absolutely no optimizations (used for the metadata module).
228     opt_level: Option<llvm::CodeGenOptLevel>,
229
230     /// Some(level) to optimize binary size, or None to not affect program size.
231     opt_size: Option<llvm::CodeGenOptSize>,
232
233     // Flags indicating which outputs to produce.
234     emit_no_opt_bc: bool,
235     emit_bc: bool,
236     emit_lto_bc: bool,
237     emit_ir: bool,
238     emit_asm: bool,
239     emit_obj: bool,
240     // Miscellaneous flags.  These are mostly copied from command-line
241     // options.
242     no_verify: bool,
243     no_prepopulate_passes: bool,
244     no_builtins: bool,
245     time_passes: bool,
246     vectorize_loop: bool,
247     vectorize_slp: bool,
248     merge_functions: bool,
249     inline_threshold: Option<usize>,
250     // Instead of creating an object file by doing LLVM codegen, just
251     // make the object file bitcode. Provides easy compatibility with
252     // emscripten's ecc compiler, when used as the linker.
253     obj_is_bitcode: bool,
254 }
255
256 unsafe impl Send for ModuleConfig { }
257
258 impl ModuleConfig {
259     fn new(tm: TargetMachineRef, passes: Vec<String>) -> ModuleConfig {
260         ModuleConfig {
261             tm: tm,
262             passes: passes,
263             opt_level: None,
264             opt_size: None,
265
266             emit_no_opt_bc: false,
267             emit_bc: false,
268             emit_lto_bc: false,
269             emit_ir: false,
270             emit_asm: false,
271             emit_obj: false,
272             obj_is_bitcode: false,
273
274             no_verify: false,
275             no_prepopulate_passes: false,
276             no_builtins: false,
277             time_passes: false,
278             vectorize_loop: false,
279             vectorize_slp: false,
280             merge_functions: false,
281             inline_threshold: None
282         }
283     }
284
285     fn set_flags(&mut self, sess: &Session, trans: &CrateTranslation) {
286         self.no_verify = sess.no_verify();
287         self.no_prepopulate_passes = sess.opts.cg.no_prepopulate_passes;
288         self.no_builtins = trans.no_builtins;
289         self.time_passes = sess.time_passes();
290         self.inline_threshold = sess.opts.cg.inline_threshold;
291         self.obj_is_bitcode = sess.target.target.options.obj_is_bitcode;
292
293         // Copy what clang does by turning on loop vectorization at O2 and
294         // slp vectorization at O3. Otherwise configure other optimization aspects
295         // of this pass manager builder.
296         self.vectorize_loop = !sess.opts.cg.no_vectorize_loops &&
297                              (sess.opts.optimize == config::OptLevel::Default ||
298                               sess.opts.optimize == config::OptLevel::Aggressive);
299         self.vectorize_slp = !sess.opts.cg.no_vectorize_slp &&
300                             sess.opts.optimize == config::OptLevel::Aggressive;
301
302         self.merge_functions = sess.opts.optimize == config::OptLevel::Default ||
303                                sess.opts.optimize == config::OptLevel::Aggressive;
304     }
305 }
306
307 /// Additional resources used by optimize_and_codegen (not module specific)
308 struct CodegenContext<'a> {
309     // Extra resources used for LTO: (sess, reachable).  This will be `None`
310     // when running in a worker thread.
311     lto_ctxt: Option<(&'a Session, &'a [String])>,
312     // Handler to use for diagnostics produced during codegen.
313     handler: &'a Handler,
314     // LLVM passes added by plugins.
315     plugin_passes: Vec<String>,
316     // LLVM optimizations for which we want to print remarks.
317     remark: Passes,
318     // Worker thread number
319     worker: usize,
320     // Directory where incremental data is stored (if any)
321     incremental: Option<PathBuf>,
322 }
323
324 impl<'a> CodegenContext<'a> {
325     fn new_with_session(sess: &'a Session, reachable: &'a [String]) -> CodegenContext<'a> {
326         CodegenContext {
327             lto_ctxt: Some((sess, reachable)),
328             handler: sess.diagnostic(),
329             plugin_passes: sess.plugin_llvm_passes.borrow().clone(),
330             remark: sess.opts.cg.remark.clone(),
331             worker: 0,
332             incremental: sess.opts.incremental.clone(),
333         }
334     }
335 }
336
337 struct HandlerFreeVars<'a> {
338     llcx: ContextRef,
339     cgcx: &'a CodegenContext<'a>,
340 }
341
342 unsafe extern "C" fn report_inline_asm<'a, 'b>(cgcx: &'a CodegenContext<'a>,
343                                                msg: &'b str,
344                                                cookie: c_uint) {
345     use syntax_pos::ExpnId;
346
347     match cgcx.lto_ctxt {
348         Some((sess, _)) => {
349             sess.codemap().with_expn_info(ExpnId::from_u32(cookie), |info| match info {
350                 Some(ei) => sess.span_err(ei.call_site, msg),
351                 None     => sess.err(msg),
352             });
353         }
354
355         None => {
356             cgcx.handler.struct_err(msg)
357                         .note("build without -C codegen-units for more exact errors")
358                         .emit();
359         }
360     }
361 }
362
363 unsafe extern "C" fn inline_asm_handler(diag: SMDiagnosticRef,
364                                         user: *const c_void,
365                                         cookie: c_uint) {
366     let HandlerFreeVars { cgcx, .. } = *(user as *const HandlerFreeVars);
367
368     let msg = llvm::build_string(|s| llvm::LLVMRustWriteSMDiagnosticToString(diag, s))
369         .expect("non-UTF8 SMDiagnostic");
370
371     report_inline_asm(cgcx, &msg[..], cookie);
372 }
373
374 unsafe extern "C" fn diagnostic_handler(info: DiagnosticInfoRef, user: *mut c_void) {
375     let HandlerFreeVars { llcx, cgcx } = *(user as *const HandlerFreeVars);
376
377     match llvm::diagnostic::Diagnostic::unpack(info) {
378         llvm::diagnostic::InlineAsm(inline) => {
379             report_inline_asm(cgcx,
380                               &llvm::twine_to_string(inline.message),
381                               inline.cookie);
382         }
383
384         llvm::diagnostic::Optimization(opt) => {
385             let pass_name = str::from_utf8(CStr::from_ptr(opt.pass_name).to_bytes())
386                                 .ok()
387                                 .expect("got a non-UTF8 pass name from LLVM");
388             let enabled = match cgcx.remark {
389                 AllPasses => true,
390                 SomePasses(ref v) => v.iter().any(|s| *s == pass_name),
391             };
392
393             if enabled {
394                 let loc = llvm::debug_loc_to_string(llcx, opt.debug_loc);
395                 cgcx.handler.note_without_error(&format!("optimization {} for {} at {}: {}",
396                                                 opt.kind.describe(),
397                                                 pass_name,
398                                                 if loc.is_empty() { "[unknown]" } else { &*loc },
399                                                 llvm::twine_to_string(opt.message)));
400             }
401         }
402
403         _ => (),
404     }
405 }
406
407 // Unsafe due to LLVM calls.
408 unsafe fn optimize_and_codegen(cgcx: &CodegenContext,
409                                mtrans: ModuleTranslation,
410                                mllvm: ModuleLlvm,
411                                config: ModuleConfig,
412                                output_names: OutputFilenames) {
413     let llmod = mllvm.llmod;
414     let llcx = mllvm.llcx;
415     let tm = config.tm;
416
417     // llcx doesn't outlive this function, so we can put this on the stack.
418     let fv = HandlerFreeVars {
419         llcx: llcx,
420         cgcx: cgcx,
421     };
422     let fv = &fv as *const HandlerFreeVars as *mut c_void;
423
424     llvm::LLVMRustSetInlineAsmDiagnosticHandler(llcx, inline_asm_handler, fv);
425     llvm::LLVMContextSetDiagnosticHandler(llcx, diagnostic_handler, fv);
426
427     let module_name = Some(&mtrans.name[..]);
428
429     if config.emit_no_opt_bc {
430         let out = output_names.temp_path_ext("no-opt.bc", module_name);
431         let out = path2cstr(&out);
432         llvm::LLVMWriteBitcodeToFile(llmod, out.as_ptr());
433     }
434
435     if config.opt_level.is_some() {
436         // Create the two optimizing pass managers. These mirror what clang
437         // does, and are by populated by LLVM's default PassManagerBuilder.
438         // Each manager has a different set of passes, but they also share
439         // some common passes.
440         let fpm = llvm::LLVMCreateFunctionPassManagerForModule(llmod);
441         let mpm = llvm::LLVMCreatePassManager();
442
443         // If we're verifying or linting, add them to the function pass
444         // manager.
445         let addpass = |pass_name: &str| {
446             let pass_name = CString::new(pass_name).unwrap();
447             let pass = llvm::LLVMRustFindAndCreatePass(pass_name.as_ptr());
448             if pass.is_null() {
449                 return false;
450             }
451             let pass_manager = match llvm::LLVMRustPassKind(pass) {
452                 llvm::PassKind::Function => fpm,
453                 llvm::PassKind::Module => mpm,
454                 llvm::PassKind::Other => {
455                     cgcx.handler.err("Encountered LLVM pass kind we can't handle");
456                     return true
457                 },
458             };
459             llvm::LLVMRustAddPass(pass_manager, pass);
460             true
461         };
462
463         if !config.no_verify { assert!(addpass("verify")); }
464         if !config.no_prepopulate_passes {
465             llvm::LLVMRustAddAnalysisPasses(tm, fpm, llmod);
466             llvm::LLVMRustAddAnalysisPasses(tm, mpm, llmod);
467             with_llvm_pmb(llmod, &config, &mut |b| {
468                 llvm::LLVMPassManagerBuilderPopulateFunctionPassManager(b, fpm);
469                 llvm::LLVMPassManagerBuilderPopulateModulePassManager(b, mpm);
470             })
471         }
472
473         for pass in &config.passes {
474             if !addpass(pass) {
475                 cgcx.handler.warn(&format!("unknown pass `{}`, ignoring",
476                                            pass));
477             }
478         }
479
480         for pass in &cgcx.plugin_passes {
481             if !addpass(pass) {
482                 cgcx.handler.err(&format!("a plugin asked for LLVM pass \
483                                            `{}` but LLVM does not \
484                                            recognize it", pass));
485             }
486         }
487
488         cgcx.handler.abort_if_errors();
489
490         // Finally, run the actual optimization passes
491         time(config.time_passes, &format!("llvm function passes [{}]", cgcx.worker), ||
492              llvm::LLVMRustRunFunctionPassManager(fpm, llmod));
493         time(config.time_passes, &format!("llvm module passes [{}]", cgcx.worker), ||
494              llvm::LLVMRunPassManager(mpm, llmod));
495
496         // Deallocate managers that we're now done with
497         llvm::LLVMDisposePassManager(fpm);
498         llvm::LLVMDisposePassManager(mpm);
499
500         match cgcx.lto_ctxt {
501             Some((sess, reachable)) if sess.lto() =>  {
502                 time(sess.time_passes(), "all lto passes", || {
503                     let temp_no_opt_bc_filename =
504                         output_names.temp_path_ext("no-opt.lto.bc", module_name);
505                     lto::run(sess,
506                              llmod,
507                              tm,
508                              reachable,
509                              &config,
510                              &temp_no_opt_bc_filename);
511                 });
512                 if config.emit_lto_bc {
513                     let out = output_names.temp_path_ext("lto.bc", module_name);
514                     let out = path2cstr(&out);
515                     llvm::LLVMWriteBitcodeToFile(llmod, out.as_ptr());
516                 }
517             },
518             _ => {},
519         }
520     }
521
522     // A codegen-specific pass manager is used to generate object
523     // files for an LLVM module.
524     //
525     // Apparently each of these pass managers is a one-shot kind of
526     // thing, so we create a new one for each type of output. The
527     // pass manager passed to the closure should be ensured to not
528     // escape the closure itself, and the manager should only be
529     // used once.
530     unsafe fn with_codegen<F>(tm: TargetMachineRef,
531                               llmod: ModuleRef,
532                               no_builtins: bool,
533                               f: F) where
534         F: FnOnce(PassManagerRef),
535     {
536         let cpm = llvm::LLVMCreatePassManager();
537         llvm::LLVMRustAddAnalysisPasses(tm, cpm, llmod);
538         llvm::LLVMRustAddLibraryInfo(cpm, llmod, no_builtins);
539         f(cpm);
540     }
541
542     // Change what we write and cleanup based on whether obj files are
543     // just llvm bitcode. In that case write bitcode, and possibly
544     // delete the bitcode if it wasn't requested. Don't generate the
545     // machine code, instead copy the .o file from the .bc
546     let write_bc = config.emit_bc || config.obj_is_bitcode;
547     let rm_bc = !config.emit_bc && config.obj_is_bitcode;
548     let write_obj = config.emit_obj && !config.obj_is_bitcode;
549     let copy_bc_to_obj = config.emit_obj && config.obj_is_bitcode;
550
551     let bc_out = output_names.temp_path(OutputType::Bitcode, module_name);
552     let obj_out = output_names.temp_path(OutputType::Object, module_name);
553
554     if write_bc {
555         let bc_out_c = path2cstr(&bc_out);
556         llvm::LLVMWriteBitcodeToFile(llmod, bc_out_c.as_ptr());
557     }
558
559     time(config.time_passes, &format!("codegen passes [{}]", cgcx.worker), || {
560         if config.emit_ir {
561             let out = output_names.temp_path(OutputType::LlvmAssembly, module_name);
562             let out = path2cstr(&out);
563             with_codegen(tm, llmod, config.no_builtins, |cpm| {
564                 llvm::LLVMRustPrintModule(cpm, llmod, out.as_ptr());
565                 llvm::LLVMDisposePassManager(cpm);
566             })
567         }
568
569         if config.emit_asm {
570             let path = output_names.temp_path(OutputType::Assembly, module_name);
571
572             // We can't use the same module for asm and binary output, because that triggers
573             // various errors like invalid IR or broken binaries, so we might have to clone the
574             // module to produce the asm output
575             let llmod = if config.emit_obj {
576                 llvm::LLVMCloneModule(llmod)
577             } else {
578                 llmod
579             };
580             with_codegen(tm, llmod, config.no_builtins, |cpm| {
581                 write_output_file(cgcx.handler, tm, cpm, llmod, &path,
582                                   llvm::FileType::AssemblyFile);
583             });
584             if config.emit_obj {
585                 llvm::LLVMDisposeModule(llmod);
586             }
587         }
588
589         if write_obj {
590             with_codegen(tm, llmod, config.no_builtins, |cpm| {
591                 write_output_file(cgcx.handler, tm, cpm, llmod, &obj_out,
592                                   llvm::FileType::ObjectFile);
593             });
594         }
595     });
596
597     if copy_bc_to_obj {
598         debug!("copying bitcode {:?} to obj {:?}", bc_out, obj_out);
599         if let Err(e) = link_or_copy(&bc_out, &obj_out) {
600             cgcx.handler.err(&format!("failed to copy bitcode to object file: {}", e));
601         }
602     }
603
604     if rm_bc {
605         debug!("removing_bitcode {:?}", bc_out);
606         if let Err(e) = fs::remove_file(&bc_out) {
607             cgcx.handler.err(&format!("failed to remove bitcode: {}", e));
608         }
609     }
610
611     llvm::LLVMRustDisposeTargetMachine(tm);
612 }
613
614
615 pub fn cleanup_llvm(trans: &CrateTranslation) {
616     for module in trans.modules.iter() {
617         unsafe {
618             match module.source {
619                 ModuleSource::Translated(llvm) => {
620                     llvm::LLVMDisposeModule(llvm.llmod);
621                     llvm::LLVMContextDispose(llvm.llcx);
622                 }
623                 ModuleSource::Preexisting(_) => {
624                 }
625             }
626         }
627     }
628 }
629
630 pub fn run_passes(sess: &Session,
631                   trans: &CrateTranslation,
632                   output_types: &HashMap<OutputType, Option<PathBuf>>,
633                   crate_output: &OutputFilenames) {
634     // It's possible that we have `codegen_units > 1` but only one item in
635     // `trans.modules`.  We could theoretically proceed and do LTO in that
636     // case, but it would be confusing to have the validity of
637     // `-Z lto -C codegen-units=2` depend on details of the crate being
638     // compiled, so we complain regardless.
639     if sess.lto() && sess.opts.cg.codegen_units > 1 {
640         // This case is impossible to handle because LTO expects to be able
641         // to combine the entire crate and all its dependencies into a
642         // single compilation unit, but each codegen unit is in a separate
643         // LLVM context, so they can't easily be combined.
644         sess.fatal("can't perform LTO when using multiple codegen units");
645     }
646
647     // Sanity check
648     assert!(trans.modules.len() == sess.opts.cg.codegen_units ||
649             sess.opts.debugging_opts.incremental.is_some());
650
651     let tm = create_target_machine(sess);
652
653     // Figure out what we actually need to build.
654
655     let mut modules_config = ModuleConfig::new(tm, sess.opts.cg.passes.clone());
656     let mut metadata_config = ModuleConfig::new(tm, vec!());
657
658     modules_config.opt_level = Some(get_llvm_opt_level(sess.opts.optimize));
659     modules_config.opt_size = Some(get_llvm_opt_size(sess.opts.optimize));
660
661     // Save all versions of the bytecode if we're saving our temporaries.
662     if sess.opts.cg.save_temps {
663         modules_config.emit_no_opt_bc = true;
664         modules_config.emit_bc = true;
665         modules_config.emit_lto_bc = true;
666         metadata_config.emit_bc = true;
667     }
668
669     // Emit bitcode files for the crate if we're emitting an rlib.
670     // Whenever an rlib is created, the bitcode is inserted into the
671     // archive in order to allow LTO against it.
672     let needs_crate_bitcode =
673             sess.crate_types.borrow().contains(&config::CrateTypeRlib) &&
674             sess.opts.output_types.contains_key(&OutputType::Exe);
675     let needs_crate_object =
676             sess.opts.output_types.contains_key(&OutputType::Exe);
677     if needs_crate_bitcode {
678         modules_config.emit_bc = true;
679     }
680
681     for output_type in output_types.keys() {
682         match *output_type {
683             OutputType::Bitcode => { modules_config.emit_bc = true; },
684             OutputType::LlvmAssembly => { modules_config.emit_ir = true; },
685             OutputType::Assembly => {
686                 modules_config.emit_asm = true;
687                 // If we're not using the LLVM assembler, this function
688                 // could be invoked specially with output_type_assembly, so
689                 // in this case we still want the metadata object file.
690                 if !sess.opts.output_types.contains_key(&OutputType::Assembly) {
691                     metadata_config.emit_obj = true;
692                 }
693             },
694             OutputType::Object => { modules_config.emit_obj = true; },
695             OutputType::Exe => {
696                 modules_config.emit_obj = true;
697                 metadata_config.emit_obj = true;
698             },
699             OutputType::DepInfo => {}
700         }
701     }
702
703     modules_config.set_flags(sess, trans);
704     metadata_config.set_flags(sess, trans);
705
706
707     // Populate a buffer with a list of codegen threads.  Items are processed in
708     // LIFO order, just because it's a tiny bit simpler that way.  (The order
709     // doesn't actually matter.)
710     let mut work_items = Vec::with_capacity(1 + trans.modules.len());
711
712     {
713         let work = build_work_item(sess,
714                                    trans.metadata_module.clone(),
715                                    metadata_config.clone(),
716                                    crate_output.clone());
717         work_items.push(work);
718     }
719
720     for mtrans in trans.modules.iter() {
721         let work = build_work_item(sess,
722                                    mtrans.clone(),
723                                    modules_config.clone(),
724                                    crate_output.clone());
725         work_items.push(work);
726     }
727
728     // Process the work items, optionally using worker threads.
729     // NOTE: This code is not really adapted to incremental compilation where
730     //       the compiler decides the number of codegen units (and will
731     //       potentially create hundreds of them).
732     let num_workers = work_items.len() - 1;
733     if num_workers == 1 {
734         run_work_singlethreaded(sess, &trans.reachable, work_items);
735     } else {
736         run_work_multithreaded(sess, work_items, num_workers);
737     }
738
739     // If in incr. comp. mode, preserve the `.o` files for potential re-use
740     for mtrans in trans.modules.iter() {
741         let mut files = vec![];
742
743         if modules_config.emit_obj {
744             let path = crate_output.temp_path(OutputType::Object, Some(&mtrans.name));
745             files.push((OutputType::Object, path));
746         }
747
748         if modules_config.emit_bc {
749             let path = crate_output.temp_path(OutputType::Bitcode, Some(&mtrans.name));
750             files.push((OutputType::Bitcode, path));
751         }
752
753         save_trans_partition(sess, &mtrans.name, mtrans.symbol_name_hash, &files);
754     }
755
756     // All codegen is finished.
757     unsafe {
758         llvm::LLVMRustDisposeTargetMachine(tm);
759     }
760
761     // Produce final compile outputs.
762     let copy_gracefully = |from: &Path, to: &Path| {
763         if let Err(e) = fs::copy(from, to) {
764             sess.err(&format!("could not copy {:?} to {:?}: {}", from, to, e));
765         }
766     };
767
768     let copy_if_one_unit = |output_type: OutputType,
769                             keep_numbered: bool| {
770         if trans.modules.len() == 1 {
771             // 1) Only one codegen unit.  In this case it's no difficulty
772             //    to copy `foo.0.x` to `foo.x`.
773             let module_name = Some(&(trans.modules[0].name)[..]);
774             let path = crate_output.temp_path(output_type, module_name);
775             copy_gracefully(&path,
776                             &crate_output.path(output_type));
777             if !sess.opts.cg.save_temps && !keep_numbered {
778                 // The user just wants `foo.x`, not `foo.#module-name#.x`.
779                 remove(sess, &path);
780             }
781         } else {
782             let ext = crate_output.temp_path(output_type, None)
783                                   .extension()
784                                   .unwrap()
785                                   .to_str()
786                                   .unwrap()
787                                   .to_owned();
788
789             if crate_output.outputs.contains_key(&output_type) {
790                 // 2) Multiple codegen units, with `--emit foo=some_name`.  We have
791                 //    no good solution for this case, so warn the user.
792                 sess.warn(&format!("ignoring emit path because multiple .{} files \
793                                     were produced", ext));
794             } else if crate_output.single_output_file.is_some() {
795                 // 3) Multiple codegen units, with `-o some_name`.  We have
796                 //    no good solution for this case, so warn the user.
797                 sess.warn(&format!("ignoring -o because multiple .{} files \
798                                     were produced", ext));
799             } else {
800                 // 4) Multiple codegen units, but no explicit name.  We
801                 //    just leave the `foo.0.x` files in place.
802                 // (We don't have to do any work in this case.)
803             }
804         }
805     };
806
807     // Flag to indicate whether the user explicitly requested bitcode.
808     // Otherwise, we produced it only as a temporary output, and will need
809     // to get rid of it.
810     let mut user_wants_bitcode = false;
811     let mut user_wants_objects = false;
812     for output_type in output_types.keys() {
813         match *output_type {
814             OutputType::Bitcode => {
815                 user_wants_bitcode = true;
816                 // Copy to .bc, but always keep the .0.bc.  There is a later
817                 // check to figure out if we should delete .0.bc files, or keep
818                 // them for making an rlib.
819                 copy_if_one_unit(OutputType::Bitcode, true);
820             }
821             OutputType::LlvmAssembly => {
822                 copy_if_one_unit(OutputType::LlvmAssembly, false);
823             }
824             OutputType::Assembly => {
825                 copy_if_one_unit(OutputType::Assembly, false);
826             }
827             OutputType::Object => {
828                 user_wants_objects = true;
829                 copy_if_one_unit(OutputType::Object, true);
830             }
831             OutputType::Exe |
832             OutputType::DepInfo => {}
833         }
834     }
835     let user_wants_bitcode = user_wants_bitcode;
836
837     // Clean up unwanted temporary files.
838
839     // We create the following files by default:
840     //  - crate.#module-name#.bc
841     //  - crate.#module-name#.o
842     //  - crate.metadata.bc
843     //  - crate.metadata.o
844     //  - crate.o (linked from crate.##.o)
845     //  - crate.bc (copied from crate.##.bc)
846     // We may create additional files if requested by the user (through
847     // `-C save-temps` or `--emit=` flags).
848
849     if !sess.opts.cg.save_temps {
850         // Remove the temporary .#module-name#.o objects.  If the user didn't
851         // explicitly request bitcode (with --emit=bc), and the bitcode is not
852         // needed for building an rlib, then we must remove .#module-name#.bc as
853         // well.
854
855         // Specific rules for keeping .#module-name#.bc:
856         //  - If we're building an rlib (`needs_crate_bitcode`), then keep
857         //    it.
858         //  - If the user requested bitcode (`user_wants_bitcode`), and
859         //    codegen_units > 1, then keep it.
860         //  - If the user requested bitcode but codegen_units == 1, then we
861         //    can toss .#module-name#.bc because we copied it to .bc earlier.
862         //  - If we're not building an rlib and the user didn't request
863         //    bitcode, then delete .#module-name#.bc.
864         // If you change how this works, also update back::link::link_rlib,
865         // where .#module-name#.bc files are (maybe) deleted after making an
866         // rlib.
867         let keep_numbered_bitcode = needs_crate_bitcode ||
868                 (user_wants_bitcode && sess.opts.cg.codegen_units > 1);
869
870         let keep_numbered_objects = needs_crate_object ||
871                 (user_wants_objects && sess.opts.cg.codegen_units > 1);
872
873         for module_name in trans.modules.iter().map(|m| Some(&m.name[..])) {
874             if modules_config.emit_obj && !keep_numbered_objects {
875                 let path = crate_output.temp_path(OutputType::Object, module_name);
876                 remove(sess, &path);
877             }
878
879             if modules_config.emit_bc && !keep_numbered_bitcode {
880                 let path = crate_output.temp_path(OutputType::Bitcode, module_name);
881                 remove(sess, &path);
882             }
883         }
884
885         if metadata_config.emit_bc && !user_wants_bitcode {
886             let path = crate_output.temp_path(OutputType::Bitcode,
887                                               Some(&trans.metadata_module.name[..]));
888             remove(sess, &path);
889         }
890     }
891
892     // We leave the following files around by default:
893     //  - crate.o
894     //  - crate.metadata.o
895     //  - crate.bc
896     // These are used in linking steps and will be cleaned up afterward.
897
898     // FIXME: time_llvm_passes support - does this use a global context or
899     // something?
900     if sess.opts.cg.codegen_units == 1 && sess.time_llvm_passes() {
901         unsafe { llvm::LLVMRustPrintPassTimings(); }
902     }
903 }
904
905 struct WorkItem {
906     mtrans: ModuleTranslation,
907     config: ModuleConfig,
908     output_names: OutputFilenames
909 }
910
911 fn build_work_item(sess: &Session,
912                    mtrans: ModuleTranslation,
913                    config: ModuleConfig,
914                    output_names: OutputFilenames)
915                    -> WorkItem
916 {
917     let mut config = config;
918     config.tm = create_target_machine(sess);
919     WorkItem {
920         mtrans: mtrans,
921         config: config,
922         output_names: output_names
923     }
924 }
925
926 fn execute_work_item(cgcx: &CodegenContext,
927                      work_item: WorkItem) {
928     unsafe {
929         match work_item.mtrans.source {
930             ModuleSource::Translated(mllvm) => {
931                 debug!("llvm-optimizing {:?}", work_item.mtrans.name);
932                 optimize_and_codegen(cgcx,
933                                      work_item.mtrans,
934                                      mllvm,
935                                      work_item.config,
936                                      work_item.output_names);
937             }
938             ModuleSource::Preexisting(wp) => {
939                 let incremental = cgcx.incremental.as_ref().unwrap();
940                 let name = &work_item.mtrans.name;
941                 for (kind, saved_file) in wp.saved_files {
942                     let obj_out = work_item.output_names.temp_path(kind, Some(name));
943                     let source_file = incremental.join(&saved_file);
944                     debug!("copying pre-existing module `{}` from {:?} to {}",
945                            work_item.mtrans.name,
946                            source_file,
947                            obj_out.display());
948                     match link_or_copy(&source_file, &obj_out) {
949                         Ok(()) => { }
950                         Err(err) => {
951                             cgcx.handler.err(&format!("unable to copy {} to {}: {}",
952                                                       source_file.display(),
953                                                       obj_out.display(),
954                                                       err));
955                         }
956                     }
957                 }
958             }
959         }
960     }
961 }
962
963 fn run_work_singlethreaded(sess: &Session,
964                            reachable: &[String],
965                            work_items: Vec<WorkItem>) {
966     let cgcx = CodegenContext::new_with_session(sess, reachable);
967
968     // Since we're running single-threaded, we can pass the session to
969     // the proc, allowing `optimize_and_codegen` to perform LTO.
970     for work in work_items.into_iter().rev() {
971         execute_work_item(&cgcx, work);
972     }
973 }
974
975 fn run_work_multithreaded(sess: &Session,
976                           work_items: Vec<WorkItem>,
977                           num_workers: usize) {
978     assert!(num_workers > 0);
979
980     // Run some workers to process the work items.
981     let work_items_arc = Arc::new(Mutex::new(work_items));
982     let mut diag_emitter = SharedEmitter::new();
983     let mut futures = Vec::with_capacity(num_workers);
984
985     for i in 0..num_workers {
986         let work_items_arc = work_items_arc.clone();
987         let diag_emitter = diag_emitter.clone();
988         let plugin_passes = sess.plugin_llvm_passes.borrow().clone();
989         let remark = sess.opts.cg.remark.clone();
990
991         let (tx, rx) = channel();
992         let mut tx = Some(tx);
993         futures.push(rx);
994
995         let incremental = sess.opts.incremental.clone();
996
997         thread::Builder::new().name(format!("codegen-{}", i)).spawn(move || {
998             let diag_handler = Handler::with_emitter(true, false, box diag_emitter);
999
1000             // Must construct cgcx inside the proc because it has non-Send
1001             // fields.
1002             let cgcx = CodegenContext {
1003                 lto_ctxt: None,
1004                 handler: &diag_handler,
1005                 plugin_passes: plugin_passes,
1006                 remark: remark,
1007                 worker: i,
1008                 incremental: incremental,
1009             };
1010
1011             loop {
1012                 // Avoid holding the lock for the entire duration of the match.
1013                 let maybe_work = work_items_arc.lock().unwrap().pop();
1014                 match maybe_work {
1015                     Some(work) => {
1016                         execute_work_item(&cgcx, work);
1017
1018                         // Make sure to fail the worker so the main thread can
1019                         // tell that there were errors.
1020                         cgcx.handler.abort_if_errors();
1021                     }
1022                     None => break,
1023                 }
1024             }
1025
1026             tx.take().unwrap().send(()).unwrap();
1027         }).unwrap();
1028     }
1029
1030     let mut panicked = false;
1031     for rx in futures {
1032         match rx.recv() {
1033             Ok(()) => {},
1034             Err(_) => {
1035                 panicked = true;
1036             },
1037         }
1038         // Display any new diagnostics.
1039         diag_emitter.dump(sess.diagnostic());
1040     }
1041     if panicked {
1042         sess.fatal("aborting due to worker thread panic");
1043     }
1044 }
1045
1046 pub fn run_assembler(sess: &Session, outputs: &OutputFilenames) {
1047     let (pname, mut cmd, _) = get_linker(sess);
1048
1049     cmd.arg("-c").arg("-o").arg(&outputs.path(OutputType::Object))
1050                            .arg(&outputs.temp_path(OutputType::Assembly, None));
1051     debug!("{:?}", cmd);
1052
1053     match cmd.output() {
1054         Ok(prog) => {
1055             if !prog.status.success() {
1056                 let mut note = prog.stderr.clone();
1057                 note.extend_from_slice(&prog.stdout);
1058
1059                 sess.struct_err(&format!("linking with `{}` failed: {}",
1060                                          pname,
1061                                          prog.status))
1062                     .note(&format!("{:?}", &cmd))
1063                     .note(str::from_utf8(&note[..]).unwrap())
1064                     .emit();
1065                 sess.abort_if_errors();
1066             }
1067         },
1068         Err(e) => {
1069             sess.err(&format!("could not exec the linker `{}`: {}", pname, e));
1070             sess.abort_if_errors();
1071         }
1072     }
1073 }
1074
1075 pub unsafe fn with_llvm_pmb(llmod: ModuleRef,
1076                             config: &ModuleConfig,
1077                             f: &mut FnMut(llvm::PassManagerBuilderRef)) {
1078     // Create the PassManagerBuilder for LLVM. We configure it with
1079     // reasonable defaults and prepare it to actually populate the pass
1080     // manager.
1081     let builder = llvm::LLVMPassManagerBuilderCreate();
1082     let opt_level = config.opt_level.unwrap_or(llvm::CodeGenOptLevel::None);
1083     let opt_size = config.opt_size.unwrap_or(llvm::CodeGenOptSizeNone);
1084     let inline_threshold = config.inline_threshold;
1085
1086     llvm::LLVMRustConfigurePassManagerBuilder(builder, opt_level,
1087                                               config.merge_functions,
1088                                               config.vectorize_slp,
1089                                               config.vectorize_loop);
1090     llvm::LLVMPassManagerBuilderSetSizeLevel(builder, opt_size as u32);
1091
1092     if opt_size != llvm::CodeGenOptSizeNone {
1093         llvm::LLVMPassManagerBuilderSetDisableUnrollLoops(builder, 1);
1094     }
1095
1096     llvm::LLVMRustAddBuilderLibraryInfo(builder, llmod, config.no_builtins);
1097
1098     // Here we match what clang does (kinda). For O0 we only inline
1099     // always-inline functions (but don't add lifetime intrinsics), at O1 we
1100     // inline with lifetime intrinsics, and O2+ we add an inliner with a
1101     // thresholds copied from clang.
1102     match (opt_level, opt_size, inline_threshold) {
1103         (_, _, Some(t)) => {
1104             llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, t as u32);
1105         }
1106         (llvm::CodeGenOptLevel::Aggressive, _, _) => {
1107             llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 275);
1108         }
1109         (_, llvm::CodeGenOptSizeDefault, _) => {
1110             llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 75);
1111         }
1112         (_, llvm::CodeGenOptSizeAggressive, _) => {
1113             llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 25);
1114         }
1115         (llvm::CodeGenOptLevel::None, _, _) => {
1116             llvm::LLVMRustAddAlwaysInlinePass(builder, false);
1117         }
1118         (llvm::CodeGenOptLevel::Less, _, _) => {
1119             llvm::LLVMRustAddAlwaysInlinePass(builder, true);
1120         }
1121         (llvm::CodeGenOptLevel::Default, _, _) => {
1122             llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 225);
1123         }
1124         (llvm::CodeGenOptLevel::Other, _, _) => {
1125             bug!("CodeGenOptLevel::Other selected")
1126         }
1127     }
1128
1129     f(builder);
1130     llvm::LLVMPassManagerBuilderDispose(builder);
1131 }