1 // Copyright 2013-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
12 use back::link::{get_linker, remove};
13 use rustc_incremental::save_trans_partition;
14 use session::config::{OutputFilenames, Passes, SomePasses, AllPasses};
16 use session::config::{self, OutputType};
18 use llvm::{ModuleRef, TargetMachineRef, PassManagerRef, DiagnosticInfoRef, ContextRef};
19 use llvm::SMDiagnosticRef;
20 use {CrateTranslation, ModuleLlvm, ModuleSource, ModuleTranslation};
21 use util::common::time;
22 use util::common::path2cstr;
23 use util::fs::link_or_copy;
24 use errors::{self, Handler, Level, DiagnosticBuilder};
25 use errors::emitter::Emitter;
26 use syntax_pos::MultiSpan;
27 use context::{is_pie_binary, get_reloc_model};
29 use std::collections::HashMap;
30 use std::ffi::{CStr, CString};
32 use std::path::{Path, PathBuf};
34 use std::sync::{Arc, Mutex};
35 use std::sync::mpsc::channel;
37 use libc::{c_uint, c_void};
39 pub fn llvm_err(handler: &errors::Handler, msg: String) -> ! {
40 match llvm::last_error() {
41 Some(err) => panic!(handler.fatal(&format!("{}: {}", msg, err))),
42 None => panic!(handler.fatal(&msg)),
46 pub fn write_output_file(
47 handler: &errors::Handler,
48 target: llvm::TargetMachineRef,
49 pm: llvm::PassManagerRef,
52 file_type: llvm::FileType) {
54 let output_c = path2cstr(output);
55 let result = llvm::LLVMRustWriteOutputFile(
56 target, pm, m, output_c.as_ptr(), file_type);
57 if result.into_result().is_err() {
58 llvm_err(handler, format!("could not write output to {}", output.display()));
70 // We use an Arc instead of just returning a list of diagnostics from the
71 // child thread because we need to make sure that the messages are seen even
72 // if the child thread panics (for example, when `fatal` is called).
74 struct SharedEmitter {
75 buffer: Arc<Mutex<Vec<Diagnostic>>>,
79 fn new() -> SharedEmitter {
81 buffer: Arc::new(Mutex::new(Vec::new())),
85 fn dump(&mut self, handler: &Handler) {
86 let mut buffer = self.buffer.lock().unwrap();
87 for diag in &*buffer {
90 handler.emit_with_code(&MultiSpan::new(),
96 handler.emit(&MultiSpan::new(),
106 impl Emitter for SharedEmitter {
107 fn emit(&mut self, db: &DiagnosticBuilder) {
108 self.buffer.lock().unwrap().push(Diagnostic {
109 msg: db.message.to_string(),
110 code: db.code.clone(),
113 for child in &db.children {
114 self.buffer.lock().unwrap().push(Diagnostic {
115 msg: child.message.to_string(),
123 // On android, we by default compile for armv7 processors. This enables
124 // things like double word CAS instructions (rather than emulating them)
125 // which are *far* more efficient. This is obviously undesirable in some
126 // cases, so if any sort of target feature is specified we don't append v7
127 // to the feature list.
129 // On iOS only armv7 and newer are supported. So it is useful to
130 // get all hardware potential via VFP3 (hardware floating point)
131 // and NEON (SIMD) instructions supported by LLVM.
132 // Note that without those flags various linking errors might
133 // arise as some of intrinsics are converted into function calls
134 // and nobody provides implementations those functions
135 fn target_feature(sess: &Session) -> String {
136 format!("{},{}", sess.target.target.options.features, sess.opts.cg.target_feature)
139 fn get_llvm_opt_level(optimize: config::OptLevel) -> llvm::CodeGenOptLevel {
141 config::OptLevel::No => llvm::CodeGenOptLevel::None,
142 config::OptLevel::Less => llvm::CodeGenOptLevel::Less,
143 config::OptLevel::Default => llvm::CodeGenOptLevel::Default,
144 config::OptLevel::Aggressive => llvm::CodeGenOptLevel::Aggressive,
145 _ => llvm::CodeGenOptLevel::Default,
149 fn get_llvm_opt_size(optimize: config::OptLevel) -> llvm::CodeGenOptSize {
151 config::OptLevel::Size => llvm::CodeGenOptSizeDefault,
152 config::OptLevel::SizeMin => llvm::CodeGenOptSizeAggressive,
153 _ => llvm::CodeGenOptSizeNone,
157 pub fn create_target_machine(sess: &Session) -> TargetMachineRef {
158 let reloc_model = get_reloc_model(sess);
160 let opt_level = get_llvm_opt_level(sess.opts.optimize);
161 let use_softfp = sess.opts.cg.soft_float;
163 let ffunction_sections = sess.target.target.options.function_sections;
164 let fdata_sections = ffunction_sections;
166 let code_model_arg = match sess.opts.cg.code_model {
167 Some(ref s) => &s[..],
168 None => &sess.target.target.options.code_model[..],
171 let code_model = match code_model_arg {
172 "default" => llvm::CodeModel::Default,
173 "small" => llvm::CodeModel::Small,
174 "kernel" => llvm::CodeModel::Kernel,
175 "medium" => llvm::CodeModel::Medium,
176 "large" => llvm::CodeModel::Large,
178 sess.err(&format!("{:?} is not a valid code model",
182 sess.abort_if_errors();
187 let triple = &sess.target.target.llvm_target;
190 let triple = CString::new(triple.as_bytes()).unwrap();
191 let cpu = match sess.opts.cg.target_cpu {
193 None => &*sess.target.target.options.cpu
195 let cpu = CString::new(cpu.as_bytes()).unwrap();
196 let features = CString::new(target_feature(sess).as_bytes()).unwrap();
197 llvm::LLVMRustCreateTargetMachine(
198 triple.as_ptr(), cpu.as_ptr(), features.as_ptr(),
210 llvm_err(sess.diagnostic(),
211 format!("Could not create LLVM TargetMachine for triple: {}",
212 triple).to_string());
219 /// Module-specific configuration for `optimize_and_codegen`.
221 pub struct ModuleConfig {
222 /// LLVM TargetMachine to use for codegen.
223 tm: TargetMachineRef,
224 /// Names of additional optimization passes to run.
226 /// Some(level) to optimize at a certain level, or None to run
227 /// absolutely no optimizations (used for the metadata module).
228 opt_level: Option<llvm::CodeGenOptLevel>,
230 /// Some(level) to optimize binary size, or None to not affect program size.
231 opt_size: Option<llvm::CodeGenOptSize>,
233 // Flags indicating which outputs to produce.
234 emit_no_opt_bc: bool,
240 // Miscellaneous flags. These are mostly copied from command-line
243 no_prepopulate_passes: bool,
246 vectorize_loop: bool,
248 merge_functions: bool,
249 inline_threshold: Option<usize>,
250 // Instead of creating an object file by doing LLVM codegen, just
251 // make the object file bitcode. Provides easy compatibility with
252 // emscripten's ecc compiler, when used as the linker.
253 obj_is_bitcode: bool,
256 unsafe impl Send for ModuleConfig { }
259 fn new(tm: TargetMachineRef, passes: Vec<String>) -> ModuleConfig {
266 emit_no_opt_bc: false,
272 obj_is_bitcode: false,
275 no_prepopulate_passes: false,
278 vectorize_loop: false,
279 vectorize_slp: false,
280 merge_functions: false,
281 inline_threshold: None
285 fn set_flags(&mut self, sess: &Session, trans: &CrateTranslation) {
286 self.no_verify = sess.no_verify();
287 self.no_prepopulate_passes = sess.opts.cg.no_prepopulate_passes;
288 self.no_builtins = trans.no_builtins;
289 self.time_passes = sess.time_passes();
290 self.inline_threshold = sess.opts.cg.inline_threshold;
291 self.obj_is_bitcode = sess.target.target.options.obj_is_bitcode;
293 // Copy what clang does by turning on loop vectorization at O2 and
294 // slp vectorization at O3. Otherwise configure other optimization aspects
295 // of this pass manager builder.
296 self.vectorize_loop = !sess.opts.cg.no_vectorize_loops &&
297 (sess.opts.optimize == config::OptLevel::Default ||
298 sess.opts.optimize == config::OptLevel::Aggressive);
299 self.vectorize_slp = !sess.opts.cg.no_vectorize_slp &&
300 sess.opts.optimize == config::OptLevel::Aggressive;
302 self.merge_functions = sess.opts.optimize == config::OptLevel::Default ||
303 sess.opts.optimize == config::OptLevel::Aggressive;
307 /// Additional resources used by optimize_and_codegen (not module specific)
308 struct CodegenContext<'a> {
309 // Extra resources used for LTO: (sess, reachable). This will be `None`
310 // when running in a worker thread.
311 lto_ctxt: Option<(&'a Session, &'a [String])>,
312 // Handler to use for diagnostics produced during codegen.
313 handler: &'a Handler,
314 // LLVM passes added by plugins.
315 plugin_passes: Vec<String>,
316 // LLVM optimizations for which we want to print remarks.
318 // Worker thread number
320 // Directory where incremental data is stored (if any)
321 incremental: Option<PathBuf>,
324 impl<'a> CodegenContext<'a> {
325 fn new_with_session(sess: &'a Session, reachable: &'a [String]) -> CodegenContext<'a> {
327 lto_ctxt: Some((sess, reachable)),
328 handler: sess.diagnostic(),
329 plugin_passes: sess.plugin_llvm_passes.borrow().clone(),
330 remark: sess.opts.cg.remark.clone(),
332 incremental: sess.opts.incremental.clone(),
337 struct HandlerFreeVars<'a> {
339 cgcx: &'a CodegenContext<'a>,
342 unsafe extern "C" fn report_inline_asm<'a, 'b>(cgcx: &'a CodegenContext<'a>,
345 use syntax_pos::ExpnId;
347 match cgcx.lto_ctxt {
349 sess.codemap().with_expn_info(ExpnId::from_u32(cookie), |info| match info {
350 Some(ei) => sess.span_err(ei.call_site, msg),
351 None => sess.err(msg),
356 cgcx.handler.struct_err(msg)
357 .note("build without -C codegen-units for more exact errors")
363 unsafe extern "C" fn inline_asm_handler(diag: SMDiagnosticRef,
366 let HandlerFreeVars { cgcx, .. } = *(user as *const HandlerFreeVars);
368 let msg = llvm::build_string(|s| llvm::LLVMRustWriteSMDiagnosticToString(diag, s))
369 .expect("non-UTF8 SMDiagnostic");
371 report_inline_asm(cgcx, &msg[..], cookie);
374 unsafe extern "C" fn diagnostic_handler(info: DiagnosticInfoRef, user: *mut c_void) {
375 let HandlerFreeVars { llcx, cgcx } = *(user as *const HandlerFreeVars);
377 match llvm::diagnostic::Diagnostic::unpack(info) {
378 llvm::diagnostic::InlineAsm(inline) => {
379 report_inline_asm(cgcx,
380 &llvm::twine_to_string(inline.message),
384 llvm::diagnostic::Optimization(opt) => {
385 let pass_name = str::from_utf8(CStr::from_ptr(opt.pass_name).to_bytes())
387 .expect("got a non-UTF8 pass name from LLVM");
388 let enabled = match cgcx.remark {
390 SomePasses(ref v) => v.iter().any(|s| *s == pass_name),
394 let loc = llvm::debug_loc_to_string(llcx, opt.debug_loc);
395 cgcx.handler.note_without_error(&format!("optimization {} for {} at {}: {}",
398 if loc.is_empty() { "[unknown]" } else { &*loc },
399 llvm::twine_to_string(opt.message)));
407 // Unsafe due to LLVM calls.
408 unsafe fn optimize_and_codegen(cgcx: &CodegenContext,
409 mtrans: ModuleTranslation,
411 config: ModuleConfig,
412 output_names: OutputFilenames) {
413 let llmod = mllvm.llmod;
414 let llcx = mllvm.llcx;
417 // llcx doesn't outlive this function, so we can put this on the stack.
418 let fv = HandlerFreeVars {
422 let fv = &fv as *const HandlerFreeVars as *mut c_void;
424 llvm::LLVMRustSetInlineAsmDiagnosticHandler(llcx, inline_asm_handler, fv);
425 llvm::LLVMContextSetDiagnosticHandler(llcx, diagnostic_handler, fv);
427 let module_name = Some(&mtrans.name[..]);
429 if config.emit_no_opt_bc {
430 let out = output_names.temp_path_ext("no-opt.bc", module_name);
431 let out = path2cstr(&out);
432 llvm::LLVMWriteBitcodeToFile(llmod, out.as_ptr());
435 if config.opt_level.is_some() {
436 // Create the two optimizing pass managers. These mirror what clang
437 // does, and are by populated by LLVM's default PassManagerBuilder.
438 // Each manager has a different set of passes, but they also share
439 // some common passes.
440 let fpm = llvm::LLVMCreateFunctionPassManagerForModule(llmod);
441 let mpm = llvm::LLVMCreatePassManager();
443 // If we're verifying or linting, add them to the function pass
445 let addpass = |pass_name: &str| {
446 let pass_name = CString::new(pass_name).unwrap();
447 let pass = llvm::LLVMRustFindAndCreatePass(pass_name.as_ptr());
451 let pass_manager = match llvm::LLVMRustPassKind(pass) {
452 llvm::PassKind::Function => fpm,
453 llvm::PassKind::Module => mpm,
454 llvm::PassKind::Other => {
455 cgcx.handler.err("Encountered LLVM pass kind we can't handle");
459 llvm::LLVMRustAddPass(pass_manager, pass);
463 if !config.no_verify { assert!(addpass("verify")); }
464 if !config.no_prepopulate_passes {
465 llvm::LLVMRustAddAnalysisPasses(tm, fpm, llmod);
466 llvm::LLVMRustAddAnalysisPasses(tm, mpm, llmod);
467 with_llvm_pmb(llmod, &config, &mut |b| {
468 llvm::LLVMPassManagerBuilderPopulateFunctionPassManager(b, fpm);
469 llvm::LLVMPassManagerBuilderPopulateModulePassManager(b, mpm);
473 for pass in &config.passes {
475 cgcx.handler.warn(&format!("unknown pass `{}`, ignoring",
480 for pass in &cgcx.plugin_passes {
482 cgcx.handler.err(&format!("a plugin asked for LLVM pass \
483 `{}` but LLVM does not \
484 recognize it", pass));
488 cgcx.handler.abort_if_errors();
490 // Finally, run the actual optimization passes
491 time(config.time_passes, &format!("llvm function passes [{}]", cgcx.worker), ||
492 llvm::LLVMRustRunFunctionPassManager(fpm, llmod));
493 time(config.time_passes, &format!("llvm module passes [{}]", cgcx.worker), ||
494 llvm::LLVMRunPassManager(mpm, llmod));
496 // Deallocate managers that we're now done with
497 llvm::LLVMDisposePassManager(fpm);
498 llvm::LLVMDisposePassManager(mpm);
500 match cgcx.lto_ctxt {
501 Some((sess, reachable)) if sess.lto() => {
502 time(sess.time_passes(), "all lto passes", || {
503 let temp_no_opt_bc_filename =
504 output_names.temp_path_ext("no-opt.lto.bc", module_name);
510 &temp_no_opt_bc_filename);
512 if config.emit_lto_bc {
513 let out = output_names.temp_path_ext("lto.bc", module_name);
514 let out = path2cstr(&out);
515 llvm::LLVMWriteBitcodeToFile(llmod, out.as_ptr());
522 // A codegen-specific pass manager is used to generate object
523 // files for an LLVM module.
525 // Apparently each of these pass managers is a one-shot kind of
526 // thing, so we create a new one for each type of output. The
527 // pass manager passed to the closure should be ensured to not
528 // escape the closure itself, and the manager should only be
530 unsafe fn with_codegen<F>(tm: TargetMachineRef,
534 F: FnOnce(PassManagerRef),
536 let cpm = llvm::LLVMCreatePassManager();
537 llvm::LLVMRustAddAnalysisPasses(tm, cpm, llmod);
538 llvm::LLVMRustAddLibraryInfo(cpm, llmod, no_builtins);
542 // Change what we write and cleanup based on whether obj files are
543 // just llvm bitcode. In that case write bitcode, and possibly
544 // delete the bitcode if it wasn't requested. Don't generate the
545 // machine code, instead copy the .o file from the .bc
546 let write_bc = config.emit_bc || config.obj_is_bitcode;
547 let rm_bc = !config.emit_bc && config.obj_is_bitcode;
548 let write_obj = config.emit_obj && !config.obj_is_bitcode;
549 let copy_bc_to_obj = config.emit_obj && config.obj_is_bitcode;
551 let bc_out = output_names.temp_path(OutputType::Bitcode, module_name);
552 let obj_out = output_names.temp_path(OutputType::Object, module_name);
555 let bc_out_c = path2cstr(&bc_out);
556 llvm::LLVMWriteBitcodeToFile(llmod, bc_out_c.as_ptr());
559 time(config.time_passes, &format!("codegen passes [{}]", cgcx.worker), || {
561 let out = output_names.temp_path(OutputType::LlvmAssembly, module_name);
562 let out = path2cstr(&out);
563 with_codegen(tm, llmod, config.no_builtins, |cpm| {
564 llvm::LLVMRustPrintModule(cpm, llmod, out.as_ptr());
565 llvm::LLVMDisposePassManager(cpm);
570 let path = output_names.temp_path(OutputType::Assembly, module_name);
572 // We can't use the same module for asm and binary output, because that triggers
573 // various errors like invalid IR or broken binaries, so we might have to clone the
574 // module to produce the asm output
575 let llmod = if config.emit_obj {
576 llvm::LLVMCloneModule(llmod)
580 with_codegen(tm, llmod, config.no_builtins, |cpm| {
581 write_output_file(cgcx.handler, tm, cpm, llmod, &path,
582 llvm::FileType::AssemblyFile);
585 llvm::LLVMDisposeModule(llmod);
590 with_codegen(tm, llmod, config.no_builtins, |cpm| {
591 write_output_file(cgcx.handler, tm, cpm, llmod, &obj_out,
592 llvm::FileType::ObjectFile);
598 debug!("copying bitcode {:?} to obj {:?}", bc_out, obj_out);
599 if let Err(e) = link_or_copy(&bc_out, &obj_out) {
600 cgcx.handler.err(&format!("failed to copy bitcode to object file: {}", e));
605 debug!("removing_bitcode {:?}", bc_out);
606 if let Err(e) = fs::remove_file(&bc_out) {
607 cgcx.handler.err(&format!("failed to remove bitcode: {}", e));
611 llvm::LLVMRustDisposeTargetMachine(tm);
615 pub fn cleanup_llvm(trans: &CrateTranslation) {
616 for module in trans.modules.iter() {
618 match module.source {
619 ModuleSource::Translated(llvm) => {
620 llvm::LLVMDisposeModule(llvm.llmod);
621 llvm::LLVMContextDispose(llvm.llcx);
623 ModuleSource::Preexisting(_) => {
630 pub fn run_passes(sess: &Session,
631 trans: &CrateTranslation,
632 output_types: &HashMap<OutputType, Option<PathBuf>>,
633 crate_output: &OutputFilenames) {
634 // It's possible that we have `codegen_units > 1` but only one item in
635 // `trans.modules`. We could theoretically proceed and do LTO in that
636 // case, but it would be confusing to have the validity of
637 // `-Z lto -C codegen-units=2` depend on details of the crate being
638 // compiled, so we complain regardless.
639 if sess.lto() && sess.opts.cg.codegen_units > 1 {
640 // This case is impossible to handle because LTO expects to be able
641 // to combine the entire crate and all its dependencies into a
642 // single compilation unit, but each codegen unit is in a separate
643 // LLVM context, so they can't easily be combined.
644 sess.fatal("can't perform LTO when using multiple codegen units");
648 assert!(trans.modules.len() == sess.opts.cg.codegen_units ||
649 sess.opts.debugging_opts.incremental.is_some());
651 let tm = create_target_machine(sess);
653 // Figure out what we actually need to build.
655 let mut modules_config = ModuleConfig::new(tm, sess.opts.cg.passes.clone());
656 let mut metadata_config = ModuleConfig::new(tm, vec!());
658 modules_config.opt_level = Some(get_llvm_opt_level(sess.opts.optimize));
659 modules_config.opt_size = Some(get_llvm_opt_size(sess.opts.optimize));
661 // Save all versions of the bytecode if we're saving our temporaries.
662 if sess.opts.cg.save_temps {
663 modules_config.emit_no_opt_bc = true;
664 modules_config.emit_bc = true;
665 modules_config.emit_lto_bc = true;
666 metadata_config.emit_bc = true;
669 // Emit bitcode files for the crate if we're emitting an rlib.
670 // Whenever an rlib is created, the bitcode is inserted into the
671 // archive in order to allow LTO against it.
672 let needs_crate_bitcode =
673 sess.crate_types.borrow().contains(&config::CrateTypeRlib) &&
674 sess.opts.output_types.contains_key(&OutputType::Exe);
675 let needs_crate_object =
676 sess.opts.output_types.contains_key(&OutputType::Exe);
677 if needs_crate_bitcode {
678 modules_config.emit_bc = true;
681 for output_type in output_types.keys() {
683 OutputType::Bitcode => { modules_config.emit_bc = true; },
684 OutputType::LlvmAssembly => { modules_config.emit_ir = true; },
685 OutputType::Assembly => {
686 modules_config.emit_asm = true;
687 // If we're not using the LLVM assembler, this function
688 // could be invoked specially with output_type_assembly, so
689 // in this case we still want the metadata object file.
690 if !sess.opts.output_types.contains_key(&OutputType::Assembly) {
691 metadata_config.emit_obj = true;
694 OutputType::Object => { modules_config.emit_obj = true; },
696 modules_config.emit_obj = true;
697 metadata_config.emit_obj = true;
699 OutputType::DepInfo => {}
703 modules_config.set_flags(sess, trans);
704 metadata_config.set_flags(sess, trans);
707 // Populate a buffer with a list of codegen threads. Items are processed in
708 // LIFO order, just because it's a tiny bit simpler that way. (The order
709 // doesn't actually matter.)
710 let mut work_items = Vec::with_capacity(1 + trans.modules.len());
713 let work = build_work_item(sess,
714 trans.metadata_module.clone(),
715 metadata_config.clone(),
716 crate_output.clone());
717 work_items.push(work);
720 for mtrans in trans.modules.iter() {
721 let work = build_work_item(sess,
723 modules_config.clone(),
724 crate_output.clone());
725 work_items.push(work);
728 // Process the work items, optionally using worker threads.
729 // NOTE: This code is not really adapted to incremental compilation where
730 // the compiler decides the number of codegen units (and will
731 // potentially create hundreds of them).
732 let num_workers = work_items.len() - 1;
733 if num_workers == 1 {
734 run_work_singlethreaded(sess, &trans.reachable, work_items);
736 run_work_multithreaded(sess, work_items, num_workers);
739 // If in incr. comp. mode, preserve the `.o` files for potential re-use
740 for mtrans in trans.modules.iter() {
741 let mut files = vec![];
743 if modules_config.emit_obj {
744 let path = crate_output.temp_path(OutputType::Object, Some(&mtrans.name));
745 files.push((OutputType::Object, path));
748 if modules_config.emit_bc {
749 let path = crate_output.temp_path(OutputType::Bitcode, Some(&mtrans.name));
750 files.push((OutputType::Bitcode, path));
753 save_trans_partition(sess, &mtrans.name, mtrans.symbol_name_hash, &files);
756 // All codegen is finished.
758 llvm::LLVMRustDisposeTargetMachine(tm);
761 // Produce final compile outputs.
762 let copy_gracefully = |from: &Path, to: &Path| {
763 if let Err(e) = fs::copy(from, to) {
764 sess.err(&format!("could not copy {:?} to {:?}: {}", from, to, e));
768 let copy_if_one_unit = |output_type: OutputType,
769 keep_numbered: bool| {
770 if trans.modules.len() == 1 {
771 // 1) Only one codegen unit. In this case it's no difficulty
772 // to copy `foo.0.x` to `foo.x`.
773 let module_name = Some(&(trans.modules[0].name)[..]);
774 let path = crate_output.temp_path(output_type, module_name);
775 copy_gracefully(&path,
776 &crate_output.path(output_type));
777 if !sess.opts.cg.save_temps && !keep_numbered {
778 // The user just wants `foo.x`, not `foo.#module-name#.x`.
782 let ext = crate_output.temp_path(output_type, None)
789 if crate_output.outputs.contains_key(&output_type) {
790 // 2) Multiple codegen units, with `--emit foo=some_name`. We have
791 // no good solution for this case, so warn the user.
792 sess.warn(&format!("ignoring emit path because multiple .{} files \
793 were produced", ext));
794 } else if crate_output.single_output_file.is_some() {
795 // 3) Multiple codegen units, with `-o some_name`. We have
796 // no good solution for this case, so warn the user.
797 sess.warn(&format!("ignoring -o because multiple .{} files \
798 were produced", ext));
800 // 4) Multiple codegen units, but no explicit name. We
801 // just leave the `foo.0.x` files in place.
802 // (We don't have to do any work in this case.)
807 // Flag to indicate whether the user explicitly requested bitcode.
808 // Otherwise, we produced it only as a temporary output, and will need
810 let mut user_wants_bitcode = false;
811 let mut user_wants_objects = false;
812 for output_type in output_types.keys() {
814 OutputType::Bitcode => {
815 user_wants_bitcode = true;
816 // Copy to .bc, but always keep the .0.bc. There is a later
817 // check to figure out if we should delete .0.bc files, or keep
818 // them for making an rlib.
819 copy_if_one_unit(OutputType::Bitcode, true);
821 OutputType::LlvmAssembly => {
822 copy_if_one_unit(OutputType::LlvmAssembly, false);
824 OutputType::Assembly => {
825 copy_if_one_unit(OutputType::Assembly, false);
827 OutputType::Object => {
828 user_wants_objects = true;
829 copy_if_one_unit(OutputType::Object, true);
832 OutputType::DepInfo => {}
835 let user_wants_bitcode = user_wants_bitcode;
837 // Clean up unwanted temporary files.
839 // We create the following files by default:
840 // - crate.#module-name#.bc
841 // - crate.#module-name#.o
842 // - crate.metadata.bc
843 // - crate.metadata.o
844 // - crate.o (linked from crate.##.o)
845 // - crate.bc (copied from crate.##.bc)
846 // We may create additional files if requested by the user (through
847 // `-C save-temps` or `--emit=` flags).
849 if !sess.opts.cg.save_temps {
850 // Remove the temporary .#module-name#.o objects. If the user didn't
851 // explicitly request bitcode (with --emit=bc), and the bitcode is not
852 // needed for building an rlib, then we must remove .#module-name#.bc as
855 // Specific rules for keeping .#module-name#.bc:
856 // - If we're building an rlib (`needs_crate_bitcode`), then keep
858 // - If the user requested bitcode (`user_wants_bitcode`), and
859 // codegen_units > 1, then keep it.
860 // - If the user requested bitcode but codegen_units == 1, then we
861 // can toss .#module-name#.bc because we copied it to .bc earlier.
862 // - If we're not building an rlib and the user didn't request
863 // bitcode, then delete .#module-name#.bc.
864 // If you change how this works, also update back::link::link_rlib,
865 // where .#module-name#.bc files are (maybe) deleted after making an
867 let keep_numbered_bitcode = needs_crate_bitcode ||
868 (user_wants_bitcode && sess.opts.cg.codegen_units > 1);
870 let keep_numbered_objects = needs_crate_object ||
871 (user_wants_objects && sess.opts.cg.codegen_units > 1);
873 for module_name in trans.modules.iter().map(|m| Some(&m.name[..])) {
874 if modules_config.emit_obj && !keep_numbered_objects {
875 let path = crate_output.temp_path(OutputType::Object, module_name);
879 if modules_config.emit_bc && !keep_numbered_bitcode {
880 let path = crate_output.temp_path(OutputType::Bitcode, module_name);
885 if metadata_config.emit_bc && !user_wants_bitcode {
886 let path = crate_output.temp_path(OutputType::Bitcode,
887 Some(&trans.metadata_module.name[..]));
892 // We leave the following files around by default:
894 // - crate.metadata.o
896 // These are used in linking steps and will be cleaned up afterward.
898 // FIXME: time_llvm_passes support - does this use a global context or
900 if sess.opts.cg.codegen_units == 1 && sess.time_llvm_passes() {
901 unsafe { llvm::LLVMRustPrintPassTimings(); }
906 mtrans: ModuleTranslation,
907 config: ModuleConfig,
908 output_names: OutputFilenames
911 fn build_work_item(sess: &Session,
912 mtrans: ModuleTranslation,
913 config: ModuleConfig,
914 output_names: OutputFilenames)
917 let mut config = config;
918 config.tm = create_target_machine(sess);
922 output_names: output_names
926 fn execute_work_item(cgcx: &CodegenContext,
927 work_item: WorkItem) {
929 match work_item.mtrans.source {
930 ModuleSource::Translated(mllvm) => {
931 debug!("llvm-optimizing {:?}", work_item.mtrans.name);
932 optimize_and_codegen(cgcx,
936 work_item.output_names);
938 ModuleSource::Preexisting(wp) => {
939 let incremental = cgcx.incremental.as_ref().unwrap();
940 let name = &work_item.mtrans.name;
941 for (kind, saved_file) in wp.saved_files {
942 let obj_out = work_item.output_names.temp_path(kind, Some(name));
943 let source_file = incremental.join(&saved_file);
944 debug!("copying pre-existing module `{}` from {:?} to {}",
945 work_item.mtrans.name,
948 match link_or_copy(&source_file, &obj_out) {
951 cgcx.handler.err(&format!("unable to copy {} to {}: {}",
952 source_file.display(),
963 fn run_work_singlethreaded(sess: &Session,
964 reachable: &[String],
965 work_items: Vec<WorkItem>) {
966 let cgcx = CodegenContext::new_with_session(sess, reachable);
968 // Since we're running single-threaded, we can pass the session to
969 // the proc, allowing `optimize_and_codegen` to perform LTO.
970 for work in work_items.into_iter().rev() {
971 execute_work_item(&cgcx, work);
975 fn run_work_multithreaded(sess: &Session,
976 work_items: Vec<WorkItem>,
977 num_workers: usize) {
978 assert!(num_workers > 0);
980 // Run some workers to process the work items.
981 let work_items_arc = Arc::new(Mutex::new(work_items));
982 let mut diag_emitter = SharedEmitter::new();
983 let mut futures = Vec::with_capacity(num_workers);
985 for i in 0..num_workers {
986 let work_items_arc = work_items_arc.clone();
987 let diag_emitter = diag_emitter.clone();
988 let plugin_passes = sess.plugin_llvm_passes.borrow().clone();
989 let remark = sess.opts.cg.remark.clone();
991 let (tx, rx) = channel();
992 let mut tx = Some(tx);
995 let incremental = sess.opts.incremental.clone();
997 thread::Builder::new().name(format!("codegen-{}", i)).spawn(move || {
998 let diag_handler = Handler::with_emitter(true, false, box diag_emitter);
1000 // Must construct cgcx inside the proc because it has non-Send
1002 let cgcx = CodegenContext {
1004 handler: &diag_handler,
1005 plugin_passes: plugin_passes,
1008 incremental: incremental,
1012 // Avoid holding the lock for the entire duration of the match.
1013 let maybe_work = work_items_arc.lock().unwrap().pop();
1016 execute_work_item(&cgcx, work);
1018 // Make sure to fail the worker so the main thread can
1019 // tell that there were errors.
1020 cgcx.handler.abort_if_errors();
1026 tx.take().unwrap().send(()).unwrap();
1030 let mut panicked = false;
1038 // Display any new diagnostics.
1039 diag_emitter.dump(sess.diagnostic());
1042 sess.fatal("aborting due to worker thread panic");
1046 pub fn run_assembler(sess: &Session, outputs: &OutputFilenames) {
1047 let (pname, mut cmd, _) = get_linker(sess);
1049 cmd.arg("-c").arg("-o").arg(&outputs.path(OutputType::Object))
1050 .arg(&outputs.temp_path(OutputType::Assembly, None));
1051 debug!("{:?}", cmd);
1053 match cmd.output() {
1055 if !prog.status.success() {
1056 let mut note = prog.stderr.clone();
1057 note.extend_from_slice(&prog.stdout);
1059 sess.struct_err(&format!("linking with `{}` failed: {}",
1062 .note(&format!("{:?}", &cmd))
1063 .note(str::from_utf8(¬e[..]).unwrap())
1065 sess.abort_if_errors();
1069 sess.err(&format!("could not exec the linker `{}`: {}", pname, e));
1070 sess.abort_if_errors();
1075 pub unsafe fn with_llvm_pmb(llmod: ModuleRef,
1076 config: &ModuleConfig,
1077 f: &mut FnMut(llvm::PassManagerBuilderRef)) {
1078 // Create the PassManagerBuilder for LLVM. We configure it with
1079 // reasonable defaults and prepare it to actually populate the pass
1081 let builder = llvm::LLVMPassManagerBuilderCreate();
1082 let opt_level = config.opt_level.unwrap_or(llvm::CodeGenOptLevel::None);
1083 let opt_size = config.opt_size.unwrap_or(llvm::CodeGenOptSizeNone);
1084 let inline_threshold = config.inline_threshold;
1086 llvm::LLVMRustConfigurePassManagerBuilder(builder, opt_level,
1087 config.merge_functions,
1088 config.vectorize_slp,
1089 config.vectorize_loop);
1090 llvm::LLVMPassManagerBuilderSetSizeLevel(builder, opt_size as u32);
1092 if opt_size != llvm::CodeGenOptSizeNone {
1093 llvm::LLVMPassManagerBuilderSetDisableUnrollLoops(builder, 1);
1096 llvm::LLVMRustAddBuilderLibraryInfo(builder, llmod, config.no_builtins);
1098 // Here we match what clang does (kinda). For O0 we only inline
1099 // always-inline functions (but don't add lifetime intrinsics), at O1 we
1100 // inline with lifetime intrinsics, and O2+ we add an inliner with a
1101 // thresholds copied from clang.
1102 match (opt_level, opt_size, inline_threshold) {
1103 (_, _, Some(t)) => {
1104 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, t as u32);
1106 (llvm::CodeGenOptLevel::Aggressive, _, _) => {
1107 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 275);
1109 (_, llvm::CodeGenOptSizeDefault, _) => {
1110 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 75);
1112 (_, llvm::CodeGenOptSizeAggressive, _) => {
1113 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 25);
1115 (llvm::CodeGenOptLevel::None, _, _) => {
1116 llvm::LLVMRustAddAlwaysInlinePass(builder, false);
1118 (llvm::CodeGenOptLevel::Less, _, _) => {
1119 llvm::LLVMRustAddAlwaysInlinePass(builder, true);
1121 (llvm::CodeGenOptLevel::Default, _, _) => {
1122 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 225);
1124 (llvm::CodeGenOptLevel::Other, _, _) => {
1125 bug!("CodeGenOptLevel::Other selected")
1130 llvm::LLVMPassManagerBuilderDispose(builder);