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::{self, 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::hir::def_id::CrateNum;
23 use rustc::util::common::{time, time_depth, set_time_depth, path2cstr};
24 use rustc::util::fs::link_or_copy;
25 use errors::{self, Handler, Level, DiagnosticBuilder, FatalError};
26 use errors::emitter::Emitter;
27 use syntax::ext::hygiene::Mark;
28 use syntax_pos::MultiSpan;
29 use context::{is_pie_binary, get_reloc_model};
30 use jobserver::{Client, Acquired};
31 use crossbeam::{scope, Scope};
35 use std::ffi::CString;
39 use std::path::{Path, PathBuf};
41 use std::sync::mpsc::{channel, Sender};
43 use libc::{c_uint, c_void, c_char, size_t};
45 pub const RELOC_MODEL_ARGS : [(&'static str, llvm::RelocMode); 7] = [
46 ("pic", llvm::RelocMode::PIC),
47 ("static", llvm::RelocMode::Static),
48 ("default", llvm::RelocMode::Default),
49 ("dynamic-no-pic", llvm::RelocMode::DynamicNoPic),
50 ("ropi", llvm::RelocMode::ROPI),
51 ("rwpi", llvm::RelocMode::RWPI),
52 ("ropi-rwpi", llvm::RelocMode::ROPI_RWPI),
55 pub const CODE_GEN_MODEL_ARGS : [(&'static str, llvm::CodeModel); 5] = [
56 ("default", llvm::CodeModel::Default),
57 ("small", llvm::CodeModel::Small),
58 ("kernel", llvm::CodeModel::Kernel),
59 ("medium", llvm::CodeModel::Medium),
60 ("large", llvm::CodeModel::Large),
63 pub fn llvm_err(handler: &errors::Handler, msg: String) -> FatalError {
64 match llvm::last_error() {
65 Some(err) => handler.fatal(&format!("{}: {}", msg, err)),
66 None => handler.fatal(&msg),
70 pub fn write_output_file(
71 handler: &errors::Handler,
72 target: llvm::TargetMachineRef,
73 pm: llvm::PassManagerRef,
76 file_type: llvm::FileType) -> Result<(), FatalError> {
78 let output_c = path2cstr(output);
79 let result = llvm::LLVMRustWriteOutputFile(
80 target, pm, m, output_c.as_ptr(), file_type);
81 if result.into_result().is_err() {
82 let msg = format!("could not write output to {}", output.display());
83 Err(llvm_err(handler, msg))
90 // On android, we by default compile for armv7 processors. This enables
91 // things like double word CAS instructions (rather than emulating them)
92 // which are *far* more efficient. This is obviously undesirable in some
93 // cases, so if any sort of target feature is specified we don't append v7
94 // to the feature list.
96 // On iOS only armv7 and newer are supported. So it is useful to
97 // get all hardware potential via VFP3 (hardware floating point)
98 // and NEON (SIMD) instructions supported by LLVM.
99 // Note that without those flags various linking errors might
100 // arise as some of intrinsics are converted into function calls
101 // and nobody provides implementations those functions
102 fn target_feature(sess: &Session) -> String {
103 let rustc_features = [
106 let requested_features = sess.opts.cg.target_feature.split(',');
107 let llvm_features = requested_features.filter(|f| {
108 !rustc_features.iter().any(|s| f.contains(s))
111 sess.target.target.options.features,
112 llvm_features.collect::<Vec<_>>().join(","))
115 fn get_llvm_opt_level(optimize: config::OptLevel) -> llvm::CodeGenOptLevel {
117 config::OptLevel::No => llvm::CodeGenOptLevel::None,
118 config::OptLevel::Less => llvm::CodeGenOptLevel::Less,
119 config::OptLevel::Default => llvm::CodeGenOptLevel::Default,
120 config::OptLevel::Aggressive => llvm::CodeGenOptLevel::Aggressive,
121 _ => llvm::CodeGenOptLevel::Default,
125 fn get_llvm_opt_size(optimize: config::OptLevel) -> llvm::CodeGenOptSize {
127 config::OptLevel::Size => llvm::CodeGenOptSizeDefault,
128 config::OptLevel::SizeMin => llvm::CodeGenOptSizeAggressive,
129 _ => llvm::CodeGenOptSizeNone,
133 pub fn create_target_machine(sess: &Session) -> TargetMachineRef {
134 let reloc_model = get_reloc_model(sess);
136 let opt_level = get_llvm_opt_level(sess.opts.optimize);
137 let use_softfp = sess.opts.cg.soft_float;
139 let ffunction_sections = sess.target.target.options.function_sections;
140 let fdata_sections = ffunction_sections;
142 let code_model_arg = match sess.opts.cg.code_model {
144 None => &sess.target.target.options.code_model,
147 let code_model = match CODE_GEN_MODEL_ARGS.iter().find(
148 |&&arg| arg.0 == code_model_arg) {
151 sess.err(&format!("{:?} is not a valid code model",
155 sess.abort_if_errors();
160 let triple = &sess.target.target.llvm_target;
163 let triple = CString::new(triple.as_bytes()).unwrap();
164 let cpu = match sess.opts.cg.target_cpu {
166 None => &*sess.target.target.options.cpu
168 let cpu = CString::new(cpu.as_bytes()).unwrap();
169 let features = CString::new(target_feature(sess).as_bytes()).unwrap();
170 llvm::LLVMRustCreateTargetMachine(
171 triple.as_ptr(), cpu.as_ptr(), features.as_ptr(),
183 let msg = format!("Could not create LLVM TargetMachine for triple: {}",
185 panic!(llvm_err(sess.diagnostic(), msg));
192 /// Module-specific configuration for `optimize_and_codegen`.
194 pub struct ModuleConfig {
195 /// LLVM TargetMachine to use for codegen.
196 tm: TargetMachineRef,
197 /// Names of additional optimization passes to run.
199 /// Some(level) to optimize at a certain level, or None to run
200 /// absolutely no optimizations (used for the metadata module).
201 opt_level: Option<llvm::CodeGenOptLevel>,
203 /// Some(level) to optimize binary size, or None to not affect program size.
204 opt_size: Option<llvm::CodeGenOptSize>,
206 // Flags indicating which outputs to produce.
207 emit_no_opt_bc: bool,
213 // Miscellaneous flags. These are mostly copied from command-line
216 no_prepopulate_passes: bool,
219 vectorize_loop: bool,
221 merge_functions: bool,
222 inline_threshold: Option<usize>,
223 // Instead of creating an object file by doing LLVM codegen, just
224 // make the object file bitcode. Provides easy compatibility with
225 // emscripten's ecc compiler, when used as the linker.
226 obj_is_bitcode: bool,
229 unsafe impl Send for ModuleConfig { }
232 fn new(tm: TargetMachineRef, passes: Vec<String>) -> ModuleConfig {
239 emit_no_opt_bc: false,
245 obj_is_bitcode: false,
248 no_prepopulate_passes: false,
251 vectorize_loop: false,
252 vectorize_slp: false,
253 merge_functions: false,
254 inline_threshold: None
258 fn set_flags(&mut self, sess: &Session, trans: &CrateTranslation) {
259 self.no_verify = sess.no_verify();
260 self.no_prepopulate_passes = sess.opts.cg.no_prepopulate_passes;
261 self.no_builtins = trans.no_builtins;
262 self.time_passes = sess.time_passes();
263 self.inline_threshold = sess.opts.cg.inline_threshold;
264 self.obj_is_bitcode = sess.target.target.options.obj_is_bitcode;
266 // Copy what clang does by turning on loop vectorization at O2 and
267 // slp vectorization at O3. Otherwise configure other optimization aspects
268 // of this pass manager builder.
269 // Turn off vectorization for emscripten, as it's not very well supported.
270 self.vectorize_loop = !sess.opts.cg.no_vectorize_loops &&
271 (sess.opts.optimize == config::OptLevel::Default ||
272 sess.opts.optimize == config::OptLevel::Aggressive) &&
273 !sess.target.target.options.is_like_emscripten;
275 self.vectorize_slp = !sess.opts.cg.no_vectorize_slp &&
276 sess.opts.optimize == config::OptLevel::Aggressive &&
277 !sess.target.target.options.is_like_emscripten;
279 self.merge_functions = sess.opts.optimize == config::OptLevel::Default ||
280 sess.opts.optimize == config::OptLevel::Aggressive;
284 /// Additional resources used by optimize_and_codegen (not module specific)
285 pub struct CodegenContext<'a> {
286 // Resouces needed when running LTO
287 pub time_passes: bool,
289 pub no_landing_pads: bool,
290 pub exported_symbols: &'a ExportedSymbols,
291 pub opts: &'a config::Options,
292 pub crate_types: Vec<config::CrateType>,
293 pub each_linked_rlib_for_lto: Vec<(CrateNum, PathBuf)>,
294 // Handler to use for diagnostics produced during codegen.
295 pub handler: &'a Handler,
296 // LLVM passes added by plugins.
297 pub plugin_passes: Vec<String>,
298 // LLVM optimizations for which we want to print remarks.
300 // Worker thread number
302 // The incremental compilation session directory, or None if we are not
303 // compiling incrementally
304 pub incr_comp_session_dir: Option<PathBuf>,
305 // Channel back to the main control thread to send messages to
306 pub tx: Sender<Message>,
309 struct HandlerFreeVars<'a> {
311 cgcx: &'a CodegenContext<'a>,
314 unsafe extern "C" fn report_inline_asm<'a, 'b>(cgcx: &'a CodegenContext<'a>,
317 drop(cgcx.tx.send(Message::InlineAsmError(cookie as u32, msg.to_string())));
320 unsafe extern "C" fn inline_asm_handler(diag: SMDiagnosticRef,
323 let HandlerFreeVars { cgcx, .. } = *(user as *const HandlerFreeVars);
325 let msg = llvm::build_string(|s| llvm::LLVMRustWriteSMDiagnosticToString(diag, s))
326 .expect("non-UTF8 SMDiagnostic");
328 report_inline_asm(cgcx, &msg, cookie);
331 unsafe extern "C" fn diagnostic_handler(info: DiagnosticInfoRef, user: *mut c_void) {
332 let HandlerFreeVars { llcx, cgcx } = *(user as *const HandlerFreeVars);
334 match llvm::diagnostic::Diagnostic::unpack(info) {
335 llvm::diagnostic::InlineAsm(inline) => {
336 report_inline_asm(cgcx,
337 &llvm::twine_to_string(inline.message),
341 llvm::diagnostic::Optimization(opt) => {
342 let enabled = match cgcx.remark {
344 SomePasses(ref v) => v.iter().any(|s| *s == opt.pass_name),
348 let loc = llvm::debug_loc_to_string(llcx, opt.debug_loc);
349 cgcx.handler.note_without_error(&format!("optimization {} for {} at {}: {}",
352 if loc.is_empty() { "[unknown]" } else { &*loc },
361 // Unsafe due to LLVM calls.
362 unsafe fn optimize_and_codegen(cgcx: &CodegenContext,
363 mtrans: ModuleTranslation,
365 config: ModuleConfig,
366 output_names: OutputFilenames)
367 -> Result<(), FatalError>
369 let llmod = mllvm.llmod;
370 let llcx = mllvm.llcx;
373 // llcx doesn't outlive this function, so we can put this on the stack.
374 let fv = HandlerFreeVars {
378 let fv = &fv as *const HandlerFreeVars as *mut c_void;
380 llvm::LLVMRustSetInlineAsmDiagnosticHandler(llcx, inline_asm_handler, fv);
381 llvm::LLVMContextSetDiagnosticHandler(llcx, diagnostic_handler, fv);
383 let module_name = Some(&mtrans.name[..]);
385 if config.emit_no_opt_bc {
386 let out = output_names.temp_path_ext("no-opt.bc", module_name);
387 let out = path2cstr(&out);
388 llvm::LLVMWriteBitcodeToFile(llmod, out.as_ptr());
391 if config.opt_level.is_some() {
392 // Create the two optimizing pass managers. These mirror what clang
393 // does, and are by populated by LLVM's default PassManagerBuilder.
394 // Each manager has a different set of passes, but they also share
395 // some common passes.
396 let fpm = llvm::LLVMCreateFunctionPassManagerForModule(llmod);
397 let mpm = llvm::LLVMCreatePassManager();
399 // If we're verifying or linting, add them to the function pass
401 let addpass = |pass_name: &str| {
402 let pass_name = CString::new(pass_name).unwrap();
403 let pass = llvm::LLVMRustFindAndCreatePass(pass_name.as_ptr());
407 let pass_manager = match llvm::LLVMRustPassKind(pass) {
408 llvm::PassKind::Function => fpm,
409 llvm::PassKind::Module => mpm,
410 llvm::PassKind::Other => {
411 cgcx.handler.err("Encountered LLVM pass kind we can't handle");
415 llvm::LLVMRustAddPass(pass_manager, pass);
419 if !config.no_verify { assert!(addpass("verify")); }
420 if !config.no_prepopulate_passes {
421 llvm::LLVMRustAddAnalysisPasses(tm, fpm, llmod);
422 llvm::LLVMRustAddAnalysisPasses(tm, mpm, llmod);
423 with_llvm_pmb(llmod, &config, &mut |b| {
424 llvm::LLVMPassManagerBuilderPopulateFunctionPassManager(b, fpm);
425 llvm::LLVMPassManagerBuilderPopulateModulePassManager(b, mpm);
429 for pass in &config.passes {
431 cgcx.handler.warn(&format!("unknown pass `{}`, ignoring",
436 for pass in &cgcx.plugin_passes {
438 cgcx.handler.err(&format!("a plugin asked for LLVM pass \
439 `{}` but LLVM does not \
440 recognize it", pass));
444 cgcx.handler.abort_if_errors();
446 // Finally, run the actual optimization passes
447 time(config.time_passes, &format!("llvm function passes [{}]", cgcx.worker), ||
448 llvm::LLVMRustRunFunctionPassManager(fpm, llmod));
449 time(config.time_passes, &format!("llvm module passes [{}]", cgcx.worker), ||
450 llvm::LLVMRunPassManager(mpm, llmod));
452 // Deallocate managers that we're now done with
453 llvm::LLVMDisposePassManager(fpm);
454 llvm::LLVMDisposePassManager(mpm);
457 time(cgcx.time_passes, "all lto passes", || {
458 let temp_no_opt_bc_filename =
459 output_names.temp_path_ext("no-opt.lto.bc", module_name);
464 &temp_no_opt_bc_filename)
466 if config.emit_lto_bc {
467 let out = output_names.temp_path_ext("lto.bc", module_name);
468 let out = path2cstr(&out);
469 llvm::LLVMWriteBitcodeToFile(llmod, out.as_ptr());
474 // A codegen-specific pass manager is used to generate object
475 // files for an LLVM module.
477 // Apparently each of these pass managers is a one-shot kind of
478 // thing, so we create a new one for each type of output. The
479 // pass manager passed to the closure should be ensured to not
480 // escape the closure itself, and the manager should only be
482 unsafe fn with_codegen<F, R>(tm: TargetMachineRef,
486 where F: FnOnce(PassManagerRef) -> R,
488 let cpm = llvm::LLVMCreatePassManager();
489 llvm::LLVMRustAddAnalysisPasses(tm, cpm, llmod);
490 llvm::LLVMRustAddLibraryInfo(cpm, llmod, no_builtins);
494 // Change what we write and cleanup based on whether obj files are
495 // just llvm bitcode. In that case write bitcode, and possibly
496 // delete the bitcode if it wasn't requested. Don't generate the
497 // machine code, instead copy the .o file from the .bc
498 let write_bc = config.emit_bc || config.obj_is_bitcode;
499 let rm_bc = !config.emit_bc && config.obj_is_bitcode;
500 let write_obj = config.emit_obj && !config.obj_is_bitcode;
501 let copy_bc_to_obj = config.emit_obj && config.obj_is_bitcode;
503 let bc_out = output_names.temp_path(OutputType::Bitcode, module_name);
504 let obj_out = output_names.temp_path(OutputType::Object, module_name);
507 let bc_out_c = path2cstr(&bc_out);
508 llvm::LLVMWriteBitcodeToFile(llmod, bc_out_c.as_ptr());
511 time(config.time_passes, &format!("codegen passes [{}]", cgcx.worker),
512 || -> Result<(), FatalError> {
514 let out = output_names.temp_path(OutputType::LlvmAssembly, module_name);
515 let out = path2cstr(&out);
517 extern "C" fn demangle_callback(input_ptr: *const c_char,
519 output_ptr: *mut c_char,
520 output_len: size_t) -> size_t {
522 slice::from_raw_parts(input_ptr as *const u8, input_len as usize)
525 let input = match str::from_utf8(input) {
530 let output = unsafe {
531 slice::from_raw_parts_mut(output_ptr as *mut u8, output_len as usize)
533 let mut cursor = io::Cursor::new(output);
535 let demangled = match rustc_demangle::try_demangle(input) {
540 if let Err(_) = write!(cursor, "{:#}", demangled) {
541 // Possible only if provided buffer is not big enough
545 cursor.position() as size_t
548 with_codegen(tm, llmod, config.no_builtins, |cpm| {
549 llvm::LLVMRustPrintModule(cpm, llmod, out.as_ptr(), demangle_callback);
550 llvm::LLVMDisposePassManager(cpm);
555 let path = output_names.temp_path(OutputType::Assembly, module_name);
557 // We can't use the same module for asm and binary output, because that triggers
558 // various errors like invalid IR or broken binaries, so we might have to clone the
559 // module to produce the asm output
560 let llmod = if config.emit_obj {
561 llvm::LLVMCloneModule(llmod)
565 with_codegen(tm, llmod, config.no_builtins, |cpm| {
566 write_output_file(cgcx.handler, tm, cpm, llmod, &path,
567 llvm::FileType::AssemblyFile)
570 llvm::LLVMDisposeModule(llmod);
575 with_codegen(tm, llmod, config.no_builtins, |cpm| {
576 write_output_file(cgcx.handler, tm, cpm, llmod, &obj_out,
577 llvm::FileType::ObjectFile)
585 debug!("copying bitcode {:?} to obj {:?}", bc_out, obj_out);
586 if let Err(e) = link_or_copy(&bc_out, &obj_out) {
587 cgcx.handler.err(&format!("failed to copy bitcode to object file: {}", e));
592 debug!("removing_bitcode {:?}", bc_out);
593 if let Err(e) = fs::remove_file(&bc_out) {
594 cgcx.handler.err(&format!("failed to remove bitcode: {}", e));
598 llvm::LLVMRustDisposeTargetMachine(tm);
603 pub fn cleanup_llvm(trans: &CrateTranslation) {
604 for module in trans.modules.iter() {
606 match module.source {
607 ModuleSource::Translated(llvm) => {
608 llvm::LLVMDisposeModule(llvm.llmod);
609 llvm::LLVMContextDispose(llvm.llcx);
611 ModuleSource::Preexisting(_) => {
618 pub fn run_passes(sess: &Session,
619 trans: &CrateTranslation,
620 output_types: &OutputTypes,
621 crate_output: &OutputFilenames) {
622 // It's possible that we have `codegen_units > 1` but only one item in
623 // `trans.modules`. We could theoretically proceed and do LTO in that
624 // case, but it would be confusing to have the validity of
625 // `-Z lto -C codegen-units=2` depend on details of the crate being
626 // compiled, so we complain regardless.
627 if sess.lto() && sess.opts.cg.codegen_units > 1 {
628 // This case is impossible to handle because LTO expects to be able
629 // to combine the entire crate and all its dependencies into a
630 // single compilation unit, but each codegen unit is in a separate
631 // LLVM context, so they can't easily be combined.
632 sess.fatal("can't perform LTO when using multiple codegen units");
636 assert!(trans.modules.len() == sess.opts.cg.codegen_units ||
637 sess.opts.debugging_opts.incremental.is_some() ||
638 !sess.opts.output_types.should_trans() ||
639 sess.opts.debugging_opts.no_trans);
641 let tm = create_target_machine(sess);
643 // Figure out what we actually need to build.
645 let mut modules_config = ModuleConfig::new(tm, sess.opts.cg.passes.clone());
646 let mut metadata_config = ModuleConfig::new(tm, vec![]);
647 let mut allocator_config = ModuleConfig::new(tm, vec![]);
649 if let Some(ref sanitizer) = sess.opts.debugging_opts.sanitizer {
651 Sanitizer::Address => {
652 modules_config.passes.push("asan".to_owned());
653 modules_config.passes.push("asan-module".to_owned());
655 Sanitizer::Memory => {
656 modules_config.passes.push("msan".to_owned())
658 Sanitizer::Thread => {
659 modules_config.passes.push("tsan".to_owned())
665 if sess.opts.debugging_opts.profile {
666 modules_config.passes.push("insert-gcov-profiling".to_owned())
669 modules_config.opt_level = Some(get_llvm_opt_level(sess.opts.optimize));
670 modules_config.opt_size = Some(get_llvm_opt_size(sess.opts.optimize));
672 // Save all versions of the bytecode if we're saving our temporaries.
673 if sess.opts.cg.save_temps {
674 modules_config.emit_no_opt_bc = true;
675 modules_config.emit_bc = true;
676 modules_config.emit_lto_bc = true;
677 metadata_config.emit_bc = true;
678 allocator_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;
704 allocator_config.emit_obj = true;
707 OutputType::Object => { modules_config.emit_obj = true; }
708 OutputType::Metadata => { metadata_config.emit_obj = true; }
710 modules_config.emit_obj = true;
711 metadata_config.emit_obj = true;
712 allocator_config.emit_obj = true;
714 OutputType::Mir => {}
715 OutputType::DepInfo => {}
719 modules_config.set_flags(sess, trans);
720 metadata_config.set_flags(sess, trans);
721 allocator_config.set_flags(sess, trans);
724 // Populate a buffer with a list of codegen threads. Items are processed in
725 // LIFO order, just because it's a tiny bit simpler that way. (The order
726 // doesn't actually matter.)
727 let mut work_items = Vec::with_capacity(1 + trans.modules.len());
730 let work = build_work_item(sess,
731 trans.metadata_module.clone(),
732 metadata_config.clone(),
733 crate_output.clone());
734 work_items.push(work);
737 if let Some(allocator) = trans.allocator_module.clone() {
738 let work = build_work_item(sess,
740 allocator_config.clone(),
741 crate_output.clone());
742 work_items.push(work);
745 for mtrans in trans.modules.iter() {
746 let work = build_work_item(sess,
748 modules_config.clone(),
749 crate_output.clone());
750 work_items.push(work);
753 if sess.opts.debugging_opts.incremental_info {
754 dump_incremental_data(&trans);
757 let client = sess.jobserver_from_env.clone().unwrap_or_else(|| {
758 // Pick a "reasonable maximum" if we don't otherwise have a jobserver in
759 // our environment, capping out at 32 so we don't take everything down
760 // by hogging the process run queue.
761 let num_workers = cmp::min(work_items.len() - 1, 32);
762 Client::new(num_workers).expect("failed to create jobserver")
765 execute_work(sess, work_items, client, &trans.exported_symbols, scope);
768 // If in incr. comp. mode, preserve the `.o` files for potential re-use
769 for mtrans in trans.modules.iter() {
770 let mut files = vec![];
772 if modules_config.emit_obj {
773 let path = crate_output.temp_path(OutputType::Object, Some(&mtrans.name));
774 files.push((OutputType::Object, path));
777 if modules_config.emit_bc {
778 let path = crate_output.temp_path(OutputType::Bitcode, Some(&mtrans.name));
779 files.push((OutputType::Bitcode, path));
782 save_trans_partition(sess, &mtrans.name, mtrans.symbol_name_hash, &files);
785 // All codegen is finished.
787 llvm::LLVMRustDisposeTargetMachine(tm);
790 // Produce final compile outputs.
791 let copy_gracefully = |from: &Path, to: &Path| {
792 if let Err(e) = fs::copy(from, to) {
793 sess.err(&format!("could not copy {:?} to {:?}: {}", from, to, e));
797 let copy_if_one_unit = |output_type: OutputType,
798 keep_numbered: bool| {
799 if trans.modules.len() == 1 {
800 // 1) Only one codegen unit. In this case it's no difficulty
801 // to copy `foo.0.x` to `foo.x`.
802 let module_name = Some(&trans.modules[0].name[..]);
803 let path = crate_output.temp_path(output_type, module_name);
804 copy_gracefully(&path,
805 &crate_output.path(output_type));
806 if !sess.opts.cg.save_temps && !keep_numbered {
807 // The user just wants `foo.x`, not `foo.#module-name#.x`.
811 let ext = crate_output.temp_path(output_type, None)
818 if crate_output.outputs.contains_key(&output_type) {
819 // 2) Multiple codegen units, with `--emit foo=some_name`. We have
820 // no good solution for this case, so warn the user.
821 sess.warn(&format!("ignoring emit path because multiple .{} files \
822 were produced", ext));
823 } else if crate_output.single_output_file.is_some() {
824 // 3) Multiple codegen units, with `-o some_name`. We have
825 // no good solution for this case, so warn the user.
826 sess.warn(&format!("ignoring -o because multiple .{} files \
827 were produced", ext));
829 // 4) Multiple codegen units, but no explicit name. We
830 // just leave the `foo.0.x` files in place.
831 // (We don't have to do any work in this case.)
836 // Flag to indicate whether the user explicitly requested bitcode.
837 // Otherwise, we produced it only as a temporary output, and will need
839 let mut user_wants_bitcode = false;
840 let mut user_wants_objects = false;
841 for output_type in output_types.keys() {
843 OutputType::Bitcode => {
844 user_wants_bitcode = true;
845 // Copy to .bc, but always keep the .0.bc. There is a later
846 // check to figure out if we should delete .0.bc files, or keep
847 // them for making an rlib.
848 copy_if_one_unit(OutputType::Bitcode, true);
850 OutputType::LlvmAssembly => {
851 copy_if_one_unit(OutputType::LlvmAssembly, false);
853 OutputType::Assembly => {
854 copy_if_one_unit(OutputType::Assembly, false);
856 OutputType::Object => {
857 user_wants_objects = true;
858 copy_if_one_unit(OutputType::Object, true);
861 OutputType::Metadata |
863 OutputType::DepInfo => {}
866 let user_wants_bitcode = user_wants_bitcode;
868 // Clean up unwanted temporary files.
870 // We create the following files by default:
871 // - #crate#.#module-name#.bc
872 // - #crate#.#module-name#.o
873 // - #crate#.crate.metadata.bc
874 // - #crate#.crate.metadata.o
875 // - #crate#.o (linked from crate.##.o)
876 // - #crate#.bc (copied from crate.##.bc)
877 // We may create additional files if requested by the user (through
878 // `-C save-temps` or `--emit=` flags).
880 if !sess.opts.cg.save_temps {
881 // Remove the temporary .#module-name#.o objects. If the user didn't
882 // explicitly request bitcode (with --emit=bc), and the bitcode is not
883 // needed for building an rlib, then we must remove .#module-name#.bc as
886 // Specific rules for keeping .#module-name#.bc:
887 // - If we're building an rlib (`needs_crate_bitcode`), then keep
889 // - If the user requested bitcode (`user_wants_bitcode`), and
890 // codegen_units > 1, then keep it.
891 // - If the user requested bitcode but codegen_units == 1, then we
892 // can toss .#module-name#.bc because we copied it to .bc earlier.
893 // - If we're not building an rlib and the user didn't request
894 // bitcode, then delete .#module-name#.bc.
895 // If you change how this works, also update back::link::link_rlib,
896 // where .#module-name#.bc files are (maybe) deleted after making an
898 let keep_numbered_bitcode = needs_crate_bitcode ||
899 (user_wants_bitcode && sess.opts.cg.codegen_units > 1);
901 let keep_numbered_objects = needs_crate_object ||
902 (user_wants_objects && sess.opts.cg.codegen_units > 1);
904 for module_name in trans.modules.iter().map(|m| Some(&m.name[..])) {
905 if modules_config.emit_obj && !keep_numbered_objects {
906 let path = crate_output.temp_path(OutputType::Object, module_name);
910 if modules_config.emit_bc && !keep_numbered_bitcode {
911 let path = crate_output.temp_path(OutputType::Bitcode, module_name);
916 if metadata_config.emit_bc && !user_wants_bitcode {
917 let path = crate_output.temp_path(OutputType::Bitcode,
918 Some(&trans.metadata_module.name));
921 if allocator_config.emit_bc && !user_wants_bitcode {
922 if let Some(ref module) = trans.allocator_module {
923 let path = crate_output.temp_path(OutputType::Bitcode,
930 // We leave the following files around by default:
932 // - #crate#.crate.metadata.o
934 // These are used in linking steps and will be cleaned up afterward.
936 // FIXME: time_llvm_passes support - does this use a global context or
938 if sess.opts.cg.codegen_units == 1 && sess.time_llvm_passes() {
939 unsafe { llvm::LLVMRustPrintPassTimings(); }
943 fn dump_incremental_data(trans: &CrateTranslation) {
945 for mtrans in trans.modules.iter() {
946 match mtrans.source {
947 ModuleSource::Preexisting(..) => reuse += 1,
948 ModuleSource::Translated(..) => (),
951 eprintln!("incremental: re-using {} out of {} modules", reuse, trans.modules.len());
955 mtrans: ModuleTranslation,
956 config: ModuleConfig,
957 output_names: OutputFilenames
960 fn build_work_item(sess: &Session,
961 mtrans: ModuleTranslation,
962 config: ModuleConfig,
963 output_names: OutputFilenames)
966 let mut config = config;
967 config.tm = create_target_machine(sess);
971 output_names: output_names
975 fn execute_work_item(cgcx: &CodegenContext, work_item: WorkItem)
976 -> Result<(), FatalError>
979 match work_item.mtrans.source {
980 ModuleSource::Translated(mllvm) => {
981 debug!("llvm-optimizing {:?}", work_item.mtrans.name);
982 optimize_and_codegen(cgcx,
986 work_item.output_names)?;
988 ModuleSource::Preexisting(wp) => {
989 let incr_comp_session_dir = cgcx.incr_comp_session_dir
992 let name = &work_item.mtrans.name;
993 for (kind, saved_file) in wp.saved_files {
994 let obj_out = work_item.output_names.temp_path(kind, Some(name));
995 let source_file = in_incr_comp_dir(&incr_comp_session_dir,
997 debug!("copying pre-existing module `{}` from {:?} to {}",
998 work_item.mtrans.name,
1001 match link_or_copy(&source_file, &obj_out) {
1004 cgcx.handler.err(&format!("unable to copy {} to {}: {}",
1005 source_file.display(),
1019 Token(io::Result<Acquired>),
1020 Diagnostic(Diagnostic),
1021 Done { success: bool },
1022 InlineAsmError(u32, String),
1026 pub struct Diagnostic {
1028 code: Option<String>,
1032 fn execute_work<'a>(sess: &'a Session,
1033 mut work_items: Vec<WorkItem>,
1035 exported_symbols: &'a ExportedSymbols,
1036 scope: &Scope<'a>) {
1037 let (tx, rx) = channel();
1038 let tx2 = tx.clone();
1040 // First up, convert our jobserver into a helper thread so we can use normal
1041 // mpsc channels to manage our messages and such. Once we've got the helper
1042 // thread then request `n-1` tokens because all of our work items are ready
1045 // Note that the `n-1` is here because we ourselves have a token (our
1046 // process) and we'll use that token to execute at least one unit of work.
1048 // After we've requested all these tokens then we'll, when we can, get
1049 // tokens on `rx` above which will get managed in the main loop below.
1050 let helper = jobserver.into_helper_thread(move |token| {
1051 drop(tx2.send(Message::Token(token)));
1052 }).expect("failed to spawn helper thread");
1053 for _ in 0..work_items.len() - 1 {
1054 helper.request_token();
1057 // This is the "main loop" of parallel work happening for parallel codegen.
1058 // It's here that we manage parallelism, schedule work, and work with
1059 // messages coming from clients.
1061 // Our channel `rx` created above is a channel of messages coming from our
1062 // various worker threads. This includes the jobserver helper thread above
1063 // as well as the work we'll spawn off here. Each turn of this loop starts
1064 // off by trying to spawn as much work as possible. After we've done that we
1065 // then wait for an event and dispatch accordingly once the event is
1066 // received. We're only done once all our work items have been drained and
1067 // nothing is running, at which point we return back up the stack.
1069 // ## Parallelism management
1071 // It's worth also touching on the management of parallelism here. We don't
1072 // want to just spawn a thread per work item because while that's optimal
1073 // parallelism it may overload a system with too many threads or violate our
1074 // configuration for the maximum amount of cpu to use for this process. To
1075 // manage this we use the `jobserver` crate.
1077 // Job servers are an artifact of GNU make and are used to manage
1078 // parallelism between processes. A jobserver is a glorified IPC semaphore
1079 // basically. Whenever we want to run some work we acquire the semaphore,
1080 // and whenever we're done with that work we release the semaphore. In this
1081 // manner we can ensure that the maximum number of parallel workers is
1082 // capped at any one point in time.
1084 // The jobserver protocol is a little unique, however. We, as a running
1085 // process, already have an ephemeral token assigned to us. We're not going
1086 // to be doing any productive work in this thread though so we're going to
1087 // give this token to a worker thread (there's no actual token to give, this
1088 // is just conceptually). As a result you'll see a few `+1` and `-1`
1089 // instances below, and it's about working with this ephemeral token.
1091 // To acquire tokens we have our `helper` thread above which is just in a
1092 // loop acquiring tokens and sending them to us. We then store all tokens
1093 // locally in a `tokens` vector once they're acquired. Currently we don't
1094 // literally send a token to a worker thread to assist with management of
1095 // our "ephemeral token".
1097 // As a result, our "spawn as much work as possible" basically means that we
1098 // fill up the `running` counter up to the limit of the `tokens` list.
1099 // Whenever we get a new token this'll mean a new unit of work is spawned,
1100 // and then whenever a unit of work finishes we relinquish a token, if we
1101 // had one, to maybe get re-acquired later.
1103 // Note that there's a race which may mean that we acquire more tokens than
1104 // we originally anticipated. For example let's say we have 2 units of work.
1105 // First we request one token from the helper thread and then we
1106 // immediately spawn one unit of work with our ephemeral token after. We may
1107 // then finish the first piece of work before the token is acquired, but we
1108 // can continue to spawn the second piece of work with our ephemeral token.
1109 // Before that work finishes, however, we may acquire a token. In that case
1110 // we actually wastefully acquired the token, so we relinquish it back to
1112 let mut tokens = Vec::new();
1113 let mut running = 0;
1114 while work_items.len() > 0 || running > 0 {
1116 // Spin up what work we can, only doing this while we've got available
1117 // parallelism slots and work left to spawn.
1118 while work_items.len() > 0 && running < tokens.len() + 1 {
1119 let item = work_items.pop().unwrap();
1120 let index = work_items.len();
1121 spawn_work(sess, exported_symbols, scope, tx.clone(), item, index);
1125 // Relinquish accidentally acquired extra tokens
1126 tokens.truncate(running.saturating_sub(1));
1128 match rx.recv().unwrap() {
1129 // Save the token locally and the next turn of the loop will use
1130 // this to spawn a new unit of work, or it may get dropped
1131 // immediately if we have no more work to spawn.
1132 Message::Token(token) => {
1133 tokens.push(token.expect("failed to acquire jobserver token"));
1136 // If a thread exits successfully then we drop a token associated
1137 // with that worker and update our `running` count. We may later
1138 // re-acquire a token to continue running more work. We may also not
1139 // actually drop a token here if the worker was running with an
1140 // "ephemeral token"
1142 // Note that if the thread failed that means it panicked, so we
1143 // abort immediately.
1144 Message::Done { success: true } => {
1148 Message::Done { success: false } => {
1149 sess.fatal("aborting due to worker thread panic");
1152 // Our worker wants us to emit an error message, so get ahold of our
1153 // `sess` and print it out
1154 Message::Diagnostic(diag) => {
1155 let handler = sess.diagnostic();
1158 handler.emit_with_code(&MultiSpan::new(),
1164 handler.emit(&MultiSpan::new(),
1170 Message::InlineAsmError(cookie, msg) => {
1171 match Mark::from_u32(cookie).expn_info() {
1172 Some(ei) => sess.span_err(ei.call_site, &msg),
1173 None => sess.err(&msg),
1177 // Sent to us after a worker sends us a batch of error messages, and
1178 // it's the point at which we check for errors.
1179 Message::AbortIfErrors => sess.diagnostic().abort_if_errors(),
1183 // Just in case, check this on the way out.
1184 sess.diagnostic().abort_if_errors();
1187 struct SharedEmitter {
1188 tx: Sender<Message>,
1191 impl Emitter for SharedEmitter {
1192 fn emit(&mut self, db: &DiagnosticBuilder) {
1193 drop(self.tx.send(Message::Diagnostic(Diagnostic {
1195 code: db.code.clone(),
1198 for child in &db.children {
1199 drop(self.tx.send(Message::Diagnostic(Diagnostic {
1200 msg: child.message(),
1205 drop(self.tx.send(Message::AbortIfErrors));
1209 fn spawn_work<'a>(sess: &'a Session,
1210 exported_symbols: &'a ExportedSymbols,
1212 tx: Sender<Message>,
1215 let plugin_passes = sess.plugin_llvm_passes.borrow().clone();
1216 let remark = sess.opts.cg.remark.clone();
1217 let incr_comp_session_dir = sess.incr_comp_session_dir_opt().map(|r| r.clone());
1218 let depth = time_depth();
1219 let lto = sess.lto();
1220 let crate_types = sess.crate_types.borrow().clone();
1221 let mut each_linked_rlib_for_lto = Vec::new();
1222 drop(link::each_linked_rlib(sess, &mut |cnum, path| {
1223 if link::ignored_for_lto(sess, cnum) {
1226 each_linked_rlib_for_lto.push((cnum, path.to_path_buf()));
1228 let time_passes = sess.time_passes();
1229 let no_landing_pads = sess.no_landing_pads();
1230 let opts = &sess.opts;
1232 scope.spawn(move || {
1233 set_time_depth(depth);
1235 // Set up a destructor which will fire off a message that we're done as
1238 tx: Sender<Message>,
1241 impl Drop for Bomb {
1242 fn drop(&mut self) {
1243 drop(self.tx.send(Message::Done { success: self.success }));
1246 let mut bomb = Bomb {
1251 // Set up our non-`Send` `CodegenContext` now that we're in a helper
1252 // thread and have all our info available to us.
1253 let emitter = SharedEmitter { tx: tx.clone() };
1254 let diag_handler = Handler::with_emitter(true, false, Box::new(emitter));
1256 let cgcx = CodegenContext {
1257 crate_types: crate_types,
1258 each_linked_rlib_for_lto: each_linked_rlib_for_lto,
1260 no_landing_pads: no_landing_pads,
1262 time_passes: time_passes,
1263 exported_symbols: exported_symbols,
1264 handler: &diag_handler,
1265 plugin_passes: plugin_passes,
1268 incr_comp_session_dir: incr_comp_session_dir,
1272 // Execute the work itself, and if it finishes successfully then flag
1273 // ourselves as a success as well.
1275 // Note that we ignore the result coming out of `execute_work_item`
1276 // which will tell us if the worker failed with a `FatalError`. If that
1277 // has happened, however, then a diagnostic was sent off to the main
1278 // thread, along with an `AbortIfErrors` message. In that case the main
1279 // thread is already exiting anyway most likely.
1281 // In any case, there's no need for us to take further action here, so
1282 // we just ignore the result and then send off our message saying that
1283 // we're done, which if `execute_work_item` failed is unlikely to be
1284 // seen by the main thread, but hey we might as well try anyway.
1285 drop(execute_work_item(&cgcx, work).is_err());
1286 bomb.success = true;
1290 pub fn run_assembler(sess: &Session, outputs: &OutputFilenames) {
1291 let (pname, mut cmd, _) = get_linker(sess);
1293 for arg in &sess.target.target.options.asm_args {
1297 cmd.arg("-c").arg("-o").arg(&outputs.path(OutputType::Object))
1298 .arg(&outputs.temp_path(OutputType::Assembly, None));
1299 debug!("{:?}", cmd);
1301 match cmd.output() {
1303 if !prog.status.success() {
1304 let mut note = prog.stderr.clone();
1305 note.extend_from_slice(&prog.stdout);
1307 sess.struct_err(&format!("linking with `{}` failed: {}",
1310 .note(&format!("{:?}", &cmd))
1311 .note(str::from_utf8(¬e[..]).unwrap())
1313 sess.abort_if_errors();
1317 sess.err(&format!("could not exec the linker `{}`: {}", pname, e));
1318 sess.abort_if_errors();
1323 pub unsafe fn with_llvm_pmb(llmod: ModuleRef,
1324 config: &ModuleConfig,
1325 f: &mut FnMut(llvm::PassManagerBuilderRef)) {
1326 // Create the PassManagerBuilder for LLVM. We configure it with
1327 // reasonable defaults and prepare it to actually populate the pass
1329 let builder = llvm::LLVMPassManagerBuilderCreate();
1330 let opt_level = config.opt_level.unwrap_or(llvm::CodeGenOptLevel::None);
1331 let opt_size = config.opt_size.unwrap_or(llvm::CodeGenOptSizeNone);
1332 let inline_threshold = config.inline_threshold;
1334 llvm::LLVMRustConfigurePassManagerBuilder(builder, opt_level,
1335 config.merge_functions,
1336 config.vectorize_slp,
1337 config.vectorize_loop);
1338 llvm::LLVMPassManagerBuilderSetSizeLevel(builder, opt_size as u32);
1340 if opt_size != llvm::CodeGenOptSizeNone {
1341 llvm::LLVMPassManagerBuilderSetDisableUnrollLoops(builder, 1);
1344 llvm::LLVMRustAddBuilderLibraryInfo(builder, llmod, config.no_builtins);
1346 // Here we match what clang does (kinda). For O0 we only inline
1347 // always-inline functions (but don't add lifetime intrinsics), at O1 we
1348 // inline with lifetime intrinsics, and O2+ we add an inliner with a
1349 // thresholds copied from clang.
1350 match (opt_level, opt_size, inline_threshold) {
1352 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, t as u32);
1354 (llvm::CodeGenOptLevel::Aggressive, ..) => {
1355 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 275);
1357 (_, llvm::CodeGenOptSizeDefault, _) => {
1358 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 75);
1360 (_, llvm::CodeGenOptSizeAggressive, _) => {
1361 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 25);
1363 (llvm::CodeGenOptLevel::None, ..) => {
1364 llvm::LLVMRustAddAlwaysInlinePass(builder, false);
1366 (llvm::CodeGenOptLevel::Less, ..) => {
1367 llvm::LLVMRustAddAlwaysInlinePass(builder, true);
1369 (llvm::CodeGenOptLevel::Default, ..) => {
1370 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 225);
1372 (llvm::CodeGenOptLevel::Other, ..) => {
1373 bug!("CodeGenOptLevel::Other selected")
1378 llvm::LLVMPassManagerBuilderDispose(builder);