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