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