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