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 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;
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};
30 use std::ffi::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); 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),
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),
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)),
64 pub fn write_output_file(
65 handler: &errors::Handler,
66 target: llvm::TargetMachineRef,
67 pm: llvm::PassManagerRef,
70 file_type: llvm::FileType) {
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()));
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).
92 struct SharedEmitter {
93 buffer: Arc<Mutex<Vec<Diagnostic>>>,
97 fn new() -> SharedEmitter {
99 buffer: Arc::new(Mutex::new(Vec::new())),
103 fn dump(&mut self, handler: &Handler) {
104 let mut buffer = self.buffer.lock().unwrap();
105 for diag in &*buffer {
108 handler.emit_with_code(&MultiSpan::new(),
114 handler.emit(&MultiSpan::new(),
124 impl Emitter for SharedEmitter {
125 fn emit(&mut self, db: &DiagnosticBuilder) {
126 self.buffer.lock().unwrap().push(Diagnostic {
128 code: db.code.clone(),
131 for child in &db.children {
132 self.buffer.lock().unwrap().push(Diagnostic {
133 msg: child.message(),
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.
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 = [
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))
162 sess.target.target.options.features,
163 llvm_features.collect::<Vec<_>>().join(","))
166 fn get_llvm_opt_level(optimize: config::OptLevel) -> llvm::CodeGenOptLevel {
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,
176 fn get_llvm_opt_size(optimize: config::OptLevel) -> llvm::CodeGenOptSize {
178 config::OptLevel::Size => llvm::CodeGenOptSizeDefault,
179 config::OptLevel::SizeMin => llvm::CodeGenOptSizeAggressive,
180 _ => llvm::CodeGenOptSizeNone,
184 pub fn create_target_machine(sess: &Session) -> TargetMachineRef {
185 let reloc_model = get_reloc_model(sess);
187 let opt_level = get_llvm_opt_level(sess.opts.optimize);
188 let use_softfp = sess.opts.cg.soft_float;
190 let ffunction_sections = sess.target.target.options.function_sections;
191 let fdata_sections = ffunction_sections;
193 let code_model_arg = match sess.opts.cg.code_model {
195 None => &sess.target.target.options.code_model,
198 let code_model = match CODE_GEN_MODEL_ARGS.iter().find(
199 |&&arg| arg.0 == code_model_arg) {
202 sess.err(&format!("{:?} is not a valid code model",
206 sess.abort_if_errors();
211 let triple = &sess.target.target.llvm_target;
214 let triple = CString::new(triple.as_bytes()).unwrap();
215 let cpu = match sess.opts.cg.target_cpu {
217 None => &*sess.target.target.options.cpu
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(),
234 llvm_err(sess.diagnostic(),
235 format!("Could not create LLVM TargetMachine for triple: {}",
236 triple).to_string());
243 /// Module-specific configuration for `optimize_and_codegen`.
245 pub struct ModuleConfig {
246 /// LLVM TargetMachine to use for codegen.
247 tm: TargetMachineRef,
248 /// Names of additional optimization passes to run.
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>,
254 /// Some(level) to optimize binary size, or None to not affect program size.
255 opt_size: Option<llvm::CodeGenOptSize>,
257 // Flags indicating which outputs to produce.
258 emit_no_opt_bc: bool,
264 // Miscellaneous flags. These are mostly copied from command-line
267 no_prepopulate_passes: bool,
270 vectorize_loop: 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,
280 unsafe impl Send for ModuleConfig { }
283 fn new(tm: TargetMachineRef, passes: Vec<String>) -> ModuleConfig {
290 emit_no_opt_bc: false,
296 obj_is_bitcode: false,
299 no_prepopulate_passes: false,
302 vectorize_loop: false,
303 vectorize_slp: false,
304 merge_functions: false,
305 inline_threshold: None
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;
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;
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;
330 self.merge_functions = sess.opts.optimize == config::OptLevel::Default ||
331 sess.opts.optimize == config::OptLevel::Aggressive;
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.
346 // Worker thread number
348 // The incremental compilation session directory, or None if we are not
349 // compiling incrementally
350 incr_comp_session_dir: Option<PathBuf>
353 impl<'a> CodegenContext<'a> {
354 fn new_with_session(sess: &'a Session,
355 exported_symbols: &'a ExportedSymbols)
356 -> CodegenContext<'a> {
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(),
363 incr_comp_session_dir: sess.incr_comp_session_dir_opt().map(|r| r.clone())
368 struct HandlerFreeVars<'a> {
370 cgcx: &'a CodegenContext<'a>,
373 unsafe extern "C" fn report_inline_asm<'a, 'b>(cgcx: &'a CodegenContext<'a>,
376 use syntax::ext::hygiene::Mark;
378 match cgcx.lto_ctxt {
380 match Mark::from_u32(cookie).expn_info() {
381 Some(ei) => sess.span_err(ei.call_site, msg),
382 None => sess.err(msg),
387 cgcx.handler.struct_err(msg)
388 .note("build without -C codegen-units for more exact errors")
394 unsafe extern "C" fn inline_asm_handler(diag: SMDiagnosticRef,
397 let HandlerFreeVars { cgcx, .. } = *(user as *const HandlerFreeVars);
399 let msg = llvm::build_string(|s| llvm::LLVMRustWriteSMDiagnosticToString(diag, s))
400 .expect("non-UTF8 SMDiagnostic");
402 report_inline_asm(cgcx, &msg, cookie);
405 unsafe extern "C" fn diagnostic_handler(info: DiagnosticInfoRef, user: *mut c_void) {
406 let HandlerFreeVars { llcx, cgcx } = *(user as *const HandlerFreeVars);
408 match llvm::diagnostic::Diagnostic::unpack(info) {
409 llvm::diagnostic::InlineAsm(inline) => {
410 report_inline_asm(cgcx,
411 &llvm::twine_to_string(inline.message),
415 llvm::diagnostic::Optimization(opt) => {
416 let enabled = match cgcx.remark {
418 SomePasses(ref v) => v.iter().any(|s| *s == opt.pass_name),
422 let loc = llvm::debug_loc_to_string(llcx, opt.debug_loc);
423 cgcx.handler.note_without_error(&format!("optimization {} for {} at {}: {}",
426 if loc.is_empty() { "[unknown]" } else { &*loc },
435 // Unsafe due to LLVM calls.
436 unsafe fn optimize_and_codegen(cgcx: &CodegenContext,
437 mtrans: ModuleTranslation,
439 config: ModuleConfig,
440 output_names: OutputFilenames) {
441 let llmod = mllvm.llmod;
442 let llcx = mllvm.llcx;
445 // llcx doesn't outlive this function, so we can put this on the stack.
446 let fv = HandlerFreeVars {
450 let fv = &fv as *const HandlerFreeVars as *mut c_void;
452 llvm::LLVMRustSetInlineAsmDiagnosticHandler(llcx, inline_asm_handler, fv);
453 llvm::LLVMContextSetDiagnosticHandler(llcx, diagnostic_handler, fv);
455 let module_name = Some(&mtrans.name[..]);
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());
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();
471 // If we're verifying or linting, add them to the function pass
473 let addpass = |pass_name: &str| {
474 let pass_name = CString::new(pass_name).unwrap();
475 let pass = llvm::LLVMRustFindAndCreatePass(pass_name.as_ptr());
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");
487 llvm::LLVMRustAddPass(pass_manager, pass);
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);
501 for pass in &config.passes {
503 cgcx.handler.warn(&format!("unknown pass `{}`, ignoring",
508 for pass in &cgcx.plugin_passes {
510 cgcx.handler.err(&format!("a plugin asked for LLVM pass \
511 `{}` but LLVM does not \
512 recognize it", pass));
516 cgcx.handler.abort_if_errors();
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));
524 // Deallocate managers that we're now done with
525 llvm::LLVMDisposePassManager(fpm);
526 llvm::LLVMDisposePassManager(mpm);
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);
538 &temp_no_opt_bc_filename);
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());
550 // A codegen-specific pass manager is used to generate object
551 // files for an LLVM module.
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
558 unsafe fn with_codegen<F>(tm: TargetMachineRef,
562 F: FnOnce(PassManagerRef),
564 let cpm = llvm::LLVMCreatePassManager();
565 llvm::LLVMRustAddAnalysisPasses(tm, cpm, llmod);
566 llvm::LLVMRustAddLibraryInfo(cpm, llmod, no_builtins);
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;
579 let bc_out = output_names.temp_path(OutputType::Bitcode, module_name);
580 let obj_out = output_names.temp_path(OutputType::Object, module_name);
583 let bc_out_c = path2cstr(&bc_out);
584 llvm::LLVMWriteBitcodeToFile(llmod, bc_out_c.as_ptr());
587 time(config.time_passes, &format!("codegen passes [{}]", cgcx.worker), || {
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);
598 let path = output_names.temp_path(OutputType::Assembly, module_name);
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)
608 with_codegen(tm, llmod, config.no_builtins, |cpm| {
609 write_output_file(cgcx.handler, tm, cpm, llmod, &path,
610 llvm::FileType::AssemblyFile);
613 llvm::LLVMDisposeModule(llmod);
618 with_codegen(tm, llmod, config.no_builtins, |cpm| {
619 write_output_file(cgcx.handler, tm, cpm, llmod, &obj_out,
620 llvm::FileType::ObjectFile);
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));
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));
639 llvm::LLVMRustDisposeTargetMachine(tm);
643 pub fn cleanup_llvm(trans: &CrateTranslation) {
644 for module in trans.modules.iter() {
646 match module.source {
647 ModuleSource::Translated(llvm) => {
648 llvm::LLVMDisposeModule(llvm.llmod);
649 llvm::LLVMContextDispose(llvm.llcx);
651 ModuleSource::Preexisting(_) => {
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");
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);
681 let tm = create_target_machine(sess);
683 // Figure out what we actually need to build.
685 let mut modules_config = ModuleConfig::new(tm, sess.opts.cg.passes.clone());
686 let mut metadata_config = ModuleConfig::new(tm, vec![]);
688 if let Some(ref sanitizer) = sess.opts.debugging_opts.sanitizer {
690 Sanitizer::Address => {
691 modules_config.passes.push("asan".to_owned());
692 modules_config.passes.push("asan-module".to_owned());
694 Sanitizer::Memory => {
695 modules_config.passes.push("msan".to_owned())
697 Sanitizer::Thread => {
698 modules_config.passes.push("tsan".to_owned())
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));
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;
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;
727 for output_type in output_types.keys() {
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;
740 OutputType::Object => { modules_config.emit_obj = true; }
741 OutputType::Metadata => { metadata_config.emit_obj = true; }
743 modules_config.emit_obj = true;
744 metadata_config.emit_obj = true;
746 OutputType::Mir => {}
747 OutputType::DepInfo => {}
751 modules_config.set_flags(sess, trans);
752 metadata_config.set_flags(sess, trans);
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());
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);
768 for mtrans in trans.modules.iter() {
769 let work = build_work_item(sess,
771 modules_config.clone(),
772 crate_output.clone());
773 work_items.push(work);
776 if sess.opts.debugging_opts.incremental_info {
777 dump_incremental_data(&trans);
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);
791 run_work_multithreaded(sess, work_items, num_workers);
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![];
798 if modules_config.emit_obj {
799 let path = crate_output.temp_path(OutputType::Object, Some(&mtrans.name));
800 files.push((OutputType::Object, path));
803 if modules_config.emit_bc {
804 let path = crate_output.temp_path(OutputType::Bitcode, Some(&mtrans.name));
805 files.push((OutputType::Bitcode, path));
808 save_trans_partition(sess, &mtrans.name, mtrans.symbol_name_hash, &files);
811 // All codegen is finished.
813 llvm::LLVMRustDisposeTargetMachine(tm);
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));
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`.
837 let ext = crate_output.temp_path(output_type, None)
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));
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.)
862 // Flag to indicate whether the user explicitly requested bitcode.
863 // Otherwise, we produced it only as a temporary output, and will need
865 let mut user_wants_bitcode = false;
866 let mut user_wants_objects = false;
867 for output_type in output_types.keys() {
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);
876 OutputType::LlvmAssembly => {
877 copy_if_one_unit(OutputType::LlvmAssembly, false);
879 OutputType::Assembly => {
880 copy_if_one_unit(OutputType::Assembly, false);
882 OutputType::Object => {
883 user_wants_objects = true;
884 copy_if_one_unit(OutputType::Object, true);
887 OutputType::Metadata |
889 OutputType::DepInfo => {}
892 let user_wants_bitcode = user_wants_bitcode;
894 // Clean up unwanted temporary files.
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).
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
912 // Specific rules for keeping .#module-name#.bc:
913 // - If we're building an rlib (`needs_crate_bitcode`), then keep
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
924 let keep_numbered_bitcode = needs_crate_bitcode ||
925 (user_wants_bitcode && sess.opts.cg.codegen_units > 1);
927 let keep_numbered_objects = needs_crate_object ||
928 (user_wants_objects && sess.opts.cg.codegen_units > 1);
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);
936 if modules_config.emit_bc && !keep_numbered_bitcode {
937 let path = crate_output.temp_path(OutputType::Bitcode, module_name);
942 if metadata_config.emit_bc && !user_wants_bitcode {
943 let path = crate_output.temp_path(OutputType::Bitcode,
944 Some(&trans.metadata_module.name));
949 // We leave the following files around by default:
951 // - #crate#.crate.metadata.o
953 // These are used in linking steps and will be cleaned up afterward.
955 // FIXME: time_llvm_passes support - does this use a global context or
957 if sess.opts.cg.codegen_units == 1 && sess.time_llvm_passes() {
958 unsafe { llvm::LLVMRustPrintPassTimings(); }
962 fn dump_incremental_data(trans: &CrateTranslation) {
964 for mtrans in trans.modules.iter() {
965 match mtrans.source {
966 ModuleSource::Preexisting(..) => reuse += 1,
967 ModuleSource::Translated(..) => (),
970 println!("incremental: re-using {} out of {} modules", reuse, trans.modules.len());
974 mtrans: ModuleTranslation,
975 config: ModuleConfig,
976 output_names: OutputFilenames
979 fn build_work_item(sess: &Session,
980 mtrans: ModuleTranslation,
981 config: ModuleConfig,
982 output_names: OutputFilenames)
985 let mut config = config;
986 config.tm = create_target_machine(sess);
990 output_names: output_names
994 fn execute_work_item(cgcx: &CodegenContext,
995 work_item: WorkItem) {
997 match work_item.mtrans.source {
998 ModuleSource::Translated(mllvm) => {
999 debug!("llvm-optimizing {:?}", work_item.mtrans.name);
1000 optimize_and_codegen(cgcx,
1004 work_item.output_names);
1006 ModuleSource::Preexisting(wp) => {
1007 let incr_comp_session_dir = cgcx.incr_comp_session_dir
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,
1015 debug!("copying pre-existing module `{}` from {:?} to {}",
1016 work_item.mtrans.name,
1019 match link_or_copy(&source_file, &obj_out) {
1022 cgcx.handler.err(&format!("unable to copy {} to {}: {}",
1023 source_file.display(),
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);
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);
1046 fn run_work_multithreaded(sess: &Session,
1047 work_items: Vec<WorkItem>,
1048 num_workers: usize) {
1049 assert!(num_workers > 0);
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);
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();
1062 let (tx, rx) = channel();
1063 let mut tx = Some(tx);
1066 let incr_comp_session_dir = sess.incr_comp_session_dir_opt().map(|r| r.clone());
1068 let depth = time_depth();
1069 thread::Builder::new().name(format!("codegen-{}", i)).spawn(move || {
1070 set_time_depth(depth);
1072 let diag_handler = Handler::with_emitter(true, false, box diag_emitter);
1074 // Must construct cgcx inside the proc because it has non-Send
1076 let cgcx = CodegenContext {
1078 handler: &diag_handler,
1079 plugin_passes: plugin_passes,
1082 incr_comp_session_dir: incr_comp_session_dir
1086 // Avoid holding the lock for the entire duration of the match.
1087 let maybe_work = work_items_arc.lock().unwrap().pop();
1090 execute_work_item(&cgcx, work);
1092 // Make sure to fail the worker so the main thread can
1093 // tell that there were errors.
1094 cgcx.handler.abort_if_errors();
1100 tx.take().unwrap().send(()).unwrap();
1104 let mut panicked = false;
1112 // Display any new diagnostics.
1113 diag_emitter.dump(sess.diagnostic());
1116 sess.fatal("aborting due to worker thread panic");
1120 pub fn run_assembler(sess: &Session, outputs: &OutputFilenames) {
1121 let (pname, mut cmd, _) = get_linker(sess);
1123 for arg in &sess.target.target.options.asm_args {
1127 cmd.arg("-c").arg("-o").arg(&outputs.path(OutputType::Object))
1128 .arg(&outputs.temp_path(OutputType::Assembly, None));
1129 debug!("{:?}", cmd);
1131 match cmd.output() {
1133 if !prog.status.success() {
1134 let mut note = prog.stderr.clone();
1135 note.extend_from_slice(&prog.stdout);
1137 sess.struct_err(&format!("linking with `{}` failed: {}",
1140 .note(&format!("{:?}", &cmd))
1141 .note(str::from_utf8(¬e[..]).unwrap())
1143 sess.abort_if_errors();
1147 sess.err(&format!("could not exec the linker `{}`: {}", pname, e));
1148 sess.abort_if_errors();
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
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;
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);
1170 if opt_size != llvm::CodeGenOptSizeNone {
1171 llvm::LLVMPassManagerBuilderSetDisableUnrollLoops(builder, 1);
1174 llvm::LLVMRustAddBuilderLibraryInfo(builder, llmod, config.no_builtins);
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) {
1182 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, t as u32);
1184 (llvm::CodeGenOptLevel::Aggressive, ..) => {
1185 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 275);
1187 (_, llvm::CodeGenOptSizeDefault, _) => {
1188 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 75);
1190 (_, llvm::CodeGenOptSizeAggressive, _) => {
1191 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 25);
1193 (llvm::CodeGenOptLevel::None, ..) => {
1194 llvm::LLVMRustAddAlwaysInlinePass(builder, false);
1196 (llvm::CodeGenOptLevel::Less, ..) => {
1197 llvm::LLVMRustAddAlwaysInlinePass(builder, true);
1199 (llvm::CodeGenOptLevel::Default, ..) => {
1200 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 225);
1202 (llvm::CodeGenOptLevel::Other, ..) => {
1203 bug!("CodeGenOptLevel::Other selected")
1208 llvm::LLVMPassManagerBuilderDispose(builder);