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 session::config::{OutputFilenames, OutputTypes, Passes, SomePasses, AllPasses, Sanitizer};
17 use session::config::{self, OutputType};
19 use llvm::{ModuleRef, TargetMachineRef, PassManagerRef, DiagnosticInfoRef, ContextRef};
20 use llvm::SMDiagnosticRef;
21 use {CrateTranslation, ModuleLlvm, ModuleSource, ModuleTranslation};
22 use util::common::{time, time_depth, set_time_depth};
23 use util::common::path2cstr;
24 use util::fs::link_or_copy;
25 use errors::{self, Handler, Level, DiagnosticBuilder};
26 use errors::emitter::Emitter;
27 use syntax_pos::MultiSpan;
28 use context::{is_pie_binary, get_reloc_model};
31 use std::ffi::CString;
33 use std::path::{Path, PathBuf};
35 use std::sync::{Arc, Mutex};
36 use std::sync::mpsc::channel;
38 use libc::{c_uint, c_void};
40 pub const RELOC_MODEL_ARGS : [(&'static str, llvm::RelocMode); 7] = [
41 ("pic", llvm::RelocMode::PIC),
42 ("static", llvm::RelocMode::Static),
43 ("default", llvm::RelocMode::Default),
44 ("dynamic-no-pic", llvm::RelocMode::DynamicNoPic),
45 ("ropi", llvm::RelocMode::ROPI),
46 ("rwpi", llvm::RelocMode::RWPI),
47 ("ropi-rwpi", llvm::RelocMode::ROPI_RWPI),
50 pub const CODE_GEN_MODEL_ARGS : [(&'static str, llvm::CodeModel); 5] = [
51 ("default", llvm::CodeModel::Default),
52 ("small", llvm::CodeModel::Small),
53 ("kernel", llvm::CodeModel::Kernel),
54 ("medium", llvm::CodeModel::Medium),
55 ("large", llvm::CodeModel::Large),
58 pub fn llvm_err(handler: &errors::Handler, msg: String) -> ! {
59 match llvm::last_error() {
60 Some(err) => panic!(handler.fatal(&format!("{}: {}", msg, err))),
61 None => panic!(handler.fatal(&msg)),
65 pub fn write_output_file(
66 handler: &errors::Handler,
67 target: llvm::TargetMachineRef,
68 pm: llvm::PassManagerRef,
71 file_type: llvm::FileType) {
73 let output_c = path2cstr(output);
74 let result = llvm::LLVMRustWriteOutputFile(
75 target, pm, m, output_c.as_ptr(), file_type);
76 if result.into_result().is_err() {
77 llvm_err(handler, format!("could not write output to {}", output.display()));
89 // We use an Arc instead of just returning a list of diagnostics from the
90 // child thread because we need to make sure that the messages are seen even
91 // if the child thread panics (for example, when `fatal` is called).
93 struct SharedEmitter {
94 buffer: Arc<Mutex<Vec<Diagnostic>>>,
98 fn new() -> SharedEmitter {
100 buffer: Arc::new(Mutex::new(Vec::new())),
104 fn dump(&mut self, handler: &Handler) {
105 let mut buffer = self.buffer.lock().unwrap();
106 for diag in &*buffer {
109 handler.emit_with_code(&MultiSpan::new(),
115 handler.emit(&MultiSpan::new(),
125 impl Emitter for SharedEmitter {
126 fn emit(&mut self, db: &DiagnosticBuilder) {
127 self.buffer.lock().unwrap().push(Diagnostic {
129 code: db.code.clone(),
132 for child in &db.children {
133 self.buffer.lock().unwrap().push(Diagnostic {
134 msg: child.message(),
142 // On android, we by default compile for armv7 processors. This enables
143 // things like double word CAS instructions (rather than emulating them)
144 // which are *far* more efficient. This is obviously undesirable in some
145 // cases, so if any sort of target feature is specified we don't append v7
146 // to the feature list.
148 // On iOS only armv7 and newer are supported. So it is useful to
149 // get all hardware potential via VFP3 (hardware floating point)
150 // and NEON (SIMD) instructions supported by LLVM.
151 // Note that without those flags various linking errors might
152 // arise as some of intrinsics are converted into function calls
153 // and nobody provides implementations those functions
154 fn target_feature(sess: &Session) -> String {
155 let rustc_features = [
158 let requested_features = sess.opts.cg.target_feature.split(',');
159 let llvm_features = requested_features.filter(|f| {
160 !rustc_features.iter().any(|s| f.contains(s))
163 sess.target.target.options.features,
164 llvm_features.collect::<Vec<_>>().join(","))
167 fn get_llvm_opt_level(optimize: config::OptLevel) -> llvm::CodeGenOptLevel {
169 config::OptLevel::No => llvm::CodeGenOptLevel::None,
170 config::OptLevel::Less => llvm::CodeGenOptLevel::Less,
171 config::OptLevel::Default => llvm::CodeGenOptLevel::Default,
172 config::OptLevel::Aggressive => llvm::CodeGenOptLevel::Aggressive,
173 _ => llvm::CodeGenOptLevel::Default,
177 fn get_llvm_opt_size(optimize: config::OptLevel) -> llvm::CodeGenOptSize {
179 config::OptLevel::Size => llvm::CodeGenOptSizeDefault,
180 config::OptLevel::SizeMin => llvm::CodeGenOptSizeAggressive,
181 _ => llvm::CodeGenOptSizeNone,
185 pub fn create_target_machine(sess: &Session) -> TargetMachineRef {
186 let reloc_model = get_reloc_model(sess);
188 let opt_level = get_llvm_opt_level(sess.opts.optimize);
189 let use_softfp = sess.opts.cg.soft_float;
191 let ffunction_sections = sess.target.target.options.function_sections;
192 let fdata_sections = ffunction_sections;
194 let code_model_arg = match sess.opts.cg.code_model {
196 None => &sess.target.target.options.code_model,
199 let code_model = match CODE_GEN_MODEL_ARGS.iter().find(
200 |&&arg| arg.0 == code_model_arg) {
203 sess.err(&format!("{:?} is not a valid code model",
207 sess.abort_if_errors();
212 let triple = &sess.target.target.llvm_target;
215 let triple = CString::new(triple.as_bytes()).unwrap();
216 let cpu = match sess.opts.cg.target_cpu {
218 None => &*sess.target.target.options.cpu
220 let cpu = CString::new(cpu.as_bytes()).unwrap();
221 let features = CString::new(target_feature(sess).as_bytes()).unwrap();
222 llvm::LLVMRustCreateTargetMachine(
223 triple.as_ptr(), cpu.as_ptr(), features.as_ptr(),
235 llvm_err(sess.diagnostic(),
236 format!("Could not create LLVM TargetMachine for triple: {}",
237 triple).to_string());
244 /// Module-specific configuration for `optimize_and_codegen`.
246 pub struct ModuleConfig {
247 /// LLVM TargetMachine to use for codegen.
248 tm: TargetMachineRef,
249 /// Names of additional optimization passes to run.
251 /// Some(level) to optimize at a certain level, or None to run
252 /// absolutely no optimizations (used for the metadata module).
253 opt_level: Option<llvm::CodeGenOptLevel>,
255 /// Some(level) to optimize binary size, or None to not affect program size.
256 opt_size: Option<llvm::CodeGenOptSize>,
258 // Flags indicating which outputs to produce.
259 emit_no_opt_bc: bool,
265 // Miscellaneous flags. These are mostly copied from command-line
268 no_prepopulate_passes: bool,
271 vectorize_loop: bool,
273 merge_functions: bool,
274 inline_threshold: Option<usize>,
275 // Instead of creating an object file by doing LLVM codegen, just
276 // make the object file bitcode. Provides easy compatibility with
277 // emscripten's ecc compiler, when used as the linker.
278 obj_is_bitcode: bool,
281 unsafe impl Send for ModuleConfig { }
284 fn new(tm: TargetMachineRef, passes: Vec<String>) -> ModuleConfig {
291 emit_no_opt_bc: false,
297 obj_is_bitcode: false,
300 no_prepopulate_passes: false,
303 vectorize_loop: false,
304 vectorize_slp: false,
305 merge_functions: false,
306 inline_threshold: None
310 fn set_flags(&mut self, sess: &Session, trans: &CrateTranslation) {
311 self.no_verify = sess.no_verify();
312 self.no_prepopulate_passes = sess.opts.cg.no_prepopulate_passes;
313 self.no_builtins = trans.no_builtins;
314 self.time_passes = sess.time_passes();
315 self.inline_threshold = sess.opts.cg.inline_threshold;
316 self.obj_is_bitcode = sess.target.target.options.obj_is_bitcode;
318 // Copy what clang does by turning on loop vectorization at O2 and
319 // slp vectorization at O3. Otherwise configure other optimization aspects
320 // of this pass manager builder.
321 // Turn off vectorization for emscripten, as it's not very well supported.
322 self.vectorize_loop = !sess.opts.cg.no_vectorize_loops &&
323 (sess.opts.optimize == config::OptLevel::Default ||
324 sess.opts.optimize == config::OptLevel::Aggressive) &&
325 !sess.target.target.options.is_like_emscripten;
327 self.vectorize_slp = !sess.opts.cg.no_vectorize_slp &&
328 sess.opts.optimize == config::OptLevel::Aggressive &&
329 !sess.target.target.options.is_like_emscripten;
331 self.merge_functions = sess.opts.optimize == config::OptLevel::Default ||
332 sess.opts.optimize == config::OptLevel::Aggressive;
336 /// Additional resources used by optimize_and_codegen (not module specific)
337 struct CodegenContext<'a> {
338 // Extra resources used for LTO: (sess, reachable). This will be `None`
339 // when running in a worker thread.
340 lto_ctxt: Option<(&'a Session, &'a ExportedSymbols)>,
341 // Handler to use for diagnostics produced during codegen.
342 handler: &'a Handler,
343 // LLVM passes added by plugins.
344 plugin_passes: Vec<String>,
345 // LLVM optimizations for which we want to print remarks.
347 // Worker thread number
349 // The incremental compilation session directory, or None if we are not
350 // compiling incrementally
351 incr_comp_session_dir: Option<PathBuf>
354 impl<'a> CodegenContext<'a> {
355 fn new_with_session(sess: &'a Session,
356 exported_symbols: &'a ExportedSymbols)
357 -> CodegenContext<'a> {
359 lto_ctxt: Some((sess, exported_symbols)),
360 handler: sess.diagnostic(),
361 plugin_passes: sess.plugin_llvm_passes.borrow().clone(),
362 remark: sess.opts.cg.remark.clone(),
364 incr_comp_session_dir: sess.incr_comp_session_dir_opt().map(|r| r.clone())
369 struct HandlerFreeVars<'a> {
371 cgcx: &'a CodegenContext<'a>,
374 unsafe extern "C" fn report_inline_asm<'a, 'b>(cgcx: &'a CodegenContext<'a>,
377 use syntax::ext::hygiene::Mark;
379 match cgcx.lto_ctxt {
381 match Mark::from_u32(cookie).expn_info() {
382 Some(ei) => sess.span_err(ei.call_site, msg),
383 None => sess.err(msg),
388 cgcx.handler.struct_err(msg)
389 .note("build without -C codegen-units for more exact errors")
395 unsafe extern "C" fn inline_asm_handler(diag: SMDiagnosticRef,
398 let HandlerFreeVars { cgcx, .. } = *(user as *const HandlerFreeVars);
400 let msg = llvm::build_string(|s| llvm::LLVMRustWriteSMDiagnosticToString(diag, s))
401 .expect("non-UTF8 SMDiagnostic");
403 report_inline_asm(cgcx, &msg, cookie);
406 unsafe extern "C" fn diagnostic_handler(info: DiagnosticInfoRef, user: *mut c_void) {
407 let HandlerFreeVars { llcx, cgcx } = *(user as *const HandlerFreeVars);
409 match llvm::diagnostic::Diagnostic::unpack(info) {
410 llvm::diagnostic::InlineAsm(inline) => {
411 report_inline_asm(cgcx,
412 &llvm::twine_to_string(inline.message),
416 llvm::diagnostic::Optimization(opt) => {
417 let enabled = match cgcx.remark {
419 SomePasses(ref v) => v.iter().any(|s| *s == opt.pass_name),
423 let loc = llvm::debug_loc_to_string(llcx, opt.debug_loc);
424 cgcx.handler.note_without_error(&format!("optimization {} for {} at {}: {}",
427 if loc.is_empty() { "[unknown]" } else { &*loc },
436 // Unsafe due to LLVM calls.
437 unsafe fn optimize_and_codegen(cgcx: &CodegenContext,
438 mtrans: ModuleTranslation,
440 config: ModuleConfig,
441 output_names: OutputFilenames) {
442 let llmod = mllvm.llmod;
443 let llcx = mllvm.llcx;
446 // llcx doesn't outlive this function, so we can put this on the stack.
447 let fv = HandlerFreeVars {
451 let fv = &fv as *const HandlerFreeVars as *mut c_void;
453 llvm::LLVMRustSetInlineAsmDiagnosticHandler(llcx, inline_asm_handler, fv);
454 llvm::LLVMContextSetDiagnosticHandler(llcx, diagnostic_handler, fv);
456 let module_name = Some(&mtrans.name[..]);
458 if config.emit_no_opt_bc {
459 let out = output_names.temp_path_ext("no-opt.bc", module_name);
460 let out = path2cstr(&out);
461 llvm::LLVMWriteBitcodeToFile(llmod, out.as_ptr());
464 if config.opt_level.is_some() {
465 // Create the two optimizing pass managers. These mirror what clang
466 // does, and are by populated by LLVM's default PassManagerBuilder.
467 // Each manager has a different set of passes, but they also share
468 // some common passes.
469 let fpm = llvm::LLVMCreateFunctionPassManagerForModule(llmod);
470 let mpm = llvm::LLVMCreatePassManager();
472 // If we're verifying or linting, add them to the function pass
474 let addpass = |pass_name: &str| {
475 let pass_name = CString::new(pass_name).unwrap();
476 let pass = llvm::LLVMRustFindAndCreatePass(pass_name.as_ptr());
480 let pass_manager = match llvm::LLVMRustPassKind(pass) {
481 llvm::PassKind::Function => fpm,
482 llvm::PassKind::Module => mpm,
483 llvm::PassKind::Other => {
484 cgcx.handler.err("Encountered LLVM pass kind we can't handle");
488 llvm::LLVMRustAddPass(pass_manager, pass);
492 if !config.no_verify { assert!(addpass("verify")); }
493 if !config.no_prepopulate_passes {
494 llvm::LLVMRustAddAnalysisPasses(tm, fpm, llmod);
495 llvm::LLVMRustAddAnalysisPasses(tm, mpm, llmod);
496 with_llvm_pmb(llmod, &config, &mut |b| {
497 llvm::LLVMPassManagerBuilderPopulateFunctionPassManager(b, fpm);
498 llvm::LLVMPassManagerBuilderPopulateModulePassManager(b, mpm);
502 for pass in &config.passes {
504 cgcx.handler.warn(&format!("unknown pass `{}`, ignoring",
509 for pass in &cgcx.plugin_passes {
511 cgcx.handler.err(&format!("a plugin asked for LLVM pass \
512 `{}` but LLVM does not \
513 recognize it", pass));
517 cgcx.handler.abort_if_errors();
519 // Finally, run the actual optimization passes
520 time(config.time_passes, &format!("llvm function passes [{}]", cgcx.worker), ||
521 llvm::LLVMRustRunFunctionPassManager(fpm, llmod));
522 time(config.time_passes, &format!("llvm module passes [{}]", cgcx.worker), ||
523 llvm::LLVMRunPassManager(mpm, llmod));
525 // Deallocate managers that we're now done with
526 llvm::LLVMDisposePassManager(fpm);
527 llvm::LLVMDisposePassManager(mpm);
529 match cgcx.lto_ctxt {
530 Some((sess, exported_symbols)) if sess.lto() => {
531 time(sess.time_passes(), "all lto passes", || {
532 let temp_no_opt_bc_filename =
533 output_names.temp_path_ext("no-opt.lto.bc", module_name);
539 &temp_no_opt_bc_filename);
541 if config.emit_lto_bc {
542 let out = output_names.temp_path_ext("lto.bc", module_name);
543 let out = path2cstr(&out);
544 llvm::LLVMWriteBitcodeToFile(llmod, out.as_ptr());
551 // A codegen-specific pass manager is used to generate object
552 // files for an LLVM module.
554 // Apparently each of these pass managers is a one-shot kind of
555 // thing, so we create a new one for each type of output. The
556 // pass manager passed to the closure should be ensured to not
557 // escape the closure itself, and the manager should only be
559 unsafe fn with_codegen<F>(tm: TargetMachineRef,
563 F: FnOnce(PassManagerRef),
565 let cpm = llvm::LLVMCreatePassManager();
566 llvm::LLVMRustAddAnalysisPasses(tm, cpm, llmod);
567 llvm::LLVMRustAddLibraryInfo(cpm, llmod, no_builtins);
571 // Change what we write and cleanup based on whether obj files are
572 // just llvm bitcode. In that case write bitcode, and possibly
573 // delete the bitcode if it wasn't requested. Don't generate the
574 // machine code, instead copy the .o file from the .bc
575 let write_bc = config.emit_bc || config.obj_is_bitcode;
576 let rm_bc = !config.emit_bc && config.obj_is_bitcode;
577 let write_obj = config.emit_obj && !config.obj_is_bitcode;
578 let copy_bc_to_obj = config.emit_obj && config.obj_is_bitcode;
580 let bc_out = output_names.temp_path(OutputType::Bitcode, module_name);
581 let obj_out = output_names.temp_path(OutputType::Object, module_name);
584 let bc_out_c = path2cstr(&bc_out);
585 llvm::LLVMWriteBitcodeToFile(llmod, bc_out_c.as_ptr());
588 time(config.time_passes, &format!("codegen passes [{}]", cgcx.worker), || {
590 let out = output_names.temp_path(OutputType::LlvmAssembly, module_name);
591 let out = path2cstr(&out);
592 with_codegen(tm, llmod, config.no_builtins, |cpm| {
593 llvm::LLVMRustPrintModule(cpm, llmod, out.as_ptr());
594 llvm::LLVMDisposePassManager(cpm);
599 let path = output_names.temp_path(OutputType::Assembly, module_name);
601 // We can't use the same module for asm and binary output, because that triggers
602 // various errors like invalid IR or broken binaries, so we might have to clone the
603 // module to produce the asm output
604 let llmod = if config.emit_obj {
605 llvm::LLVMCloneModule(llmod)
609 with_codegen(tm, llmod, config.no_builtins, |cpm| {
610 write_output_file(cgcx.handler, tm, cpm, llmod, &path,
611 llvm::FileType::AssemblyFile);
614 llvm::LLVMDisposeModule(llmod);
619 with_codegen(tm, llmod, config.no_builtins, |cpm| {
620 write_output_file(cgcx.handler, tm, cpm, llmod, &obj_out,
621 llvm::FileType::ObjectFile);
627 debug!("copying bitcode {:?} to obj {:?}", bc_out, obj_out);
628 if let Err(e) = link_or_copy(&bc_out, &obj_out) {
629 cgcx.handler.err(&format!("failed to copy bitcode to object file: {}", e));
634 debug!("removing_bitcode {:?}", bc_out);
635 if let Err(e) = fs::remove_file(&bc_out) {
636 cgcx.handler.err(&format!("failed to remove bitcode: {}", e));
640 llvm::LLVMRustDisposeTargetMachine(tm);
644 pub fn cleanup_llvm(trans: &CrateTranslation) {
645 for module in trans.modules.iter() {
647 match module.source {
648 ModuleSource::Translated(llvm) => {
649 llvm::LLVMDisposeModule(llvm.llmod);
650 llvm::LLVMContextDispose(llvm.llcx);
652 ModuleSource::Preexisting(_) => {
659 pub fn run_passes(sess: &Session,
660 trans: &CrateTranslation,
661 output_types: &OutputTypes,
662 crate_output: &OutputFilenames) {
663 // It's possible that we have `codegen_units > 1` but only one item in
664 // `trans.modules`. We could theoretically proceed and do LTO in that
665 // case, but it would be confusing to have the validity of
666 // `-Z lto -C codegen-units=2` depend on details of the crate being
667 // compiled, so we complain regardless.
668 if sess.lto() && sess.opts.cg.codegen_units > 1 {
669 // This case is impossible to handle because LTO expects to be able
670 // to combine the entire crate and all its dependencies into a
671 // single compilation unit, but each codegen unit is in a separate
672 // LLVM context, so they can't easily be combined.
673 sess.fatal("can't perform LTO when using multiple codegen units");
677 assert!(trans.modules.len() == sess.opts.cg.codegen_units ||
678 sess.opts.debugging_opts.incremental.is_some() ||
679 !sess.opts.output_types.should_trans() ||
680 sess.opts.debugging_opts.no_trans);
682 let tm = create_target_machine(sess);
684 // Figure out what we actually need to build.
686 let mut modules_config = ModuleConfig::new(tm, sess.opts.cg.passes.clone());
687 let mut metadata_config = ModuleConfig::new(tm, vec![]);
689 if let Some(ref sanitizer) = sess.opts.debugging_opts.sanitizer {
691 Sanitizer::Address => {
692 modules_config.passes.push("asan".to_owned());
693 modules_config.passes.push("asan-module".to_owned());
695 Sanitizer::Memory => {
696 modules_config.passes.push("msan".to_owned())
698 Sanitizer::Thread => {
699 modules_config.passes.push("tsan".to_owned())
705 modules_config.opt_level = Some(get_llvm_opt_level(sess.opts.optimize));
706 modules_config.opt_size = Some(get_llvm_opt_size(sess.opts.optimize));
708 // Save all versions of the bytecode if we're saving our temporaries.
709 if sess.opts.cg.save_temps {
710 modules_config.emit_no_opt_bc = true;
711 modules_config.emit_bc = true;
712 modules_config.emit_lto_bc = true;
713 metadata_config.emit_bc = true;
716 // Emit bitcode files for the crate if we're emitting an rlib.
717 // Whenever an rlib is created, the bitcode is inserted into the
718 // archive in order to allow LTO against it.
719 let needs_crate_bitcode =
720 sess.crate_types.borrow().contains(&config::CrateTypeRlib) &&
721 sess.opts.output_types.contains_key(&OutputType::Exe);
722 let needs_crate_object =
723 sess.opts.output_types.contains_key(&OutputType::Exe);
724 if needs_crate_bitcode {
725 modules_config.emit_bc = true;
728 for output_type in output_types.keys() {
730 OutputType::Bitcode => { modules_config.emit_bc = true; }
731 OutputType::LlvmAssembly => { modules_config.emit_ir = true; }
732 OutputType::Assembly => {
733 modules_config.emit_asm = true;
734 // If we're not using the LLVM assembler, this function
735 // could be invoked specially with output_type_assembly, so
736 // in this case we still want the metadata object file.
737 if !sess.opts.output_types.contains_key(&OutputType::Assembly) {
738 metadata_config.emit_obj = true;
741 OutputType::Object => { modules_config.emit_obj = true; }
742 OutputType::Metadata => { metadata_config.emit_obj = true; }
744 modules_config.emit_obj = true;
745 metadata_config.emit_obj = true;
747 OutputType::Mir => {}
748 OutputType::DepInfo => {}
752 modules_config.set_flags(sess, trans);
753 metadata_config.set_flags(sess, trans);
756 // Populate a buffer with a list of codegen threads. Items are processed in
757 // LIFO order, just because it's a tiny bit simpler that way. (The order
758 // doesn't actually matter.)
759 let mut work_items = Vec::with_capacity(1 + trans.modules.len());
762 let work = build_work_item(sess,
763 trans.metadata_module.clone(),
764 metadata_config.clone(),
765 crate_output.clone());
766 work_items.push(work);
769 for mtrans in trans.modules.iter() {
770 let work = build_work_item(sess,
772 modules_config.clone(),
773 crate_output.clone());
774 work_items.push(work);
777 if sess.opts.debugging_opts.incremental_info {
778 dump_incremental_data(&trans);
781 // Process the work items, optionally using worker threads.
782 // NOTE: We are hardcoding a limit of worker threads for now. With
783 // incremental compilation we can run into situations where we would
784 // open hundreds of threads otherwise -- which can make things slower
785 // if things don't fit into memory anymore, or can cause the compiler
786 // to crash because of too many open file handles. See #39280 for
787 // some discussion on how to improve this in the future.
788 let num_workers = cmp::min(work_items.len() - 1, 32);
789 if num_workers <= 1 {
790 run_work_singlethreaded(sess, &trans.exported_symbols, work_items);
792 run_work_multithreaded(sess, work_items, num_workers);
795 // If in incr. comp. mode, preserve the `.o` files for potential re-use
796 for mtrans in trans.modules.iter() {
797 let mut files = vec![];
799 if modules_config.emit_obj {
800 let path = crate_output.temp_path(OutputType::Object, Some(&mtrans.name));
801 files.push((OutputType::Object, path));
804 if modules_config.emit_bc {
805 let path = crate_output.temp_path(OutputType::Bitcode, Some(&mtrans.name));
806 files.push((OutputType::Bitcode, path));
809 save_trans_partition(sess, &mtrans.name, mtrans.symbol_name_hash, &files);
812 // All codegen is finished.
814 llvm::LLVMRustDisposeTargetMachine(tm);
817 // Produce final compile outputs.
818 let copy_gracefully = |from: &Path, to: &Path| {
819 if let Err(e) = fs::copy(from, to) {
820 sess.err(&format!("could not copy {:?} to {:?}: {}", from, to, e));
824 let copy_if_one_unit = |output_type: OutputType,
825 keep_numbered: bool| {
826 if trans.modules.len() == 1 {
827 // 1) Only one codegen unit. In this case it's no difficulty
828 // to copy `foo.0.x` to `foo.x`.
829 let module_name = Some(&trans.modules[0].name[..]);
830 let path = crate_output.temp_path(output_type, module_name);
831 copy_gracefully(&path,
832 &crate_output.path(output_type));
833 if !sess.opts.cg.save_temps && !keep_numbered {
834 // The user just wants `foo.x`, not `foo.#module-name#.x`.
838 let ext = crate_output.temp_path(output_type, None)
845 if crate_output.outputs.contains_key(&output_type) {
846 // 2) Multiple codegen units, with `--emit foo=some_name`. We have
847 // no good solution for this case, so warn the user.
848 sess.warn(&format!("ignoring emit path because multiple .{} files \
849 were produced", ext));
850 } else if crate_output.single_output_file.is_some() {
851 // 3) Multiple codegen units, with `-o some_name`. We have
852 // no good solution for this case, so warn the user.
853 sess.warn(&format!("ignoring -o because multiple .{} files \
854 were produced", ext));
856 // 4) Multiple codegen units, but no explicit name. We
857 // just leave the `foo.0.x` files in place.
858 // (We don't have to do any work in this case.)
863 // Flag to indicate whether the user explicitly requested bitcode.
864 // Otherwise, we produced it only as a temporary output, and will need
866 let mut user_wants_bitcode = false;
867 let mut user_wants_objects = false;
868 for output_type in output_types.keys() {
870 OutputType::Bitcode => {
871 user_wants_bitcode = true;
872 // Copy to .bc, but always keep the .0.bc. There is a later
873 // check to figure out if we should delete .0.bc files, or keep
874 // them for making an rlib.
875 copy_if_one_unit(OutputType::Bitcode, true);
877 OutputType::LlvmAssembly => {
878 copy_if_one_unit(OutputType::LlvmAssembly, false);
880 OutputType::Assembly => {
881 copy_if_one_unit(OutputType::Assembly, false);
883 OutputType::Object => {
884 user_wants_objects = true;
885 copy_if_one_unit(OutputType::Object, true);
888 OutputType::Metadata |
890 OutputType::DepInfo => {}
893 let user_wants_bitcode = user_wants_bitcode;
895 // Clean up unwanted temporary files.
897 // We create the following files by default:
898 // - #crate#.#module-name#.bc
899 // - #crate#.#module-name#.o
900 // - #crate#.crate.metadata.bc
901 // - #crate#.crate.metadata.o
902 // - #crate#.o (linked from crate.##.o)
903 // - #crate#.bc (copied from crate.##.bc)
904 // We may create additional files if requested by the user (through
905 // `-C save-temps` or `--emit=` flags).
907 if !sess.opts.cg.save_temps {
908 // Remove the temporary .#module-name#.o objects. If the user didn't
909 // explicitly request bitcode (with --emit=bc), and the bitcode is not
910 // needed for building an rlib, then we must remove .#module-name#.bc as
913 // Specific rules for keeping .#module-name#.bc:
914 // - If we're building an rlib (`needs_crate_bitcode`), then keep
916 // - If the user requested bitcode (`user_wants_bitcode`), and
917 // codegen_units > 1, then keep it.
918 // - If the user requested bitcode but codegen_units == 1, then we
919 // can toss .#module-name#.bc because we copied it to .bc earlier.
920 // - If we're not building an rlib and the user didn't request
921 // bitcode, then delete .#module-name#.bc.
922 // If you change how this works, also update back::link::link_rlib,
923 // where .#module-name#.bc files are (maybe) deleted after making an
925 let keep_numbered_bitcode = needs_crate_bitcode ||
926 (user_wants_bitcode && sess.opts.cg.codegen_units > 1);
928 let keep_numbered_objects = needs_crate_object ||
929 (user_wants_objects && sess.opts.cg.codegen_units > 1);
931 for module_name in trans.modules.iter().map(|m| Some(&m.name[..])) {
932 if modules_config.emit_obj && !keep_numbered_objects {
933 let path = crate_output.temp_path(OutputType::Object, module_name);
937 if modules_config.emit_bc && !keep_numbered_bitcode {
938 let path = crate_output.temp_path(OutputType::Bitcode, module_name);
943 if metadata_config.emit_bc && !user_wants_bitcode {
944 let path = crate_output.temp_path(OutputType::Bitcode,
945 Some(&trans.metadata_module.name));
950 // We leave the following files around by default:
952 // - #crate#.crate.metadata.o
954 // These are used in linking steps and will be cleaned up afterward.
956 // FIXME: time_llvm_passes support - does this use a global context or
958 if sess.opts.cg.codegen_units == 1 && sess.time_llvm_passes() {
959 unsafe { llvm::LLVMRustPrintPassTimings(); }
963 fn dump_incremental_data(trans: &CrateTranslation) {
965 for mtrans in trans.modules.iter() {
966 match mtrans.source {
967 ModuleSource::Preexisting(..) => reuse += 1,
968 ModuleSource::Translated(..) => (),
971 println!("incremental: re-using {} out of {} modules", reuse, trans.modules.len());
975 mtrans: ModuleTranslation,
976 config: ModuleConfig,
977 output_names: OutputFilenames
980 fn build_work_item(sess: &Session,
981 mtrans: ModuleTranslation,
982 config: ModuleConfig,
983 output_names: OutputFilenames)
986 let mut config = config;
987 config.tm = create_target_machine(sess);
991 output_names: output_names
995 fn execute_work_item(cgcx: &CodegenContext,
996 work_item: WorkItem) {
998 match work_item.mtrans.source {
999 ModuleSource::Translated(mllvm) => {
1000 debug!("llvm-optimizing {:?}", work_item.mtrans.name);
1001 optimize_and_codegen(cgcx,
1005 work_item.output_names);
1007 ModuleSource::Preexisting(wp) => {
1008 let incr_comp_session_dir = cgcx.incr_comp_session_dir
1011 let name = &work_item.mtrans.name;
1012 for (kind, saved_file) in wp.saved_files {
1013 let obj_out = work_item.output_names.temp_path(kind, Some(name));
1014 let source_file = in_incr_comp_dir(&incr_comp_session_dir,
1016 debug!("copying pre-existing module `{}` from {:?} to {}",
1017 work_item.mtrans.name,
1020 match link_or_copy(&source_file, &obj_out) {
1023 cgcx.handler.err(&format!("unable to copy {} to {}: {}",
1024 source_file.display(),
1035 fn run_work_singlethreaded(sess: &Session,
1036 exported_symbols: &ExportedSymbols,
1037 work_items: Vec<WorkItem>) {
1038 let cgcx = CodegenContext::new_with_session(sess, exported_symbols);
1040 // Since we're running single-threaded, we can pass the session to
1041 // the proc, allowing `optimize_and_codegen` to perform LTO.
1042 for work in work_items.into_iter().rev() {
1043 execute_work_item(&cgcx, work);
1047 fn run_work_multithreaded(sess: &Session,
1048 work_items: Vec<WorkItem>,
1049 num_workers: usize) {
1050 assert!(num_workers > 0);
1052 // Run some workers to process the work items.
1053 let work_items_arc = Arc::new(Mutex::new(work_items));
1054 let mut diag_emitter = SharedEmitter::new();
1055 let mut futures = Vec::with_capacity(num_workers);
1057 for i in 0..num_workers {
1058 let work_items_arc = work_items_arc.clone();
1059 let diag_emitter = diag_emitter.clone();
1060 let plugin_passes = sess.plugin_llvm_passes.borrow().clone();
1061 let remark = sess.opts.cg.remark.clone();
1063 let (tx, rx) = channel();
1064 let mut tx = Some(tx);
1067 let incr_comp_session_dir = sess.incr_comp_session_dir_opt().map(|r| r.clone());
1069 let depth = time_depth();
1070 thread::Builder::new().name(format!("codegen-{}", i)).spawn(move || {
1071 set_time_depth(depth);
1073 let diag_handler = Handler::with_emitter(true, false, box diag_emitter);
1075 // Must construct cgcx inside the proc because it has non-Send
1077 let cgcx = CodegenContext {
1079 handler: &diag_handler,
1080 plugin_passes: plugin_passes,
1083 incr_comp_session_dir: incr_comp_session_dir
1087 // Avoid holding the lock for the entire duration of the match.
1088 let maybe_work = work_items_arc.lock().unwrap().pop();
1091 execute_work_item(&cgcx, work);
1093 // Make sure to fail the worker so the main thread can
1094 // tell that there were errors.
1095 cgcx.handler.abort_if_errors();
1101 tx.take().unwrap().send(()).unwrap();
1105 let mut panicked = false;
1113 // Display any new diagnostics.
1114 diag_emitter.dump(sess.diagnostic());
1117 sess.fatal("aborting due to worker thread panic");
1121 pub fn run_assembler(sess: &Session, outputs: &OutputFilenames) {
1122 let (pname, mut cmd, _) = get_linker(sess);
1124 for arg in &sess.target.target.options.asm_args {
1128 cmd.arg("-c").arg("-o").arg(&outputs.path(OutputType::Object))
1129 .arg(&outputs.temp_path(OutputType::Assembly, None));
1130 debug!("{:?}", cmd);
1132 match cmd.output() {
1134 if !prog.status.success() {
1135 let mut note = prog.stderr.clone();
1136 note.extend_from_slice(&prog.stdout);
1138 sess.struct_err(&format!("linking with `{}` failed: {}",
1141 .note(&format!("{:?}", &cmd))
1142 .note(str::from_utf8(¬e[..]).unwrap())
1144 sess.abort_if_errors();
1148 sess.err(&format!("could not exec the linker `{}`: {}", pname, e));
1149 sess.abort_if_errors();
1154 pub unsafe fn with_llvm_pmb(llmod: ModuleRef,
1155 config: &ModuleConfig,
1156 f: &mut FnMut(llvm::PassManagerBuilderRef)) {
1157 // Create the PassManagerBuilder for LLVM. We configure it with
1158 // reasonable defaults and prepare it to actually populate the pass
1160 let builder = llvm::LLVMPassManagerBuilderCreate();
1161 let opt_level = config.opt_level.unwrap_or(llvm::CodeGenOptLevel::None);
1162 let opt_size = config.opt_size.unwrap_or(llvm::CodeGenOptSizeNone);
1163 let inline_threshold = config.inline_threshold;
1165 llvm::LLVMRustConfigurePassManagerBuilder(builder, opt_level,
1166 config.merge_functions,
1167 config.vectorize_slp,
1168 config.vectorize_loop);
1169 llvm::LLVMPassManagerBuilderSetSizeLevel(builder, opt_size as u32);
1171 if opt_size != llvm::CodeGenOptSizeNone {
1172 llvm::LLVMPassManagerBuilderSetDisableUnrollLoops(builder, 1);
1175 llvm::LLVMRustAddBuilderLibraryInfo(builder, llmod, config.no_builtins);
1177 // Here we match what clang does (kinda). For O0 we only inline
1178 // always-inline functions (but don't add lifetime intrinsics), at O1 we
1179 // inline with lifetime intrinsics, and O2+ we add an inliner with a
1180 // thresholds copied from clang.
1181 match (opt_level, opt_size, inline_threshold) {
1183 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, t as u32);
1185 (llvm::CodeGenOptLevel::Aggressive, ..) => {
1186 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 275);
1188 (_, llvm::CodeGenOptSizeDefault, _) => {
1189 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 75);
1191 (_, llvm::CodeGenOptSizeAggressive, _) => {
1192 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 25);
1194 (llvm::CodeGenOptLevel::None, ..) => {
1195 llvm::LLVMRustAddAlwaysInlinePass(builder, false);
1197 (llvm::CodeGenOptLevel::Less, ..) => {
1198 llvm::LLVMRustAddAlwaysInlinePass(builder, true);
1200 (llvm::CodeGenOptLevel::Default, ..) => {
1201 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 225);
1203 (llvm::CodeGenOptLevel::Other, ..) => {
1204 bug!("CodeGenOptLevel::Other selected")
1209 llvm::LLVMPassManagerBuilderDispose(builder);