2 use crate::back::lto::ThinBuffer;
3 use crate::back::profiling::{
4 selfprofile_after_pass_callback, selfprofile_before_pass_callback, LlvmSelfProfiler,
9 use crate::llvm::{self, DiagnosticInfo, PassManager, SMDiagnostic};
11 use crate::type_::Type;
12 use crate::LlvmCodegenBackend;
13 use crate::ModuleLlvm;
14 use rustc_codegen_ssa::back::write::{BitcodeSection, CodegenContext, EmitObj, ModuleConfig};
15 use rustc_codegen_ssa::traits::*;
16 use rustc_codegen_ssa::{CompiledModule, ModuleCodegen};
17 use rustc_data_structures::small_c_str::SmallCStr;
18 use rustc_errors::{FatalError, Handler, Level};
19 use rustc_fs_util::{link_or_copy, path_to_c_string};
20 use rustc_hir::def_id::LOCAL_CRATE;
21 use rustc_middle::bug;
22 use rustc_middle::ty::TyCtxt;
23 use rustc_session::config::{self, Lto, OutputType, Passes, SanitizerSet, SwitchWithOptPath};
24 use rustc_session::Session;
25 use rustc_span::symbol::sym;
26 use rustc_span::InnerSpan;
27 use rustc_target::spec::{CodeModel, RelocModel};
30 use libc::{c_char, c_int, c_uint, c_void, size_t};
31 use std::ffi::CString;
33 use std::io::{self, Write};
34 use std::path::{Path, PathBuf};
39 pub fn llvm_err(handler: &rustc_errors::Handler, msg: &str) -> FatalError {
40 match llvm::last_error() {
41 Some(err) => handler.fatal(&format!("{}: {}", msg, err)),
42 None => handler.fatal(&msg),
46 pub fn write_output_file(
47 handler: &rustc_errors::Handler,
48 target: &'ll llvm::TargetMachine,
49 pm: &llvm::PassManager<'ll>,
52 file_type: llvm::FileType,
53 ) -> Result<(), FatalError> {
55 let output_c = path_to_c_string(output);
56 let result = llvm::LLVMRustWriteOutputFile(target, pm, m, output_c.as_ptr(), file_type);
57 result.into_result().map_err(|()| {
58 let msg = format!("could not write output to {}", output.display());
59 llvm_err(handler, &msg)
64 pub fn create_informational_target_machine(sess: &Session) -> &'static mut llvm::TargetMachine {
65 target_machine_factory(sess, config::OptLevel::No)()
66 .unwrap_or_else(|err| llvm_err(sess.diagnostic(), &err).raise())
69 pub fn create_target_machine(tcx: TyCtxt<'_>) -> &'static mut llvm::TargetMachine {
70 target_machine_factory(&tcx.sess, tcx.backend_optimization_level(LOCAL_CRATE))()
71 .unwrap_or_else(|err| llvm_err(tcx.sess.diagnostic(), &err).raise())
74 pub fn to_llvm_opt_settings(
75 cfg: config::OptLevel,
76 ) -> (llvm::CodeGenOptLevel, llvm::CodeGenOptSize) {
77 use self::config::OptLevel::*;
79 No => (llvm::CodeGenOptLevel::None, llvm::CodeGenOptSizeNone),
80 Less => (llvm::CodeGenOptLevel::Less, llvm::CodeGenOptSizeNone),
81 Default => (llvm::CodeGenOptLevel::Default, llvm::CodeGenOptSizeNone),
82 Aggressive => (llvm::CodeGenOptLevel::Aggressive, llvm::CodeGenOptSizeNone),
83 Size => (llvm::CodeGenOptLevel::Default, llvm::CodeGenOptSizeDefault),
84 SizeMin => (llvm::CodeGenOptLevel::Default, llvm::CodeGenOptSizeAggressive),
88 fn to_pass_builder_opt_level(cfg: config::OptLevel) -> llvm::PassBuilderOptLevel {
89 use config::OptLevel::*;
91 No => llvm::PassBuilderOptLevel::O0,
92 Less => llvm::PassBuilderOptLevel::O1,
93 Default => llvm::PassBuilderOptLevel::O2,
94 Aggressive => llvm::PassBuilderOptLevel::O3,
95 Size => llvm::PassBuilderOptLevel::Os,
96 SizeMin => llvm::PassBuilderOptLevel::Oz,
100 fn to_llvm_relocation_model(relocation_model: RelocModel) -> llvm::RelocModel {
101 match relocation_model {
102 RelocModel::Static => llvm::RelocModel::Static,
103 RelocModel::Pic => llvm::RelocModel::PIC,
104 RelocModel::DynamicNoPic => llvm::RelocModel::DynamicNoPic,
105 RelocModel::Ropi => llvm::RelocModel::ROPI,
106 RelocModel::Rwpi => llvm::RelocModel::RWPI,
107 RelocModel::RopiRwpi => llvm::RelocModel::ROPI_RWPI,
111 fn to_llvm_code_model(code_model: Option<CodeModel>) -> llvm::CodeModel {
113 Some(CodeModel::Tiny) => llvm::CodeModel::Tiny,
114 Some(CodeModel::Small) => llvm::CodeModel::Small,
115 Some(CodeModel::Kernel) => llvm::CodeModel::Kernel,
116 Some(CodeModel::Medium) => llvm::CodeModel::Medium,
117 Some(CodeModel::Large) => llvm::CodeModel::Large,
118 None => llvm::CodeModel::None,
122 pub fn target_machine_factory(
124 optlvl: config::OptLevel,
125 ) -> Arc<dyn Fn() -> Result<&'static mut llvm::TargetMachine, String> + Send + Sync> {
126 let reloc_model = to_llvm_relocation_model(sess.relocation_model());
128 let (opt_level, _) = to_llvm_opt_settings(optlvl);
129 let use_softfp = sess.opts.cg.soft_float;
131 let ffunction_sections =
132 sess.opts.debugging_opts.function_sections.unwrap_or(sess.target.options.function_sections);
133 let fdata_sections = ffunction_sections;
135 let code_model = to_llvm_code_model(sess.code_model());
137 let features = attributes::llvm_target_features(sess).collect::<Vec<_>>();
138 let mut singlethread = sess.target.options.singlethread;
140 // On the wasm target once the `atomics` feature is enabled that means that
141 // we're no longer single-threaded, or otherwise we don't want LLVM to
142 // lower atomic operations to single-threaded operations.
144 && sess.target.llvm_target.contains("wasm32")
145 && sess.target_features.contains(&sym::atomics)
147 singlethread = false;
150 let triple = SmallCStr::new(&sess.target.llvm_target);
151 let cpu = SmallCStr::new(llvm_util::target_cpu(sess));
152 let features = features.join(",");
153 let features = CString::new(features).unwrap();
154 let abi = SmallCStr::new(&sess.target.options.llvm_abiname);
155 let trap_unreachable = sess.target.options.trap_unreachable;
156 let emit_stack_size_section = sess.opts.debugging_opts.emit_stack_sizes;
158 let asm_comments = sess.asm_comments();
159 let relax_elf_relocations = sess.target.options.relax_elf_relocations;
161 let use_init_array = !sess
165 .unwrap_or(sess.target.options.use_ctors_section);
169 llvm::LLVMRustCreateTargetMachine(
183 emit_stack_size_section,
184 relax_elf_relocations,
190 format!("Could not create LLVM TargetMachine for triple: {}", triple.to_str().unwrap())
195 pub(crate) fn save_temp_bitcode(
196 cgcx: &CodegenContext<LlvmCodegenBackend>,
197 module: &ModuleCodegen<ModuleLlvm>,
200 if !cgcx.save_temps {
204 let ext = format!("{}.bc", name);
205 let cgu = Some(&module.name[..]);
206 let path = cgcx.output_filenames.temp_path_ext(&ext, cgu);
207 let cstr = path_to_c_string(&path);
208 let llmod = module.module_llvm.llmod();
209 llvm::LLVMWriteBitcodeToFile(llmod, cstr.as_ptr());
213 pub struct DiagnosticHandlers<'a> {
214 data: *mut (&'a CodegenContext<LlvmCodegenBackend>, &'a Handler),
215 llcx: &'a llvm::Context,
218 impl<'a> DiagnosticHandlers<'a> {
220 cgcx: &'a CodegenContext<LlvmCodegenBackend>,
221 handler: &'a Handler,
222 llcx: &'a llvm::Context,
224 let data = Box::into_raw(Box::new((cgcx, handler)));
226 llvm::LLVMRustSetInlineAsmDiagnosticHandler(llcx, inline_asm_handler, data.cast());
227 llvm::LLVMContextSetDiagnosticHandler(llcx, diagnostic_handler, data.cast());
229 DiagnosticHandlers { data, llcx }
233 impl<'a> Drop for DiagnosticHandlers<'a> {
235 use std::ptr::null_mut;
237 llvm::LLVMRustSetInlineAsmDiagnosticHandler(self.llcx, inline_asm_handler, null_mut());
238 llvm::LLVMContextSetDiagnosticHandler(self.llcx, diagnostic_handler, null_mut());
239 drop(Box::from_raw(self.data));
244 fn report_inline_asm(
245 cgcx: &CodegenContext<LlvmCodegenBackend>,
247 level: llvm::DiagnosticLevel,
249 source: Option<(String, Vec<InnerSpan>)>,
251 // In LTO build we may get srcloc values from other crates which are invalid
252 // since they use a different source map. To be safe we just suppress these
254 if matches!(cgcx.lto, Lto::Fat | Lto::Thin) {
257 let level = match level {
258 llvm::DiagnosticLevel::Error => Level::Error,
259 llvm::DiagnosticLevel::Warning => Level::Warning,
260 llvm::DiagnosticLevel::Note | llvm::DiagnosticLevel::Remark => Level::Note,
262 cgcx.diag_emitter.inline_asm_error(cookie as u32, msg, level, source);
265 unsafe extern "C" fn inline_asm_handler(diag: &SMDiagnostic, user: *const c_void, cookie: c_uint) {
269 let (cgcx, _) = *(user as *const (&CodegenContext<LlvmCodegenBackend>, &Handler));
271 // Recover the post-substitution assembly code from LLVM for better
273 let mut have_source = false;
274 let mut buffer = String::new();
275 let mut level = llvm::DiagnosticLevel::Error;
277 let mut ranges = [0; 8];
278 let mut num_ranges = ranges.len() / 2;
279 let msg = llvm::build_string(|msg| {
280 buffer = llvm::build_string(|buffer| {
281 have_source = llvm::LLVMRustUnpackSMDiagnostic(
291 .expect("non-UTF8 inline asm");
293 .expect("non-UTF8 SMDiagnostic");
295 let source = have_source.then(|| {
296 let mut spans = vec![InnerSpan::new(loc as usize, loc as usize)];
297 for i in 0..num_ranges {
298 spans.push(InnerSpan::new(ranges[i * 2] as usize, ranges[i * 2 + 1] as usize));
303 report_inline_asm(cgcx, msg, level, cookie, source);
306 unsafe extern "C" fn diagnostic_handler(info: &DiagnosticInfo, user: *mut c_void) {
310 let (cgcx, diag_handler) = *(user as *const (&CodegenContext<LlvmCodegenBackend>, &Handler));
312 match llvm::diagnostic::Diagnostic::unpack(info) {
313 llvm::diagnostic::InlineAsm(inline) => {
316 llvm::twine_to_string(inline.message),
323 llvm::diagnostic::Optimization(opt) => {
324 let enabled = match cgcx.remark {
326 Passes::Some(ref v) => v.iter().any(|s| *s == opt.pass_name),
330 diag_handler.note_without_error(&format!(
331 "optimization {} for {} at {}:{}:{}: {}",
341 llvm::diagnostic::PGO(diagnostic_ref) | llvm::diagnostic::Linker(diagnostic_ref) => {
342 let msg = llvm::build_string(|s| {
343 llvm::LLVMRustWriteDiagnosticInfoToString(diagnostic_ref, s)
345 .expect("non-UTF8 diagnostic");
346 diag_handler.warn(&msg);
348 llvm::diagnostic::Unsupported(diagnostic_ref) => {
349 let msg = llvm::build_string(|s| {
350 llvm::LLVMRustWriteDiagnosticInfoToString(diagnostic_ref, s)
352 .expect("non-UTF8 diagnostic");
353 diag_handler.err(&msg);
355 llvm::diagnostic::UnknownDiagnostic(..) => {}
359 fn get_pgo_gen_path(config: &ModuleConfig) -> Option<CString> {
360 match config.pgo_gen {
361 SwitchWithOptPath::Enabled(ref opt_dir_path) => {
362 let path = if let Some(dir_path) = opt_dir_path {
363 dir_path.join("default_%m.profraw")
365 PathBuf::from("default_%m.profraw")
368 Some(CString::new(format!("{}", path.display())).unwrap())
370 SwitchWithOptPath::Disabled => None,
374 fn get_pgo_use_path(config: &ModuleConfig) -> Option<CString> {
378 .map(|path_buf| CString::new(path_buf.to_string_lossy().as_bytes()).unwrap())
381 pub(crate) fn should_use_new_llvm_pass_manager(config: &ModuleConfig) -> bool {
382 // We only support the new pass manager starting with LLVM 9.
383 if llvm_util::get_major_version() < 9 {
387 // The new pass manager is disabled by default.
388 config.new_llvm_pass_manager
391 pub(crate) unsafe fn optimize_with_new_llvm_pass_manager(
392 cgcx: &CodegenContext<LlvmCodegenBackend>,
393 module: &ModuleCodegen<ModuleLlvm>,
394 config: &ModuleConfig,
395 opt_level: config::OptLevel,
396 opt_stage: llvm::OptStage,
399 opt_level != config::OptLevel::Size && opt_level != config::OptLevel::SizeMin;
400 let using_thin_buffers = opt_stage == llvm::OptStage::PreLinkThinLTO || config.bitcode_needed();
401 let pgo_gen_path = get_pgo_gen_path(config);
402 let pgo_use_path = get_pgo_use_path(config);
403 let is_lto = opt_stage == llvm::OptStage::ThinLTO || opt_stage == llvm::OptStage::FatLTO;
404 // Sanitizer instrumentation is only inserted during the pre-link optimization stage.
405 let sanitizer_options = if !is_lto {
406 Some(llvm::SanitizerOptions {
407 sanitize_address: config.sanitizer.contains(SanitizerSet::ADDRESS),
408 sanitize_address_recover: config.sanitizer_recover.contains(SanitizerSet::ADDRESS),
409 sanitize_memory: config.sanitizer.contains(SanitizerSet::MEMORY),
410 sanitize_memory_recover: config.sanitizer_recover.contains(SanitizerSet::MEMORY),
411 sanitize_memory_track_origins: config.sanitizer_memory_track_origins as c_int,
412 sanitize_thread: config.sanitizer.contains(SanitizerSet::THREAD),
418 let llvm_selfprofiler = if cgcx.prof.llvm_recording_enabled() {
419 let mut llvm_profiler = LlvmSelfProfiler::new(cgcx.prof.get_self_profiler().unwrap());
420 &mut llvm_profiler as *mut _ as *mut c_void
425 // FIXME: NewPM doesn't provide a facility to pass custom InlineParams.
426 // We would have to add upstream support for this first, before we can support
427 // config.inline_threshold and our more aggressive default thresholds.
428 // FIXME: NewPM uses an different and more explicit way to textually represent
429 // pass pipelines. It would probably make sense to expose this, but it would
430 // require a different format than the current -C passes.
431 llvm::LLVMRustOptimizeWithNewPassManager(
432 module.module_llvm.llmod(),
433 &*module.module_llvm.tm,
434 to_pass_builder_opt_level(opt_level),
436 config.no_prepopulate_passes,
437 config.verify_llvm_ir,
439 config.merge_functions,
441 config.vectorize_slp,
442 config.vectorize_loop,
444 config.emit_lifetime_markers,
445 sanitizer_options.as_ref(),
446 pgo_gen_path.as_ref().map_or(std::ptr::null(), |s| s.as_ptr()),
447 pgo_use_path.as_ref().map_or(std::ptr::null(), |s| s.as_ptr()),
449 selfprofile_before_pass_callback,
450 selfprofile_after_pass_callback,
454 // Unsafe due to LLVM calls.
455 pub(crate) unsafe fn optimize(
456 cgcx: &CodegenContext<LlvmCodegenBackend>,
457 diag_handler: &Handler,
458 module: &ModuleCodegen<ModuleLlvm>,
459 config: &ModuleConfig,
460 ) -> Result<(), FatalError> {
461 let _timer = cgcx.prof.generic_activity_with_arg("LLVM_module_optimize", &module.name[..]);
463 let llmod = module.module_llvm.llmod();
464 let llcx = &*module.module_llvm.llcx;
465 let tm = &*module.module_llvm.tm;
466 let _handlers = DiagnosticHandlers::new(cgcx, diag_handler, llcx);
468 let module_name = module.name.clone();
469 let module_name = Some(&module_name[..]);
471 if config.emit_no_opt_bc {
472 let out = cgcx.output_filenames.temp_path_ext("no-opt.bc", module_name);
473 let out = path_to_c_string(&out);
474 llvm::LLVMWriteBitcodeToFile(llmod, out.as_ptr());
477 if let Some(opt_level) = config.opt_level {
478 if should_use_new_llvm_pass_manager(config) {
479 let opt_stage = match cgcx.lto {
480 Lto::Fat => llvm::OptStage::PreLinkFatLTO,
481 Lto::Thin | Lto::ThinLocal => llvm::OptStage::PreLinkThinLTO,
482 _ if cgcx.opts.cg.linker_plugin_lto.enabled() => llvm::OptStage::PreLinkThinLTO,
483 _ => llvm::OptStage::PreLinkNoLTO,
485 optimize_with_new_llvm_pass_manager(cgcx, module, config, opt_level, opt_stage);
489 if cgcx.prof.llvm_recording_enabled() {
491 .warn("`-Z self-profile-events = llvm` requires `-Z new-llvm-pass-manager`");
494 // Create the two optimizing pass managers. These mirror what clang
495 // does, and are by populated by LLVM's default PassManagerBuilder.
496 // Each manager has a different set of passes, but they also share
497 // some common passes.
498 let fpm = llvm::LLVMCreateFunctionPassManagerForModule(llmod);
499 let mpm = llvm::LLVMCreatePassManager();
502 let find_pass = |pass_name: &str| {
503 let pass_name = SmallCStr::new(pass_name);
504 llvm::LLVMRustFindAndCreatePass(pass_name.as_ptr())
507 if config.verify_llvm_ir {
508 // Verification should run as the very first pass.
509 llvm::LLVMRustAddPass(fpm, find_pass("verify").unwrap());
512 let mut extra_passes = Vec::new();
513 let mut have_name_anon_globals_pass = false;
515 for pass_name in &config.passes {
516 if pass_name == "lint" {
517 // Linting should also be performed early, directly on the generated IR.
518 llvm::LLVMRustAddPass(fpm, find_pass("lint").unwrap());
522 if let Some(pass) = find_pass(pass_name) {
523 extra_passes.push(pass);
525 diag_handler.warn(&format!("unknown pass `{}`, ignoring", pass_name));
528 if pass_name == "name-anon-globals" {
529 have_name_anon_globals_pass = true;
533 add_sanitizer_passes(config, &mut extra_passes);
535 // Some options cause LLVM bitcode to be emitted, which uses ThinLTOBuffers, so we need
536 // to make sure we run LLVM's NameAnonGlobals pass when emitting bitcode; otherwise
537 // we'll get errors in LLVM.
538 let using_thin_buffers = config.bitcode_needed();
539 if !config.no_prepopulate_passes {
540 llvm::LLVMAddAnalysisPasses(tm, fpm);
541 llvm::LLVMAddAnalysisPasses(tm, mpm);
542 let opt_level = to_llvm_opt_settings(opt_level).0;
543 let prepare_for_thin_lto = cgcx.lto == Lto::Thin
544 || cgcx.lto == Lto::ThinLocal
545 || (cgcx.lto != Lto::Fat && cgcx.opts.cg.linker_plugin_lto.enabled());
546 with_llvm_pmb(llmod, &config, opt_level, prepare_for_thin_lto, &mut |b| {
547 llvm::LLVMRustAddLastExtensionPasses(
549 extra_passes.as_ptr(),
550 extra_passes.len() as size_t,
552 llvm::LLVMPassManagerBuilderPopulateFunctionPassManager(b, fpm);
553 llvm::LLVMPassManagerBuilderPopulateModulePassManager(b, mpm);
556 have_name_anon_globals_pass = have_name_anon_globals_pass || prepare_for_thin_lto;
557 if using_thin_buffers && !prepare_for_thin_lto {
558 llvm::LLVMRustAddPass(mpm, find_pass("name-anon-globals").unwrap());
559 have_name_anon_globals_pass = true;
562 // If we don't use the standard pipeline, directly populate the MPM
563 // with the extra passes.
564 for pass in extra_passes {
565 llvm::LLVMRustAddPass(mpm, pass);
569 if using_thin_buffers && !have_name_anon_globals_pass {
570 // As described above, this will probably cause an error in LLVM
571 if config.no_prepopulate_passes {
573 "The current compilation is going to use thin LTO buffers \
574 without running LLVM's NameAnonGlobals pass. \
575 This will likely cause errors in LLVM. Consider adding \
576 -C passes=name-anon-globals to the compiler command line.",
580 "We are using thin LTO buffers without running the NameAnonGlobals pass. \
581 This will likely cause errors in LLVM and should never happen."
587 diag_handler.abort_if_errors();
589 // Finally, run the actual optimization passes
591 let _timer = cgcx.prof.extra_verbose_generic_activity(
592 "LLVM_module_optimize_function_passes",
595 llvm::LLVMRustRunFunctionPassManager(fpm, llmod);
598 let _timer = cgcx.prof.extra_verbose_generic_activity(
599 "LLVM_module_optimize_module_passes",
602 llvm::LLVMRunPassManager(mpm, llmod);
605 // Deallocate managers that we're now done with
606 llvm::LLVMDisposePassManager(fpm);
607 llvm::LLVMDisposePassManager(mpm);
612 unsafe fn add_sanitizer_passes(config: &ModuleConfig, passes: &mut Vec<&'static mut llvm::Pass>) {
613 if config.sanitizer.contains(SanitizerSet::ADDRESS) {
614 let recover = config.sanitizer_recover.contains(SanitizerSet::ADDRESS);
615 passes.push(llvm::LLVMRustCreateAddressSanitizerFunctionPass(recover));
616 passes.push(llvm::LLVMRustCreateModuleAddressSanitizerPass(recover));
618 if config.sanitizer.contains(SanitizerSet::MEMORY) {
619 let track_origins = config.sanitizer_memory_track_origins as c_int;
620 let recover = config.sanitizer_recover.contains(SanitizerSet::MEMORY);
621 passes.push(llvm::LLVMRustCreateMemorySanitizerPass(track_origins, recover));
623 if config.sanitizer.contains(SanitizerSet::THREAD) {
624 passes.push(llvm::LLVMRustCreateThreadSanitizerPass());
629 cgcx: &CodegenContext<LlvmCodegenBackend>,
630 diag_handler: &Handler,
631 mut modules: Vec<ModuleCodegen<ModuleLlvm>>,
632 ) -> Result<ModuleCodegen<ModuleLlvm>, FatalError> {
633 use super::lto::{Linker, ModuleBuffer};
634 // Sort the modules by name to ensure to ensure deterministic behavior.
635 modules.sort_by(|a, b| a.name.cmp(&b.name));
636 let (first, elements) =
637 modules.split_first().expect("Bug! modules must contain at least one module.");
639 let mut linker = Linker::new(first.module_llvm.llmod());
640 for module in elements {
642 cgcx.prof.generic_activity_with_arg("LLVM_link_module", format!("{:?}", module.name));
643 let buffer = ModuleBuffer::new(module.module_llvm.llmod());
644 linker.add(&buffer.data()).map_err(|()| {
645 let msg = format!("failed to serialize module {:?}", module.name);
646 llvm_err(&diag_handler, &msg)
650 Ok(modules.remove(0))
653 pub(crate) unsafe fn codegen(
654 cgcx: &CodegenContext<LlvmCodegenBackend>,
655 diag_handler: &Handler,
656 module: ModuleCodegen<ModuleLlvm>,
657 config: &ModuleConfig,
658 ) -> Result<CompiledModule, FatalError> {
659 let _timer = cgcx.prof.generic_activity_with_arg("LLVM_module_codegen", &module.name[..]);
661 let llmod = module.module_llvm.llmod();
662 let llcx = &*module.module_llvm.llcx;
663 let tm = &*module.module_llvm.tm;
664 let module_name = module.name.clone();
665 let module_name = Some(&module_name[..]);
666 let handlers = DiagnosticHandlers::new(cgcx, diag_handler, llcx);
668 if cgcx.msvc_imps_needed {
669 create_msvc_imps(cgcx, llcx, llmod);
672 // A codegen-specific pass manager is used to generate object
673 // files for an LLVM module.
675 // Apparently each of these pass managers is a one-shot kind of
676 // thing, so we create a new one for each type of output. The
677 // pass manager passed to the closure should be ensured to not
678 // escape the closure itself, and the manager should only be
680 unsafe fn with_codegen<'ll, F, R>(
681 tm: &'ll llvm::TargetMachine,
682 llmod: &'ll llvm::Module,
687 F: FnOnce(&'ll mut PassManager<'ll>) -> R,
689 let cpm = llvm::LLVMCreatePassManager();
690 llvm::LLVMAddAnalysisPasses(tm, cpm);
691 llvm::LLVMRustAddLibraryInfo(cpm, llmod, no_builtins);
695 // Two things to note:
696 // - If object files are just LLVM bitcode we write bitcode, copy it to
697 // the .o file, and delete the bitcode if it wasn't otherwise
699 // - If we don't have the integrated assembler then we need to emit
700 // asm from LLVM and use `gcc` to create the object file.
702 let bc_out = cgcx.output_filenames.temp_path(OutputType::Bitcode, module_name);
703 let obj_out = cgcx.output_filenames.temp_path(OutputType::Object, module_name);
705 if config.bitcode_needed() {
708 .generic_activity_with_arg("LLVM_module_codegen_make_bitcode", &module.name[..]);
709 let thin = ThinBuffer::new(llmod);
710 let data = thin.data();
712 if config.emit_bc || config.emit_obj == EmitObj::Bitcode {
713 let _timer = cgcx.prof.generic_activity_with_arg(
714 "LLVM_module_codegen_emit_bitcode",
717 if let Err(e) = fs::write(&bc_out, data) {
718 let msg = format!("failed to write bytecode to {}: {}", bc_out.display(), e);
719 diag_handler.err(&msg);
723 if config.emit_obj == EmitObj::ObjectCode(BitcodeSection::Full) {
724 let _timer = cgcx.prof.generic_activity_with_arg(
725 "LLVM_module_codegen_embed_bitcode",
728 embed_bitcode(cgcx, llcx, llmod, &config.bc_cmdline, data);
735 .generic_activity_with_arg("LLVM_module_codegen_emit_ir", &module.name[..]);
736 let out = cgcx.output_filenames.temp_path(OutputType::LlvmAssembly, module_name);
737 let out_c = path_to_c_string(&out);
739 extern "C" fn demangle_callback(
740 input_ptr: *const c_char,
742 output_ptr: *mut c_char,
746 unsafe { slice::from_raw_parts(input_ptr as *const u8, input_len as usize) };
748 let input = match str::from_utf8(input) {
753 let output = unsafe {
754 slice::from_raw_parts_mut(output_ptr as *mut u8, output_len as usize)
756 let mut cursor = io::Cursor::new(output);
758 let demangled = match rustc_demangle::try_demangle(input) {
763 if write!(cursor, "{:#}", demangled).is_err() {
764 // Possible only if provided buffer is not big enough
768 cursor.position() as size_t
771 let result = llvm::LLVMRustPrintModule(llmod, out_c.as_ptr(), demangle_callback);
772 result.into_result().map_err(|()| {
773 let msg = format!("failed to write LLVM IR to {}", out.display());
774 llvm_err(diag_handler, &msg)
781 .generic_activity_with_arg("LLVM_module_codegen_emit_asm", &module.name[..]);
782 let path = cgcx.output_filenames.temp_path(OutputType::Assembly, module_name);
784 // We can't use the same module for asm and object code output,
785 // because that triggers various errors like invalid IR or broken
786 // binaries. So we must clone the module to produce the asm output
787 // if we are also producing object code.
788 let llmod = if let EmitObj::ObjectCode(_) = config.emit_obj {
789 llvm::LLVMCloneModule(llmod)
793 with_codegen(tm, llmod, config.no_builtins, |cpm| {
794 write_output_file(diag_handler, tm, cpm, llmod, &path, llvm::FileType::AssemblyFile)
798 match config.emit_obj {
799 EmitObj::ObjectCode(_) => {
802 .generic_activity_with_arg("LLVM_module_codegen_emit_obj", &module.name[..]);
803 with_codegen(tm, llmod, config.no_builtins, |cpm| {
810 llvm::FileType::ObjectFile,
815 EmitObj::Bitcode => {
816 debug!("copying bitcode {:?} to obj {:?}", bc_out, obj_out);
817 if let Err(e) = link_or_copy(&bc_out, &obj_out) {
818 diag_handler.err(&format!("failed to copy bitcode to object file: {}", e));
822 debug!("removing_bitcode {:?}", bc_out);
823 if let Err(e) = fs::remove_file(&bc_out) {
824 diag_handler.err(&format!("failed to remove bitcode: {}", e));
835 Ok(module.into_compiled_module(
836 config.emit_obj != EmitObj::None,
838 &cgcx.output_filenames,
842 /// Embed the bitcode of an LLVM module in the LLVM module itself.
844 /// This is done primarily for iOS where it appears to be standard to compile C
845 /// code at least with `-fembed-bitcode` which creates two sections in the
848 /// * __LLVM,__bitcode
849 /// * __LLVM,__cmdline
851 /// It appears *both* of these sections are necessary to get the linker to
852 /// recognize what's going on. A suitable cmdline value is taken from the
855 /// Furthermore debug/O1 builds don't actually embed bitcode but rather just
856 /// embed an empty section.
858 /// Basically all of this is us attempting to follow in the footsteps of clang
859 /// on iOS. See #35968 for lots more info.
860 unsafe fn embed_bitcode(
861 cgcx: &CodegenContext<LlvmCodegenBackend>,
862 llcx: &llvm::Context,
863 llmod: &llvm::Module,
867 let llconst = common::bytes_in_context(llcx, bitcode);
868 let llglobal = llvm::LLVMAddGlobal(
870 common::val_ty(llconst),
871 "rustc.embedded.module\0".as_ptr().cast(),
873 llvm::LLVMSetInitializer(llglobal, llconst);
875 let is_apple = cgcx.opts.target_triple.triple().contains("-ios")
876 || cgcx.opts.target_triple.triple().contains("-darwin")
877 || cgcx.opts.target_triple.triple().contains("-tvos");
879 let section = if is_apple { "__LLVM,__bitcode\0" } else { ".llvmbc\0" };
880 llvm::LLVMSetSection(llglobal, section.as_ptr().cast());
881 llvm::LLVMRustSetLinkage(llglobal, llvm::Linkage::PrivateLinkage);
882 llvm::LLVMSetGlobalConstant(llglobal, llvm::True);
884 let llconst = common::bytes_in_context(llcx, cmdline.as_bytes());
885 let llglobal = llvm::LLVMAddGlobal(
887 common::val_ty(llconst),
888 "rustc.embedded.cmdline\0".as_ptr().cast(),
890 llvm::LLVMSetInitializer(llglobal, llconst);
891 let section = if is_apple { "__LLVM,__cmdline\0" } else { ".llvmcmd\0" };
892 llvm::LLVMSetSection(llglobal, section.as_ptr().cast());
893 llvm::LLVMRustSetLinkage(llglobal, llvm::Linkage::PrivateLinkage);
895 // We're adding custom sections to the output object file, but we definitely
896 // do not want these custom sections to make their way into the final linked
897 // executable. The purpose of these custom sections is for tooling
898 // surrounding object files to work with the LLVM IR, if necessary. For
899 // example rustc's own LTO will look for LLVM IR inside of the object file
900 // in these sections by default.
902 // To handle this is a bit different depending on the object file format
903 // used by the backend, broken down into a few different categories:
905 // * Mach-O - this is for macOS. Inspecting the source code for the native
906 // linker here shows that the `.llvmbc` and `.llvmcmd` sections are
907 // automatically skipped by the linker. In that case there's nothing extra
908 // that we need to do here.
910 // * Wasm - the native LLD linker is hard-coded to skip `.llvmbc` and
911 // `.llvmcmd` sections, so there's nothing extra we need to do.
913 // * COFF - if we don't do anything the linker will by default copy all
914 // these sections to the output artifact, not what we want! To subvert
915 // this we want to flag the sections we inserted here as
916 // `IMAGE_SCN_LNK_REMOVE`. Unfortunately though LLVM has no native way to
917 // do this. Thankfully though we can do this with some inline assembly,
918 // which is easy enough to add via module-level global inline asm.
920 // * ELF - this is very similar to COFF above. One difference is that these
921 // sections are removed from the output linked artifact when
922 // `--gc-sections` is passed, which we pass by default. If that flag isn't
923 // passed though then these sections will show up in the final output.
924 // Additionally the flag that we need to set here is `SHF_EXCLUDE`.
926 || cgcx.opts.target_triple.triple().starts_with("wasm")
927 || cgcx.opts.target_triple.triple().starts_with("asmjs")
929 // nothing to do here
930 } else if cgcx.opts.target_triple.triple().contains("windows")
931 || cgcx.opts.target_triple.triple().contains("uefi")
934 .section .llvmbc,\"n\"
935 .section .llvmcmd,\"n\"
937 llvm::LLVMRustAppendModuleInlineAsm(llmod, asm.as_ptr().cast(), asm.len());
940 .section .llvmbc,\"e\"
941 .section .llvmcmd,\"e\"
943 llvm::LLVMRustAppendModuleInlineAsm(llmod, asm.as_ptr().cast(), asm.len());
947 pub unsafe fn with_llvm_pmb(
948 llmod: &llvm::Module,
949 config: &ModuleConfig,
950 opt_level: llvm::CodeGenOptLevel,
951 prepare_for_thin_lto: bool,
952 f: &mut dyn FnMut(&llvm::PassManagerBuilder),
956 // Create the PassManagerBuilder for LLVM. We configure it with
957 // reasonable defaults and prepare it to actually populate the pass
959 let builder = llvm::LLVMPassManagerBuilderCreate();
961 config.opt_size.map(|x| to_llvm_opt_settings(x).1).unwrap_or(llvm::CodeGenOptSizeNone);
962 let inline_threshold = config.inline_threshold;
963 let pgo_gen_path = get_pgo_gen_path(config);
964 let pgo_use_path = get_pgo_use_path(config);
966 llvm::LLVMRustConfigurePassManagerBuilder(
969 config.merge_functions,
970 config.vectorize_slp,
971 config.vectorize_loop,
972 prepare_for_thin_lto,
973 pgo_gen_path.as_ref().map_or(ptr::null(), |s| s.as_ptr()),
974 pgo_use_path.as_ref().map_or(ptr::null(), |s| s.as_ptr()),
977 llvm::LLVMPassManagerBuilderSetSizeLevel(builder, opt_size as u32);
979 if opt_size != llvm::CodeGenOptSizeNone {
980 llvm::LLVMPassManagerBuilderSetDisableUnrollLoops(builder, 1);
983 llvm::LLVMRustAddBuilderLibraryInfo(builder, llmod, config.no_builtins);
985 // Here we match what clang does (kinda). For O0 we only inline
986 // always-inline functions (but don't add lifetime intrinsics), at O1 we
987 // inline with lifetime intrinsics, and O2+ we add an inliner with a
988 // thresholds copied from clang.
989 match (opt_level, opt_size, inline_threshold) {
991 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, t as u32);
993 (llvm::CodeGenOptLevel::Aggressive, ..) => {
994 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 275);
996 (_, llvm::CodeGenOptSizeDefault, _) => {
997 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 75);
999 (_, llvm::CodeGenOptSizeAggressive, _) => {
1000 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 25);
1002 (llvm::CodeGenOptLevel::None, ..) => {
1003 llvm::LLVMRustAddAlwaysInlinePass(builder, config.emit_lifetime_markers);
1005 (llvm::CodeGenOptLevel::Less, ..) => {
1006 llvm::LLVMRustAddAlwaysInlinePass(builder, config.emit_lifetime_markers);
1008 (llvm::CodeGenOptLevel::Default, ..) => {
1009 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 225);
1014 llvm::LLVMPassManagerBuilderDispose(builder);
1017 // Create a `__imp_<symbol> = &symbol` global for every public static `symbol`.
1018 // This is required to satisfy `dllimport` references to static data in .rlibs
1019 // when using MSVC linker. We do this only for data, as linker can fix up
1020 // code references on its own.
1021 // See #26591, #27438
1022 fn create_msvc_imps(
1023 cgcx: &CodegenContext<LlvmCodegenBackend>,
1024 llcx: &llvm::Context,
1025 llmod: &llvm::Module,
1027 if !cgcx.msvc_imps_needed {
1030 // The x86 ABI seems to require that leading underscores are added to symbol
1031 // names, so we need an extra underscore on x86. There's also a leading
1032 // '\x01' here which disables LLVM's symbol mangling (e.g., no extra
1033 // underscores added in front).
1034 let prefix = if cgcx.target_arch == "x86" { "\x01__imp__" } else { "\x01__imp_" };
1037 let i8p_ty = Type::i8p_llcx(llcx);
1038 let globals = base::iter_globals(llmod)
1040 llvm::LLVMRustGetLinkage(val) == llvm::Linkage::ExternalLinkage
1041 && llvm::LLVMIsDeclaration(val) == 0
1044 // Exclude some symbols that we know are not Rust symbols.
1045 let name = llvm::get_value_name(val);
1046 if ignored(name) { None } else { Some((val, name)) }
1048 .map(move |(val, name)| {
1049 let mut imp_name = prefix.as_bytes().to_vec();
1050 imp_name.extend(name);
1051 let imp_name = CString::new(imp_name).unwrap();
1054 .collect::<Vec<_>>();
1056 for (imp_name, val) in globals {
1057 let imp = llvm::LLVMAddGlobal(llmod, i8p_ty, imp_name.as_ptr().cast());
1058 llvm::LLVMSetInitializer(imp, consts::ptrcast(val, i8p_ty));
1059 llvm::LLVMRustSetLinkage(imp, llvm::Linkage::ExternalLinkage);
1063 // Use this function to exclude certain symbols from `__imp` generation.
1064 fn ignored(symbol_name: &[u8]) -> bool {
1065 // These are symbols generated by LLVM's profiling instrumentation
1066 symbol_name.starts_with(b"__llvm_profile_")