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.
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.
12 use back::link::{get_linker, remove};
13 use rustc_incremental::save_trans_partition;
14 use session::config::{OutputFilenames, Passes, SomePasses, AllPasses};
16 use session::config::{self, OutputType};
18 use llvm::{ModuleRef, TargetMachineRef, PassManagerRef, DiagnosticInfoRef, ContextRef};
19 use llvm::SMDiagnosticRef;
20 use {CrateTranslation, ModuleLlvm, ModuleSource, ModuleTranslation};
21 use util::common::time;
22 use util::common::path2cstr;
23 use util::fs::link_or_copy;
24 use errors::{self, Handler, Level, DiagnosticBuilder};
25 use errors::emitter::Emitter;
26 use syntax_pos::MultiSpan;
27 use context::{is_pie_binary, get_reloc_model};
29 use std::collections::HashMap;
30 use std::ffi::{CStr, CString};
32 use std::path::{Path, PathBuf};
34 use std::sync::{Arc, Mutex};
35 use std::sync::mpsc::channel;
37 use libc::{c_uint, c_void};
39 pub const RELOC_MODEL_ARGS : [(&'static str, llvm::RelocMode); 4] = [
40 ("pic", llvm::RelocMode::PIC),
41 ("static", llvm::RelocMode::Static),
42 ("default", llvm::RelocMode::Default),
43 ("dynamic-no-pic", llvm::RelocMode::DynamicNoPic),
46 pub const CODE_GEN_MODEL_ARGS : [(&'static str, llvm::CodeModel); 5] = [
47 ("default", llvm::CodeModel::Default),
48 ("small", llvm::CodeModel::Small),
49 ("kernel", llvm::CodeModel::Kernel),
50 ("medium", llvm::CodeModel::Medium),
51 ("large", llvm::CodeModel::Large),
54 pub fn llvm_err(handler: &errors::Handler, msg: String) -> ! {
55 match llvm::last_error() {
56 Some(err) => panic!(handler.fatal(&format!("{}: {}", msg, err))),
57 None => panic!(handler.fatal(&msg)),
61 pub fn write_output_file(
62 handler: &errors::Handler,
63 target: llvm::TargetMachineRef,
64 pm: llvm::PassManagerRef,
67 file_type: llvm::FileType) {
69 let output_c = path2cstr(output);
70 let result = llvm::LLVMRustWriteOutputFile(
71 target, pm, m, output_c.as_ptr(), file_type);
72 if result.into_result().is_err() {
73 llvm_err(handler, format!("could not write output to {}", output.display()));
85 // We use an Arc instead of just returning a list of diagnostics from the
86 // child thread because we need to make sure that the messages are seen even
87 // if the child thread panics (for example, when `fatal` is called).
89 struct SharedEmitter {
90 buffer: Arc<Mutex<Vec<Diagnostic>>>,
94 fn new() -> SharedEmitter {
96 buffer: Arc::new(Mutex::new(Vec::new())),
100 fn dump(&mut self, handler: &Handler) {
101 let mut buffer = self.buffer.lock().unwrap();
102 for diag in &*buffer {
105 handler.emit_with_code(&MultiSpan::new(),
111 handler.emit(&MultiSpan::new(),
121 impl Emitter for SharedEmitter {
122 fn emit(&mut self, db: &DiagnosticBuilder) {
123 self.buffer.lock().unwrap().push(Diagnostic {
124 msg: db.message.to_string(),
125 code: db.code.clone(),
128 for child in &db.children {
129 self.buffer.lock().unwrap().push(Diagnostic {
130 msg: child.message.to_string(),
138 // On android, we by default compile for armv7 processors. This enables
139 // things like double word CAS instructions (rather than emulating them)
140 // which are *far* more efficient. This is obviously undesirable in some
141 // cases, so if any sort of target feature is specified we don't append v7
142 // to the feature list.
144 // On iOS only armv7 and newer are supported. So it is useful to
145 // get all hardware potential via VFP3 (hardware floating point)
146 // and NEON (SIMD) instructions supported by LLVM.
147 // Note that without those flags various linking errors might
148 // arise as some of intrinsics are converted into function calls
149 // and nobody provides implementations those functions
150 fn target_feature(sess: &Session) -> String {
151 format!("{},{}", sess.target.target.options.features, sess.opts.cg.target_feature)
154 fn get_llvm_opt_level(optimize: config::OptLevel) -> llvm::CodeGenOptLevel {
156 config::OptLevel::No => llvm::CodeGenOptLevel::None,
157 config::OptLevel::Less => llvm::CodeGenOptLevel::Less,
158 config::OptLevel::Default => llvm::CodeGenOptLevel::Default,
159 config::OptLevel::Aggressive => llvm::CodeGenOptLevel::Aggressive,
160 _ => llvm::CodeGenOptLevel::Default,
164 fn get_llvm_opt_size(optimize: config::OptLevel) -> llvm::CodeGenOptSize {
166 config::OptLevel::Size => llvm::CodeGenOptSizeDefault,
167 config::OptLevel::SizeMin => llvm::CodeGenOptSizeAggressive,
168 _ => llvm::CodeGenOptSizeNone,
172 pub fn create_target_machine(sess: &Session) -> TargetMachineRef {
173 let reloc_model = get_reloc_model(sess);
175 let opt_level = get_llvm_opt_level(sess.opts.optimize);
176 let use_softfp = sess.opts.cg.soft_float;
178 let ffunction_sections = sess.target.target.options.function_sections;
179 let fdata_sections = ffunction_sections;
181 let code_model_arg = match sess.opts.cg.code_model {
182 Some(ref s) => &s[..],
183 None => &sess.target.target.options.code_model[..],
186 let code_model = match CODE_GEN_MODEL_ARGS.iter().find(
187 |&&arg| arg.0 == code_model_arg) {
190 sess.err(&format!("{:?} is not a valid code model",
194 sess.abort_if_errors();
199 let triple = &sess.target.target.llvm_target;
202 let triple = CString::new(triple.as_bytes()).unwrap();
203 let cpu = match sess.opts.cg.target_cpu {
205 None => &*sess.target.target.options.cpu
207 let cpu = CString::new(cpu.as_bytes()).unwrap();
208 let features = CString::new(target_feature(sess).as_bytes()).unwrap();
209 llvm::LLVMRustCreateTargetMachine(
210 triple.as_ptr(), cpu.as_ptr(), features.as_ptr(),
222 llvm_err(sess.diagnostic(),
223 format!("Could not create LLVM TargetMachine for triple: {}",
224 triple).to_string());
231 /// Module-specific configuration for `optimize_and_codegen`.
233 pub struct ModuleConfig {
234 /// LLVM TargetMachine to use for codegen.
235 tm: TargetMachineRef,
236 /// Names of additional optimization passes to run.
238 /// Some(level) to optimize at a certain level, or None to run
239 /// absolutely no optimizations (used for the metadata module).
240 opt_level: Option<llvm::CodeGenOptLevel>,
242 /// Some(level) to optimize binary size, or None to not affect program size.
243 opt_size: Option<llvm::CodeGenOptSize>,
245 // Flags indicating which outputs to produce.
246 emit_no_opt_bc: bool,
252 // Miscellaneous flags. These are mostly copied from command-line
255 no_prepopulate_passes: bool,
258 vectorize_loop: bool,
260 merge_functions: bool,
261 inline_threshold: Option<usize>,
262 // Instead of creating an object file by doing LLVM codegen, just
263 // make the object file bitcode. Provides easy compatibility with
264 // emscripten's ecc compiler, when used as the linker.
265 obj_is_bitcode: bool,
268 unsafe impl Send for ModuleConfig { }
271 fn new(tm: TargetMachineRef, passes: Vec<String>) -> ModuleConfig {
278 emit_no_opt_bc: false,
284 obj_is_bitcode: false,
287 no_prepopulate_passes: false,
290 vectorize_loop: false,
291 vectorize_slp: false,
292 merge_functions: false,
293 inline_threshold: None
297 fn set_flags(&mut self, sess: &Session, trans: &CrateTranslation) {
298 self.no_verify = sess.no_verify();
299 self.no_prepopulate_passes = sess.opts.cg.no_prepopulate_passes;
300 self.no_builtins = trans.no_builtins;
301 self.time_passes = sess.time_passes();
302 self.inline_threshold = sess.opts.cg.inline_threshold;
303 self.obj_is_bitcode = sess.target.target.options.obj_is_bitcode;
305 // Copy what clang does by turning on loop vectorization at O2 and
306 // slp vectorization at O3. Otherwise configure other optimization aspects
307 // of this pass manager builder.
308 self.vectorize_loop = !sess.opts.cg.no_vectorize_loops &&
309 (sess.opts.optimize == config::OptLevel::Default ||
310 sess.opts.optimize == config::OptLevel::Aggressive);
311 self.vectorize_slp = !sess.opts.cg.no_vectorize_slp &&
312 sess.opts.optimize == config::OptLevel::Aggressive;
314 self.merge_functions = sess.opts.optimize == config::OptLevel::Default ||
315 sess.opts.optimize == config::OptLevel::Aggressive;
319 /// Additional resources used by optimize_and_codegen (not module specific)
320 struct CodegenContext<'a> {
321 // Extra resources used for LTO: (sess, reachable). This will be `None`
322 // when running in a worker thread.
323 lto_ctxt: Option<(&'a Session, &'a [String])>,
324 // Handler to use for diagnostics produced during codegen.
325 handler: &'a Handler,
326 // LLVM passes added by plugins.
327 plugin_passes: Vec<String>,
328 // LLVM optimizations for which we want to print remarks.
330 // Worker thread number
332 // Directory where incremental data is stored (if any)
333 incremental: Option<PathBuf>,
336 impl<'a> CodegenContext<'a> {
337 fn new_with_session(sess: &'a Session, reachable: &'a [String]) -> CodegenContext<'a> {
339 lto_ctxt: Some((sess, reachable)),
340 handler: sess.diagnostic(),
341 plugin_passes: sess.plugin_llvm_passes.borrow().clone(),
342 remark: sess.opts.cg.remark.clone(),
344 incremental: sess.opts.incremental.clone(),
349 struct HandlerFreeVars<'a> {
351 cgcx: &'a CodegenContext<'a>,
354 unsafe extern "C" fn report_inline_asm<'a, 'b>(cgcx: &'a CodegenContext<'a>,
357 use syntax_pos::ExpnId;
359 match cgcx.lto_ctxt {
361 sess.codemap().with_expn_info(ExpnId::from_u32(cookie), |info| match info {
362 Some(ei) => sess.span_err(ei.call_site, msg),
363 None => sess.err(msg),
368 cgcx.handler.struct_err(msg)
369 .note("build without -C codegen-units for more exact errors")
375 unsafe extern "C" fn inline_asm_handler(diag: SMDiagnosticRef,
378 let HandlerFreeVars { cgcx, .. } = *(user as *const HandlerFreeVars);
380 let msg = llvm::build_string(|s| llvm::LLVMRustWriteSMDiagnosticToString(diag, s))
381 .expect("non-UTF8 SMDiagnostic");
383 report_inline_asm(cgcx, &msg[..], cookie);
386 unsafe extern "C" fn diagnostic_handler(info: DiagnosticInfoRef, user: *mut c_void) {
387 let HandlerFreeVars { llcx, cgcx } = *(user as *const HandlerFreeVars);
389 match llvm::diagnostic::Diagnostic::unpack(info) {
390 llvm::diagnostic::InlineAsm(inline) => {
391 report_inline_asm(cgcx,
392 &llvm::twine_to_string(inline.message),
396 llvm::diagnostic::Optimization(opt) => {
397 let pass_name = str::from_utf8(CStr::from_ptr(opt.pass_name).to_bytes())
399 .expect("got a non-UTF8 pass name from LLVM");
400 let enabled = match cgcx.remark {
402 SomePasses(ref v) => v.iter().any(|s| *s == pass_name),
406 let loc = llvm::debug_loc_to_string(llcx, opt.debug_loc);
407 cgcx.handler.note_without_error(&format!("optimization {} for {} at {}: {}",
410 if loc.is_empty() { "[unknown]" } else { &*loc },
411 llvm::twine_to_string(opt.message)));
419 // Unsafe due to LLVM calls.
420 unsafe fn optimize_and_codegen(cgcx: &CodegenContext,
421 mtrans: ModuleTranslation,
423 config: ModuleConfig,
424 output_names: OutputFilenames) {
425 let llmod = mllvm.llmod;
426 let llcx = mllvm.llcx;
429 // llcx doesn't outlive this function, so we can put this on the stack.
430 let fv = HandlerFreeVars {
434 let fv = &fv as *const HandlerFreeVars as *mut c_void;
436 llvm::LLVMRustSetInlineAsmDiagnosticHandler(llcx, inline_asm_handler, fv);
437 llvm::LLVMContextSetDiagnosticHandler(llcx, diagnostic_handler, fv);
439 let module_name = Some(&mtrans.name[..]);
441 if config.emit_no_opt_bc {
442 let out = output_names.temp_path_ext("no-opt.bc", module_name);
443 let out = path2cstr(&out);
444 llvm::LLVMWriteBitcodeToFile(llmod, out.as_ptr());
447 if config.opt_level.is_some() {
448 // Create the two optimizing pass managers. These mirror what clang
449 // does, and are by populated by LLVM's default PassManagerBuilder.
450 // Each manager has a different set of passes, but they also share
451 // some common passes.
452 let fpm = llvm::LLVMCreateFunctionPassManagerForModule(llmod);
453 let mpm = llvm::LLVMCreatePassManager();
455 // If we're verifying or linting, add them to the function pass
457 let addpass = |pass_name: &str| {
458 let pass_name = CString::new(pass_name).unwrap();
459 let pass = llvm::LLVMRustFindAndCreatePass(pass_name.as_ptr());
463 let pass_manager = match llvm::LLVMRustPassKind(pass) {
464 llvm::PassKind::Function => fpm,
465 llvm::PassKind::Module => mpm,
466 llvm::PassKind::Other => {
467 cgcx.handler.err("Encountered LLVM pass kind we can't handle");
471 llvm::LLVMRustAddPass(pass_manager, pass);
475 if !config.no_verify { assert!(addpass("verify")); }
476 if !config.no_prepopulate_passes {
477 llvm::LLVMRustAddAnalysisPasses(tm, fpm, llmod);
478 llvm::LLVMRustAddAnalysisPasses(tm, mpm, llmod);
479 with_llvm_pmb(llmod, &config, &mut |b| {
480 llvm::LLVMPassManagerBuilderPopulateFunctionPassManager(b, fpm);
481 llvm::LLVMPassManagerBuilderPopulateModulePassManager(b, mpm);
485 for pass in &config.passes {
487 cgcx.handler.warn(&format!("unknown pass `{}`, ignoring",
492 for pass in &cgcx.plugin_passes {
494 cgcx.handler.err(&format!("a plugin asked for LLVM pass \
495 `{}` but LLVM does not \
496 recognize it", pass));
500 cgcx.handler.abort_if_errors();
502 // Finally, run the actual optimization passes
503 time(config.time_passes, &format!("llvm function passes [{}]", cgcx.worker), ||
504 llvm::LLVMRustRunFunctionPassManager(fpm, llmod));
505 time(config.time_passes, &format!("llvm module passes [{}]", cgcx.worker), ||
506 llvm::LLVMRunPassManager(mpm, llmod));
508 // Deallocate managers that we're now done with
509 llvm::LLVMDisposePassManager(fpm);
510 llvm::LLVMDisposePassManager(mpm);
512 match cgcx.lto_ctxt {
513 Some((sess, reachable)) if sess.lto() => {
514 time(sess.time_passes(), "all lto passes", || {
515 let temp_no_opt_bc_filename =
516 output_names.temp_path_ext("no-opt.lto.bc", module_name);
522 &temp_no_opt_bc_filename);
524 if config.emit_lto_bc {
525 let out = output_names.temp_path_ext("lto.bc", module_name);
526 let out = path2cstr(&out);
527 llvm::LLVMWriteBitcodeToFile(llmod, out.as_ptr());
534 // A codegen-specific pass manager is used to generate object
535 // files for an LLVM module.
537 // Apparently each of these pass managers is a one-shot kind of
538 // thing, so we create a new one for each type of output. The
539 // pass manager passed to the closure should be ensured to not
540 // escape the closure itself, and the manager should only be
542 unsafe fn with_codegen<F>(tm: TargetMachineRef,
546 F: FnOnce(PassManagerRef),
548 let cpm = llvm::LLVMCreatePassManager();
549 llvm::LLVMRustAddAnalysisPasses(tm, cpm, llmod);
550 llvm::LLVMRustAddLibraryInfo(cpm, llmod, no_builtins);
554 // Change what we write and cleanup based on whether obj files are
555 // just llvm bitcode. In that case write bitcode, and possibly
556 // delete the bitcode if it wasn't requested. Don't generate the
557 // machine code, instead copy the .o file from the .bc
558 let write_bc = config.emit_bc || config.obj_is_bitcode;
559 let rm_bc = !config.emit_bc && config.obj_is_bitcode;
560 let write_obj = config.emit_obj && !config.obj_is_bitcode;
561 let copy_bc_to_obj = config.emit_obj && config.obj_is_bitcode;
563 let bc_out = output_names.temp_path(OutputType::Bitcode, module_name);
564 let obj_out = output_names.temp_path(OutputType::Object, module_name);
567 let bc_out_c = path2cstr(&bc_out);
568 llvm::LLVMWriteBitcodeToFile(llmod, bc_out_c.as_ptr());
571 time(config.time_passes, &format!("codegen passes [{}]", cgcx.worker), || {
573 let out = output_names.temp_path(OutputType::LlvmAssembly, module_name);
574 let out = path2cstr(&out);
575 with_codegen(tm, llmod, config.no_builtins, |cpm| {
576 llvm::LLVMRustPrintModule(cpm, llmod, out.as_ptr());
577 llvm::LLVMDisposePassManager(cpm);
582 let path = output_names.temp_path(OutputType::Assembly, module_name);
584 // We can't use the same module for asm and binary output, because that triggers
585 // various errors like invalid IR or broken binaries, so we might have to clone the
586 // module to produce the asm output
587 let llmod = if config.emit_obj {
588 llvm::LLVMCloneModule(llmod)
592 with_codegen(tm, llmod, config.no_builtins, |cpm| {
593 write_output_file(cgcx.handler, tm, cpm, llmod, &path,
594 llvm::FileType::AssemblyFile);
597 llvm::LLVMDisposeModule(llmod);
602 with_codegen(tm, llmod, config.no_builtins, |cpm| {
603 write_output_file(cgcx.handler, tm, cpm, llmod, &obj_out,
604 llvm::FileType::ObjectFile);
610 debug!("copying bitcode {:?} to obj {:?}", bc_out, obj_out);
611 if let Err(e) = link_or_copy(&bc_out, &obj_out) {
612 cgcx.handler.err(&format!("failed to copy bitcode to object file: {}", e));
617 debug!("removing_bitcode {:?}", bc_out);
618 if let Err(e) = fs::remove_file(&bc_out) {
619 cgcx.handler.err(&format!("failed to remove bitcode: {}", e));
623 llvm::LLVMRustDisposeTargetMachine(tm);
627 pub fn cleanup_llvm(trans: &CrateTranslation) {
628 for module in trans.modules.iter() {
630 match module.source {
631 ModuleSource::Translated(llvm) => {
632 llvm::LLVMDisposeModule(llvm.llmod);
633 llvm::LLVMContextDispose(llvm.llcx);
635 ModuleSource::Preexisting(_) => {
642 pub fn run_passes(sess: &Session,
643 trans: &CrateTranslation,
644 output_types: &HashMap<OutputType, Option<PathBuf>>,
645 crate_output: &OutputFilenames) {
646 // It's possible that we have `codegen_units > 1` but only one item in
647 // `trans.modules`. We could theoretically proceed and do LTO in that
648 // case, but it would be confusing to have the validity of
649 // `-Z lto -C codegen-units=2` depend on details of the crate being
650 // compiled, so we complain regardless.
651 if sess.lto() && sess.opts.cg.codegen_units > 1 {
652 // This case is impossible to handle because LTO expects to be able
653 // to combine the entire crate and all its dependencies into a
654 // single compilation unit, but each codegen unit is in a separate
655 // LLVM context, so they can't easily be combined.
656 sess.fatal("can't perform LTO when using multiple codegen units");
660 assert!(trans.modules.len() == sess.opts.cg.codegen_units ||
661 sess.opts.debugging_opts.incremental.is_some());
663 let tm = create_target_machine(sess);
665 // Figure out what we actually need to build.
667 let mut modules_config = ModuleConfig::new(tm, sess.opts.cg.passes.clone());
668 let mut metadata_config = ModuleConfig::new(tm, vec!());
670 modules_config.opt_level = Some(get_llvm_opt_level(sess.opts.optimize));
671 modules_config.opt_size = Some(get_llvm_opt_size(sess.opts.optimize));
673 // Save all versions of the bytecode if we're saving our temporaries.
674 if sess.opts.cg.save_temps {
675 modules_config.emit_no_opt_bc = true;
676 modules_config.emit_bc = true;
677 modules_config.emit_lto_bc = true;
678 metadata_config.emit_bc = true;
681 // Emit bitcode files for the crate if we're emitting an rlib.
682 // Whenever an rlib is created, the bitcode is inserted into the
683 // archive in order to allow LTO against it.
684 let needs_crate_bitcode =
685 sess.crate_types.borrow().contains(&config::CrateTypeRlib) &&
686 sess.opts.output_types.contains_key(&OutputType::Exe);
687 let needs_crate_object =
688 sess.opts.output_types.contains_key(&OutputType::Exe);
689 if needs_crate_bitcode {
690 modules_config.emit_bc = true;
693 for output_type in output_types.keys() {
695 OutputType::Bitcode => { modules_config.emit_bc = true; },
696 OutputType::LlvmAssembly => { modules_config.emit_ir = true; },
697 OutputType::Assembly => {
698 modules_config.emit_asm = true;
699 // If we're not using the LLVM assembler, this function
700 // could be invoked specially with output_type_assembly, so
701 // in this case we still want the metadata object file.
702 if !sess.opts.output_types.contains_key(&OutputType::Assembly) {
703 metadata_config.emit_obj = true;
706 OutputType::Object => { modules_config.emit_obj = true; },
708 modules_config.emit_obj = true;
709 metadata_config.emit_obj = true;
711 OutputType::DepInfo => {}
715 modules_config.set_flags(sess, trans);
716 metadata_config.set_flags(sess, trans);
719 // Populate a buffer with a list of codegen threads. Items are processed in
720 // LIFO order, just because it's a tiny bit simpler that way. (The order
721 // doesn't actually matter.)
722 let mut work_items = Vec::with_capacity(1 + trans.modules.len());
725 let work = build_work_item(sess,
726 trans.metadata_module.clone(),
727 metadata_config.clone(),
728 crate_output.clone());
729 work_items.push(work);
732 for mtrans in trans.modules.iter() {
733 let work = build_work_item(sess,
735 modules_config.clone(),
736 crate_output.clone());
737 work_items.push(work);
740 // Process the work items, optionally using worker threads.
741 // NOTE: This code is not really adapted to incremental compilation where
742 // the compiler decides the number of codegen units (and will
743 // potentially create hundreds of them).
744 let num_workers = work_items.len() - 1;
745 if num_workers == 1 {
746 run_work_singlethreaded(sess, &trans.reachable, work_items);
748 run_work_multithreaded(sess, work_items, num_workers);
751 // If in incr. comp. mode, preserve the `.o` files for potential re-use
752 for mtrans in trans.modules.iter() {
753 let mut files = vec![];
755 if modules_config.emit_obj {
756 let path = crate_output.temp_path(OutputType::Object, Some(&mtrans.name));
757 files.push((OutputType::Object, path));
760 if modules_config.emit_bc {
761 let path = crate_output.temp_path(OutputType::Bitcode, Some(&mtrans.name));
762 files.push((OutputType::Bitcode, path));
765 save_trans_partition(sess, &mtrans.name, mtrans.symbol_name_hash, &files);
768 // All codegen is finished.
770 llvm::LLVMRustDisposeTargetMachine(tm);
773 // Produce final compile outputs.
774 let copy_gracefully = |from: &Path, to: &Path| {
775 if let Err(e) = fs::copy(from, to) {
776 sess.err(&format!("could not copy {:?} to {:?}: {}", from, to, e));
780 let copy_if_one_unit = |output_type: OutputType,
781 keep_numbered: bool| {
782 if trans.modules.len() == 1 {
783 // 1) Only one codegen unit. In this case it's no difficulty
784 // to copy `foo.0.x` to `foo.x`.
785 let module_name = Some(&(trans.modules[0].name)[..]);
786 let path = crate_output.temp_path(output_type, module_name);
787 copy_gracefully(&path,
788 &crate_output.path(output_type));
789 if !sess.opts.cg.save_temps && !keep_numbered {
790 // The user just wants `foo.x`, not `foo.#module-name#.x`.
794 let ext = crate_output.temp_path(output_type, None)
801 if crate_output.outputs.contains_key(&output_type) {
802 // 2) Multiple codegen units, with `--emit foo=some_name`. We have
803 // no good solution for this case, so warn the user.
804 sess.warn(&format!("ignoring emit path because multiple .{} files \
805 were produced", ext));
806 } else if crate_output.single_output_file.is_some() {
807 // 3) Multiple codegen units, with `-o some_name`. We have
808 // no good solution for this case, so warn the user.
809 sess.warn(&format!("ignoring -o because multiple .{} files \
810 were produced", ext));
812 // 4) Multiple codegen units, but no explicit name. We
813 // just leave the `foo.0.x` files in place.
814 // (We don't have to do any work in this case.)
819 // Flag to indicate whether the user explicitly requested bitcode.
820 // Otherwise, we produced it only as a temporary output, and will need
822 let mut user_wants_bitcode = false;
823 let mut user_wants_objects = false;
824 for output_type in output_types.keys() {
826 OutputType::Bitcode => {
827 user_wants_bitcode = true;
828 // Copy to .bc, but always keep the .0.bc. There is a later
829 // check to figure out if we should delete .0.bc files, or keep
830 // them for making an rlib.
831 copy_if_one_unit(OutputType::Bitcode, true);
833 OutputType::LlvmAssembly => {
834 copy_if_one_unit(OutputType::LlvmAssembly, false);
836 OutputType::Assembly => {
837 copy_if_one_unit(OutputType::Assembly, false);
839 OutputType::Object => {
840 user_wants_objects = true;
841 copy_if_one_unit(OutputType::Object, true);
844 OutputType::DepInfo => {}
847 let user_wants_bitcode = user_wants_bitcode;
849 // Clean up unwanted temporary files.
851 // We create the following files by default:
852 // - crate.#module-name#.bc
853 // - crate.#module-name#.o
854 // - crate.metadata.bc
855 // - crate.metadata.o
856 // - crate.o (linked from crate.##.o)
857 // - crate.bc (copied from crate.##.bc)
858 // We may create additional files if requested by the user (through
859 // `-C save-temps` or `--emit=` flags).
861 if !sess.opts.cg.save_temps {
862 // Remove the temporary .#module-name#.o objects. If the user didn't
863 // explicitly request bitcode (with --emit=bc), and the bitcode is not
864 // needed for building an rlib, then we must remove .#module-name#.bc as
867 // Specific rules for keeping .#module-name#.bc:
868 // - If we're building an rlib (`needs_crate_bitcode`), then keep
870 // - If the user requested bitcode (`user_wants_bitcode`), and
871 // codegen_units > 1, then keep it.
872 // - If the user requested bitcode but codegen_units == 1, then we
873 // can toss .#module-name#.bc because we copied it to .bc earlier.
874 // - If we're not building an rlib and the user didn't request
875 // bitcode, then delete .#module-name#.bc.
876 // If you change how this works, also update back::link::link_rlib,
877 // where .#module-name#.bc files are (maybe) deleted after making an
879 let keep_numbered_bitcode = needs_crate_bitcode ||
880 (user_wants_bitcode && sess.opts.cg.codegen_units > 1);
882 let keep_numbered_objects = needs_crate_object ||
883 (user_wants_objects && sess.opts.cg.codegen_units > 1);
885 for module_name in trans.modules.iter().map(|m| Some(&m.name[..])) {
886 if modules_config.emit_obj && !keep_numbered_objects {
887 let path = crate_output.temp_path(OutputType::Object, module_name);
891 if modules_config.emit_bc && !keep_numbered_bitcode {
892 let path = crate_output.temp_path(OutputType::Bitcode, module_name);
897 if metadata_config.emit_bc && !user_wants_bitcode {
898 let path = crate_output.temp_path(OutputType::Bitcode,
899 Some(&trans.metadata_module.name[..]));
904 // We leave the following files around by default:
906 // - crate.metadata.o
908 // These are used in linking steps and will be cleaned up afterward.
910 // FIXME: time_llvm_passes support - does this use a global context or
912 if sess.opts.cg.codegen_units == 1 && sess.time_llvm_passes() {
913 unsafe { llvm::LLVMRustPrintPassTimings(); }
918 mtrans: ModuleTranslation,
919 config: ModuleConfig,
920 output_names: OutputFilenames
923 fn build_work_item(sess: &Session,
924 mtrans: ModuleTranslation,
925 config: ModuleConfig,
926 output_names: OutputFilenames)
929 let mut config = config;
930 config.tm = create_target_machine(sess);
934 output_names: output_names
938 fn execute_work_item(cgcx: &CodegenContext,
939 work_item: WorkItem) {
941 match work_item.mtrans.source {
942 ModuleSource::Translated(mllvm) => {
943 debug!("llvm-optimizing {:?}", work_item.mtrans.name);
944 optimize_and_codegen(cgcx,
948 work_item.output_names);
950 ModuleSource::Preexisting(wp) => {
951 let incremental = cgcx.incremental.as_ref().unwrap();
952 let name = &work_item.mtrans.name;
953 for (kind, saved_file) in wp.saved_files {
954 let obj_out = work_item.output_names.temp_path(kind, Some(name));
955 let source_file = incremental.join(&saved_file);
956 debug!("copying pre-existing module `{}` from {:?} to {}",
957 work_item.mtrans.name,
960 match link_or_copy(&source_file, &obj_out) {
963 cgcx.handler.err(&format!("unable to copy {} to {}: {}",
964 source_file.display(),
975 fn run_work_singlethreaded(sess: &Session,
976 reachable: &[String],
977 work_items: Vec<WorkItem>) {
978 let cgcx = CodegenContext::new_with_session(sess, reachable);
980 // Since we're running single-threaded, we can pass the session to
981 // the proc, allowing `optimize_and_codegen` to perform LTO.
982 for work in work_items.into_iter().rev() {
983 execute_work_item(&cgcx, work);
987 fn run_work_multithreaded(sess: &Session,
988 work_items: Vec<WorkItem>,
989 num_workers: usize) {
990 assert!(num_workers > 0);
992 // Run some workers to process the work items.
993 let work_items_arc = Arc::new(Mutex::new(work_items));
994 let mut diag_emitter = SharedEmitter::new();
995 let mut futures = Vec::with_capacity(num_workers);
997 for i in 0..num_workers {
998 let work_items_arc = work_items_arc.clone();
999 let diag_emitter = diag_emitter.clone();
1000 let plugin_passes = sess.plugin_llvm_passes.borrow().clone();
1001 let remark = sess.opts.cg.remark.clone();
1003 let (tx, rx) = channel();
1004 let mut tx = Some(tx);
1007 let incremental = sess.opts.incremental.clone();
1009 thread::Builder::new().name(format!("codegen-{}", i)).spawn(move || {
1010 let diag_handler = Handler::with_emitter(true, false, box diag_emitter);
1012 // Must construct cgcx inside the proc because it has non-Send
1014 let cgcx = CodegenContext {
1016 handler: &diag_handler,
1017 plugin_passes: plugin_passes,
1020 incremental: incremental,
1024 // Avoid holding the lock for the entire duration of the match.
1025 let maybe_work = work_items_arc.lock().unwrap().pop();
1028 execute_work_item(&cgcx, work);
1030 // Make sure to fail the worker so the main thread can
1031 // tell that there were errors.
1032 cgcx.handler.abort_if_errors();
1038 tx.take().unwrap().send(()).unwrap();
1042 let mut panicked = false;
1050 // Display any new diagnostics.
1051 diag_emitter.dump(sess.diagnostic());
1054 sess.fatal("aborting due to worker thread panic");
1058 pub fn run_assembler(sess: &Session, outputs: &OutputFilenames) {
1059 let (pname, mut cmd, _) = get_linker(sess);
1061 cmd.arg("-c").arg("-o").arg(&outputs.path(OutputType::Object))
1062 .arg(&outputs.temp_path(OutputType::Assembly, None));
1063 debug!("{:?}", cmd);
1065 match cmd.output() {
1067 if !prog.status.success() {
1068 let mut note = prog.stderr.clone();
1069 note.extend_from_slice(&prog.stdout);
1071 sess.struct_err(&format!("linking with `{}` failed: {}",
1074 .note(&format!("{:?}", &cmd))
1075 .note(str::from_utf8(¬e[..]).unwrap())
1077 sess.abort_if_errors();
1081 sess.err(&format!("could not exec the linker `{}`: {}", pname, e));
1082 sess.abort_if_errors();
1087 pub unsafe fn with_llvm_pmb(llmod: ModuleRef,
1088 config: &ModuleConfig,
1089 f: &mut FnMut(llvm::PassManagerBuilderRef)) {
1090 // Create the PassManagerBuilder for LLVM. We configure it with
1091 // reasonable defaults and prepare it to actually populate the pass
1093 let builder = llvm::LLVMPassManagerBuilderCreate();
1094 let opt_level = config.opt_level.unwrap_or(llvm::CodeGenOptLevel::None);
1095 let opt_size = config.opt_size.unwrap_or(llvm::CodeGenOptSizeNone);
1096 let inline_threshold = config.inline_threshold;
1098 llvm::LLVMRustConfigurePassManagerBuilder(builder, opt_level,
1099 config.merge_functions,
1100 config.vectorize_slp,
1101 config.vectorize_loop);
1102 llvm::LLVMPassManagerBuilderSetSizeLevel(builder, opt_size as u32);
1104 if opt_size != llvm::CodeGenOptSizeNone {
1105 llvm::LLVMPassManagerBuilderSetDisableUnrollLoops(builder, 1);
1108 llvm::LLVMRustAddBuilderLibraryInfo(builder, llmod, config.no_builtins);
1110 // Here we match what clang does (kinda). For O0 we only inline
1111 // always-inline functions (but don't add lifetime intrinsics), at O1 we
1112 // inline with lifetime intrinsics, and O2+ we add an inliner with a
1113 // thresholds copied from clang.
1114 match (opt_level, opt_size, inline_threshold) {
1115 (_, _, Some(t)) => {
1116 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, t as u32);
1118 (llvm::CodeGenOptLevel::Aggressive, _, _) => {
1119 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 275);
1121 (_, llvm::CodeGenOptSizeDefault, _) => {
1122 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 75);
1124 (_, llvm::CodeGenOptSizeAggressive, _) => {
1125 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 25);
1127 (llvm::CodeGenOptLevel::None, _, _) => {
1128 llvm::LLVMRustAddAlwaysInlinePass(builder, false);
1130 (llvm::CodeGenOptLevel::Less, _, _) => {
1131 llvm::LLVMRustAddAlwaysInlinePass(builder, true);
1133 (llvm::CodeGenOptLevel::Default, _, _) => {
1134 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 225);
1136 (llvm::CodeGenOptLevel::Other, _, _) => {
1137 bug!("CodeGenOptLevel::Other selected")
1142 llvm::LLVMPassManagerBuilderDispose(builder);