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.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.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.llvm_abiname);
155 let trap_unreachable =
156 sess.opts.debugging_opts.trap_unreachable.unwrap_or(sess.target.trap_unreachable);
157 let emit_stack_size_section = sess.opts.debugging_opts.emit_stack_sizes;
159 let asm_comments = sess.asm_comments();
160 let relax_elf_relocations =
161 sess.opts.debugging_opts.relax_elf_relocations.unwrap_or(sess.target.relax_elf_relocations);
164 !sess.opts.debugging_opts.use_ctors_section.unwrap_or(sess.target.use_ctors_section);
168 llvm::LLVMRustCreateTargetMachine(
182 emit_stack_size_section,
183 relax_elf_relocations,
189 format!("Could not create LLVM TargetMachine for triple: {}", triple.to_str().unwrap())
194 pub(crate) fn save_temp_bitcode(
195 cgcx: &CodegenContext<LlvmCodegenBackend>,
196 module: &ModuleCodegen<ModuleLlvm>,
199 if !cgcx.save_temps {
203 let ext = format!("{}.bc", name);
204 let cgu = Some(&module.name[..]);
205 let path = cgcx.output_filenames.temp_path_ext(&ext, cgu);
206 let cstr = path_to_c_string(&path);
207 let llmod = module.module_llvm.llmod();
208 llvm::LLVMWriteBitcodeToFile(llmod, cstr.as_ptr());
212 pub struct DiagnosticHandlers<'a> {
213 data: *mut (&'a CodegenContext<LlvmCodegenBackend>, &'a Handler),
214 llcx: &'a llvm::Context,
217 impl<'a> DiagnosticHandlers<'a> {
219 cgcx: &'a CodegenContext<LlvmCodegenBackend>,
220 handler: &'a Handler,
221 llcx: &'a llvm::Context,
223 let data = Box::into_raw(Box::new((cgcx, handler)));
225 llvm::LLVMRustSetInlineAsmDiagnosticHandler(llcx, inline_asm_handler, data.cast());
226 llvm::LLVMContextSetDiagnosticHandler(llcx, diagnostic_handler, data.cast());
228 DiagnosticHandlers { data, llcx }
232 impl<'a> Drop for DiagnosticHandlers<'a> {
234 use std::ptr::null_mut;
236 llvm::LLVMRustSetInlineAsmDiagnosticHandler(self.llcx, inline_asm_handler, null_mut());
237 llvm::LLVMContextSetDiagnosticHandler(self.llcx, diagnostic_handler, null_mut());
238 drop(Box::from_raw(self.data));
243 fn report_inline_asm(
244 cgcx: &CodegenContext<LlvmCodegenBackend>,
246 level: llvm::DiagnosticLevel,
248 source: Option<(String, Vec<InnerSpan>)>,
250 // In LTO build we may get srcloc values from other crates which are invalid
251 // since they use a different source map. To be safe we just suppress these
253 if matches!(cgcx.lto, Lto::Fat | Lto::Thin) {
256 let level = match level {
257 llvm::DiagnosticLevel::Error => Level::Error,
258 llvm::DiagnosticLevel::Warning => Level::Warning,
259 llvm::DiagnosticLevel::Note | llvm::DiagnosticLevel::Remark => Level::Note,
261 cgcx.diag_emitter.inline_asm_error(cookie as u32, msg, level, source);
264 unsafe extern "C" fn inline_asm_handler(diag: &SMDiagnostic, user: *const c_void, cookie: c_uint) {
268 let (cgcx, _) = *(user as *const (&CodegenContext<LlvmCodegenBackend>, &Handler));
270 // Recover the post-substitution assembly code from LLVM for better
272 let mut have_source = false;
273 let mut buffer = String::new();
274 let mut level = llvm::DiagnosticLevel::Error;
276 let mut ranges = [0; 8];
277 let mut num_ranges = ranges.len() / 2;
278 let msg = llvm::build_string(|msg| {
279 buffer = llvm::build_string(|buffer| {
280 have_source = llvm::LLVMRustUnpackSMDiagnostic(
290 .expect("non-UTF8 inline asm");
292 .expect("non-UTF8 SMDiagnostic");
294 let source = have_source.then(|| {
295 let mut spans = vec![InnerSpan::new(loc as usize, loc as usize)];
296 for i in 0..num_ranges {
297 spans.push(InnerSpan::new(ranges[i * 2] as usize, ranges[i * 2 + 1] as usize));
302 report_inline_asm(cgcx, msg, level, cookie, source);
305 unsafe extern "C" fn diagnostic_handler(info: &DiagnosticInfo, user: *mut c_void) {
309 let (cgcx, diag_handler) = *(user as *const (&CodegenContext<LlvmCodegenBackend>, &Handler));
311 match llvm::diagnostic::Diagnostic::unpack(info) {
312 llvm::diagnostic::InlineAsm(inline) => {
315 llvm::twine_to_string(inline.message),
322 llvm::diagnostic::Optimization(opt) => {
323 let enabled = match cgcx.remark {
325 Passes::Some(ref v) => v.iter().any(|s| *s == opt.pass_name),
329 diag_handler.note_without_error(&format!(
330 "optimization {} for {} at {}:{}:{}: {}",
340 llvm::diagnostic::PGO(diagnostic_ref) | llvm::diagnostic::Linker(diagnostic_ref) => {
341 let msg = llvm::build_string(|s| {
342 llvm::LLVMRustWriteDiagnosticInfoToString(diagnostic_ref, s)
344 .expect("non-UTF8 diagnostic");
345 diag_handler.warn(&msg);
347 llvm::diagnostic::Unsupported(diagnostic_ref) => {
348 let msg = llvm::build_string(|s| {
349 llvm::LLVMRustWriteDiagnosticInfoToString(diagnostic_ref, s)
351 .expect("non-UTF8 diagnostic");
352 diag_handler.err(&msg);
354 llvm::diagnostic::UnknownDiagnostic(..) => {}
358 fn get_pgo_gen_path(config: &ModuleConfig) -> Option<CString> {
359 match config.pgo_gen {
360 SwitchWithOptPath::Enabled(ref opt_dir_path) => {
361 let path = if let Some(dir_path) = opt_dir_path {
362 dir_path.join("default_%m.profraw")
364 PathBuf::from("default_%m.profraw")
367 Some(CString::new(format!("{}", path.display())).unwrap())
369 SwitchWithOptPath::Disabled => None,
373 fn get_pgo_use_path(config: &ModuleConfig) -> Option<CString> {
377 .map(|path_buf| CString::new(path_buf.to_string_lossy().as_bytes()).unwrap())
380 pub(crate) fn should_use_new_llvm_pass_manager(config: &ModuleConfig) -> bool {
381 // The new pass manager is disabled by default.
382 config.new_llvm_pass_manager
385 pub(crate) unsafe fn optimize_with_new_llvm_pass_manager(
386 cgcx: &CodegenContext<LlvmCodegenBackend>,
387 module: &ModuleCodegen<ModuleLlvm>,
388 config: &ModuleConfig,
389 opt_level: config::OptLevel,
390 opt_stage: llvm::OptStage,
393 opt_level != config::OptLevel::Size && opt_level != config::OptLevel::SizeMin;
394 let using_thin_buffers = opt_stage == llvm::OptStage::PreLinkThinLTO || config.bitcode_needed();
395 let pgo_gen_path = get_pgo_gen_path(config);
396 let pgo_use_path = get_pgo_use_path(config);
397 let is_lto = opt_stage == llvm::OptStage::ThinLTO || opt_stage == llvm::OptStage::FatLTO;
398 // Sanitizer instrumentation is only inserted during the pre-link optimization stage.
399 let sanitizer_options = if !is_lto {
400 Some(llvm::SanitizerOptions {
401 sanitize_address: config.sanitizer.contains(SanitizerSet::ADDRESS),
402 sanitize_address_recover: config.sanitizer_recover.contains(SanitizerSet::ADDRESS),
403 sanitize_memory: config.sanitizer.contains(SanitizerSet::MEMORY),
404 sanitize_memory_recover: config.sanitizer_recover.contains(SanitizerSet::MEMORY),
405 sanitize_memory_track_origins: config.sanitizer_memory_track_origins as c_int,
406 sanitize_thread: config.sanitizer.contains(SanitizerSet::THREAD),
412 let llvm_selfprofiler = if cgcx.prof.llvm_recording_enabled() {
413 let mut llvm_profiler = LlvmSelfProfiler::new(cgcx.prof.get_self_profiler().unwrap());
414 &mut llvm_profiler as *mut _ as *mut c_void
419 // FIXME: NewPM doesn't provide a facility to pass custom InlineParams.
420 // We would have to add upstream support for this first, before we can support
421 // config.inline_threshold and our more aggressive default thresholds.
422 // FIXME: NewPM uses an different and more explicit way to textually represent
423 // pass pipelines. It would probably make sense to expose this, but it would
424 // require a different format than the current -C passes.
425 llvm::LLVMRustOptimizeWithNewPassManager(
426 module.module_llvm.llmod(),
427 &*module.module_llvm.tm,
428 to_pass_builder_opt_level(opt_level),
430 config.no_prepopulate_passes,
431 config.verify_llvm_ir,
433 config.merge_functions,
435 config.vectorize_slp,
436 config.vectorize_loop,
438 config.emit_lifetime_markers,
439 sanitizer_options.as_ref(),
440 pgo_gen_path.as_ref().map_or(std::ptr::null(), |s| s.as_ptr()),
441 pgo_use_path.as_ref().map_or(std::ptr::null(), |s| s.as_ptr()),
443 selfprofile_before_pass_callback,
444 selfprofile_after_pass_callback,
448 // Unsafe due to LLVM calls.
449 pub(crate) unsafe fn optimize(
450 cgcx: &CodegenContext<LlvmCodegenBackend>,
451 diag_handler: &Handler,
452 module: &ModuleCodegen<ModuleLlvm>,
453 config: &ModuleConfig,
454 ) -> Result<(), FatalError> {
455 let _timer = cgcx.prof.generic_activity_with_arg("LLVM_module_optimize", &module.name[..]);
457 let llmod = module.module_llvm.llmod();
458 let llcx = &*module.module_llvm.llcx;
459 let tm = &*module.module_llvm.tm;
460 let _handlers = DiagnosticHandlers::new(cgcx, diag_handler, llcx);
462 let module_name = module.name.clone();
463 let module_name = Some(&module_name[..]);
465 if config.emit_no_opt_bc {
466 let out = cgcx.output_filenames.temp_path_ext("no-opt.bc", module_name);
467 let out = path_to_c_string(&out);
468 llvm::LLVMWriteBitcodeToFile(llmod, out.as_ptr());
471 if let Some(opt_level) = config.opt_level {
472 if should_use_new_llvm_pass_manager(config) {
473 let opt_stage = match cgcx.lto {
474 Lto::Fat => llvm::OptStage::PreLinkFatLTO,
475 Lto::Thin | Lto::ThinLocal => llvm::OptStage::PreLinkThinLTO,
476 _ if cgcx.opts.cg.linker_plugin_lto.enabled() => llvm::OptStage::PreLinkThinLTO,
477 _ => llvm::OptStage::PreLinkNoLTO,
479 optimize_with_new_llvm_pass_manager(cgcx, module, config, opt_level, opt_stage);
483 if cgcx.prof.llvm_recording_enabled() {
485 .warn("`-Z self-profile-events = llvm` requires `-Z new-llvm-pass-manager`");
488 // Create the two optimizing pass managers. These mirror what clang
489 // does, and are by populated by LLVM's default PassManagerBuilder.
490 // Each manager has a different set of passes, but they also share
491 // some common passes.
492 let fpm = llvm::LLVMCreateFunctionPassManagerForModule(llmod);
493 let mpm = llvm::LLVMCreatePassManager();
496 let find_pass = |pass_name: &str| {
497 let pass_name = SmallCStr::new(pass_name);
498 llvm::LLVMRustFindAndCreatePass(pass_name.as_ptr())
501 if config.verify_llvm_ir {
502 // Verification should run as the very first pass.
503 llvm::LLVMRustAddPass(fpm, find_pass("verify").unwrap());
506 let mut extra_passes = Vec::new();
507 let mut have_name_anon_globals_pass = false;
509 for pass_name in &config.passes {
510 if pass_name == "lint" {
511 // Linting should also be performed early, directly on the generated IR.
512 llvm::LLVMRustAddPass(fpm, find_pass("lint").unwrap());
516 if let Some(pass) = find_pass(pass_name) {
517 extra_passes.push(pass);
519 diag_handler.warn(&format!("unknown pass `{}`, ignoring", pass_name));
522 if pass_name == "name-anon-globals" {
523 have_name_anon_globals_pass = true;
527 add_sanitizer_passes(config, &mut extra_passes);
529 // Some options cause LLVM bitcode to be emitted, which uses ThinLTOBuffers, so we need
530 // to make sure we run LLVM's NameAnonGlobals pass when emitting bitcode; otherwise
531 // we'll get errors in LLVM.
532 let using_thin_buffers = config.bitcode_needed();
533 if !config.no_prepopulate_passes {
534 llvm::LLVMAddAnalysisPasses(tm, fpm);
535 llvm::LLVMAddAnalysisPasses(tm, mpm);
536 let opt_level = to_llvm_opt_settings(opt_level).0;
537 let prepare_for_thin_lto = cgcx.lto == Lto::Thin
538 || cgcx.lto == Lto::ThinLocal
539 || (cgcx.lto != Lto::Fat && cgcx.opts.cg.linker_plugin_lto.enabled());
540 with_llvm_pmb(llmod, &config, opt_level, prepare_for_thin_lto, &mut |b| {
541 llvm::LLVMRustAddLastExtensionPasses(
543 extra_passes.as_ptr(),
544 extra_passes.len() as size_t,
546 llvm::LLVMPassManagerBuilderPopulateFunctionPassManager(b, fpm);
547 llvm::LLVMPassManagerBuilderPopulateModulePassManager(b, mpm);
550 have_name_anon_globals_pass = have_name_anon_globals_pass || prepare_for_thin_lto;
551 if using_thin_buffers && !prepare_for_thin_lto {
552 llvm::LLVMRustAddPass(mpm, find_pass("name-anon-globals").unwrap());
553 have_name_anon_globals_pass = true;
556 // If we don't use the standard pipeline, directly populate the MPM
557 // with the extra passes.
558 for pass in extra_passes {
559 llvm::LLVMRustAddPass(mpm, pass);
563 if using_thin_buffers && !have_name_anon_globals_pass {
564 // As described above, this will probably cause an error in LLVM
565 if config.no_prepopulate_passes {
567 "The current compilation is going to use thin LTO buffers \
568 without running LLVM's NameAnonGlobals pass. \
569 This will likely cause errors in LLVM. Consider adding \
570 -C passes=name-anon-globals to the compiler command line.",
574 "We are using thin LTO buffers without running the NameAnonGlobals pass. \
575 This will likely cause errors in LLVM and should never happen."
581 diag_handler.abort_if_errors();
583 // Finally, run the actual optimization passes
585 let _timer = cgcx.prof.extra_verbose_generic_activity(
586 "LLVM_module_optimize_function_passes",
589 llvm::LLVMRustRunFunctionPassManager(fpm, llmod);
592 let _timer = cgcx.prof.extra_verbose_generic_activity(
593 "LLVM_module_optimize_module_passes",
596 llvm::LLVMRunPassManager(mpm, llmod);
599 // Deallocate managers that we're now done with
600 llvm::LLVMDisposePassManager(fpm);
601 llvm::LLVMDisposePassManager(mpm);
606 unsafe fn add_sanitizer_passes(config: &ModuleConfig, passes: &mut Vec<&'static mut llvm::Pass>) {
607 if config.sanitizer.contains(SanitizerSet::ADDRESS) {
608 let recover = config.sanitizer_recover.contains(SanitizerSet::ADDRESS);
609 passes.push(llvm::LLVMRustCreateAddressSanitizerFunctionPass(recover));
610 passes.push(llvm::LLVMRustCreateModuleAddressSanitizerPass(recover));
612 if config.sanitizer.contains(SanitizerSet::MEMORY) {
613 let track_origins = config.sanitizer_memory_track_origins as c_int;
614 let recover = config.sanitizer_recover.contains(SanitizerSet::MEMORY);
615 passes.push(llvm::LLVMRustCreateMemorySanitizerPass(track_origins, recover));
617 if config.sanitizer.contains(SanitizerSet::THREAD) {
618 passes.push(llvm::LLVMRustCreateThreadSanitizerPass());
623 cgcx: &CodegenContext<LlvmCodegenBackend>,
624 diag_handler: &Handler,
625 mut modules: Vec<ModuleCodegen<ModuleLlvm>>,
626 ) -> Result<ModuleCodegen<ModuleLlvm>, FatalError> {
627 use super::lto::{Linker, ModuleBuffer};
628 // Sort the modules by name to ensure to ensure deterministic behavior.
629 modules.sort_by(|a, b| a.name.cmp(&b.name));
630 let (first, elements) =
631 modules.split_first().expect("Bug! modules must contain at least one module.");
633 let mut linker = Linker::new(first.module_llvm.llmod());
634 for module in elements {
636 cgcx.prof.generic_activity_with_arg("LLVM_link_module", format!("{:?}", module.name));
637 let buffer = ModuleBuffer::new(module.module_llvm.llmod());
638 linker.add(&buffer.data()).map_err(|()| {
639 let msg = format!("failed to serialize module {:?}", module.name);
640 llvm_err(&diag_handler, &msg)
644 Ok(modules.remove(0))
647 pub(crate) unsafe fn codegen(
648 cgcx: &CodegenContext<LlvmCodegenBackend>,
649 diag_handler: &Handler,
650 module: ModuleCodegen<ModuleLlvm>,
651 config: &ModuleConfig,
652 ) -> Result<CompiledModule, FatalError> {
653 let _timer = cgcx.prof.generic_activity_with_arg("LLVM_module_codegen", &module.name[..]);
655 let llmod = module.module_llvm.llmod();
656 let llcx = &*module.module_llvm.llcx;
657 let tm = &*module.module_llvm.tm;
658 let module_name = module.name.clone();
659 let module_name = Some(&module_name[..]);
660 let handlers = DiagnosticHandlers::new(cgcx, diag_handler, llcx);
662 if cgcx.msvc_imps_needed {
663 create_msvc_imps(cgcx, llcx, llmod);
666 // A codegen-specific pass manager is used to generate object
667 // files for an LLVM module.
669 // Apparently each of these pass managers is a one-shot kind of
670 // thing, so we create a new one for each type of output. The
671 // pass manager passed to the closure should be ensured to not
672 // escape the closure itself, and the manager should only be
674 unsafe fn with_codegen<'ll, F, R>(
675 tm: &'ll llvm::TargetMachine,
676 llmod: &'ll llvm::Module,
681 F: FnOnce(&'ll mut PassManager<'ll>) -> R,
683 let cpm = llvm::LLVMCreatePassManager();
684 llvm::LLVMAddAnalysisPasses(tm, cpm);
685 llvm::LLVMRustAddLibraryInfo(cpm, llmod, no_builtins);
689 // Two things to note:
690 // - If object files are just LLVM bitcode we write bitcode, copy it to
691 // the .o file, and delete the bitcode if it wasn't otherwise
693 // - If we don't have the integrated assembler then we need to emit
694 // asm from LLVM and use `gcc` to create the object file.
696 let bc_out = cgcx.output_filenames.temp_path(OutputType::Bitcode, module_name);
697 let obj_out = cgcx.output_filenames.temp_path(OutputType::Object, module_name);
699 if config.bitcode_needed() {
702 .generic_activity_with_arg("LLVM_module_codegen_make_bitcode", &module.name[..]);
703 let thin = ThinBuffer::new(llmod);
704 let data = thin.data();
706 if config.emit_bc || config.emit_obj == EmitObj::Bitcode {
707 let _timer = cgcx.prof.generic_activity_with_arg(
708 "LLVM_module_codegen_emit_bitcode",
711 if let Err(e) = fs::write(&bc_out, data) {
712 let msg = format!("failed to write bytecode to {}: {}", bc_out.display(), e);
713 diag_handler.err(&msg);
717 if config.emit_obj == EmitObj::ObjectCode(BitcodeSection::Full) {
718 let _timer = cgcx.prof.generic_activity_with_arg(
719 "LLVM_module_codegen_embed_bitcode",
722 embed_bitcode(cgcx, llcx, llmod, &config.bc_cmdline, data);
729 .generic_activity_with_arg("LLVM_module_codegen_emit_ir", &module.name[..]);
730 let out = cgcx.output_filenames.temp_path(OutputType::LlvmAssembly, module_name);
731 let out_c = path_to_c_string(&out);
733 extern "C" fn demangle_callback(
734 input_ptr: *const c_char,
736 output_ptr: *mut c_char,
740 unsafe { slice::from_raw_parts(input_ptr as *const u8, input_len as usize) };
742 let input = match str::from_utf8(input) {
747 let output = unsafe {
748 slice::from_raw_parts_mut(output_ptr as *mut u8, output_len as usize)
750 let mut cursor = io::Cursor::new(output);
752 let demangled = match rustc_demangle::try_demangle(input) {
757 if write!(cursor, "{:#}", demangled).is_err() {
758 // Possible only if provided buffer is not big enough
762 cursor.position() as size_t
765 let result = llvm::LLVMRustPrintModule(llmod, out_c.as_ptr(), demangle_callback);
766 result.into_result().map_err(|()| {
767 let msg = format!("failed to write LLVM IR to {}", out.display());
768 llvm_err(diag_handler, &msg)
775 .generic_activity_with_arg("LLVM_module_codegen_emit_asm", &module.name[..]);
776 let path = cgcx.output_filenames.temp_path(OutputType::Assembly, module_name);
778 // We can't use the same module for asm and object code output,
779 // because that triggers various errors like invalid IR or broken
780 // binaries. So we must clone the module to produce the asm output
781 // if we are also producing object code.
782 let llmod = if let EmitObj::ObjectCode(_) = config.emit_obj {
783 llvm::LLVMCloneModule(llmod)
787 with_codegen(tm, llmod, config.no_builtins, |cpm| {
788 write_output_file(diag_handler, tm, cpm, llmod, &path, llvm::FileType::AssemblyFile)
792 match config.emit_obj {
793 EmitObj::ObjectCode(_) => {
796 .generic_activity_with_arg("LLVM_module_codegen_emit_obj", &module.name[..]);
797 with_codegen(tm, llmod, config.no_builtins, |cpm| {
804 llvm::FileType::ObjectFile,
809 EmitObj::Bitcode => {
810 debug!("copying bitcode {:?} to obj {:?}", bc_out, obj_out);
811 if let Err(e) = link_or_copy(&bc_out, &obj_out) {
812 diag_handler.err(&format!("failed to copy bitcode to object file: {}", e));
816 debug!("removing_bitcode {:?}", bc_out);
817 if let Err(e) = fs::remove_file(&bc_out) {
818 diag_handler.err(&format!("failed to remove bitcode: {}", e));
829 Ok(module.into_compiled_module(
830 config.emit_obj != EmitObj::None,
832 &cgcx.output_filenames,
836 /// Embed the bitcode of an LLVM module in the LLVM module itself.
838 /// This is done primarily for iOS where it appears to be standard to compile C
839 /// code at least with `-fembed-bitcode` which creates two sections in the
842 /// * __LLVM,__bitcode
843 /// * __LLVM,__cmdline
845 /// It appears *both* of these sections are necessary to get the linker to
846 /// recognize what's going on. A suitable cmdline value is taken from the
849 /// Furthermore debug/O1 builds don't actually embed bitcode but rather just
850 /// embed an empty section.
852 /// Basically all of this is us attempting to follow in the footsteps of clang
853 /// on iOS. See #35968 for lots more info.
854 unsafe fn embed_bitcode(
855 cgcx: &CodegenContext<LlvmCodegenBackend>,
856 llcx: &llvm::Context,
857 llmod: &llvm::Module,
861 let llconst = common::bytes_in_context(llcx, bitcode);
862 let llglobal = llvm::LLVMAddGlobal(
864 common::val_ty(llconst),
865 "rustc.embedded.module\0".as_ptr().cast(),
867 llvm::LLVMSetInitializer(llglobal, llconst);
869 let is_apple = cgcx.opts.target_triple.triple().contains("-ios")
870 || cgcx.opts.target_triple.triple().contains("-darwin")
871 || cgcx.opts.target_triple.triple().contains("-tvos");
873 let section = if is_apple { "__LLVM,__bitcode\0" } else { ".llvmbc\0" };
874 llvm::LLVMSetSection(llglobal, section.as_ptr().cast());
875 llvm::LLVMRustSetLinkage(llglobal, llvm::Linkage::PrivateLinkage);
876 llvm::LLVMSetGlobalConstant(llglobal, llvm::True);
878 let llconst = common::bytes_in_context(llcx, cmdline.as_bytes());
879 let llglobal = llvm::LLVMAddGlobal(
881 common::val_ty(llconst),
882 "rustc.embedded.cmdline\0".as_ptr().cast(),
884 llvm::LLVMSetInitializer(llglobal, llconst);
885 let section = if is_apple { "__LLVM,__cmdline\0" } else { ".llvmcmd\0" };
886 llvm::LLVMSetSection(llglobal, section.as_ptr().cast());
887 llvm::LLVMRustSetLinkage(llglobal, llvm::Linkage::PrivateLinkage);
889 // We're adding custom sections to the output object file, but we definitely
890 // do not want these custom sections to make their way into the final linked
891 // executable. The purpose of these custom sections is for tooling
892 // surrounding object files to work with the LLVM IR, if necessary. For
893 // example rustc's own LTO will look for LLVM IR inside of the object file
894 // in these sections by default.
896 // To handle this is a bit different depending on the object file format
897 // used by the backend, broken down into a few different categories:
899 // * Mach-O - this is for macOS. Inspecting the source code for the native
900 // linker here shows that the `.llvmbc` and `.llvmcmd` sections are
901 // automatically skipped by the linker. In that case there's nothing extra
902 // that we need to do here.
904 // * Wasm - the native LLD linker is hard-coded to skip `.llvmbc` and
905 // `.llvmcmd` sections, so there's nothing extra we need to do.
907 // * COFF - if we don't do anything the linker will by default copy all
908 // these sections to the output artifact, not what we want! To subvert
909 // this we want to flag the sections we inserted here as
910 // `IMAGE_SCN_LNK_REMOVE`. Unfortunately though LLVM has no native way to
911 // do this. Thankfully though we can do this with some inline assembly,
912 // which is easy enough to add via module-level global inline asm.
914 // * ELF - this is very similar to COFF above. One difference is that these
915 // sections are removed from the output linked artifact when
916 // `--gc-sections` is passed, which we pass by default. If that flag isn't
917 // passed though then these sections will show up in the final output.
918 // Additionally the flag that we need to set here is `SHF_EXCLUDE`.
920 || cgcx.opts.target_triple.triple().starts_with("wasm")
921 || cgcx.opts.target_triple.triple().starts_with("asmjs")
923 // nothing to do here
924 } else if cgcx.is_pe_coff {
926 .section .llvmbc,\"n\"
927 .section .llvmcmd,\"n\"
929 llvm::LLVMRustAppendModuleInlineAsm(llmod, asm.as_ptr().cast(), asm.len());
932 .section .llvmbc,\"e\"
933 .section .llvmcmd,\"e\"
935 llvm::LLVMRustAppendModuleInlineAsm(llmod, asm.as_ptr().cast(), asm.len());
939 pub unsafe fn with_llvm_pmb(
940 llmod: &llvm::Module,
941 config: &ModuleConfig,
942 opt_level: llvm::CodeGenOptLevel,
943 prepare_for_thin_lto: bool,
944 f: &mut dyn FnMut(&llvm::PassManagerBuilder),
948 // Create the PassManagerBuilder for LLVM. We configure it with
949 // reasonable defaults and prepare it to actually populate the pass
951 let builder = llvm::LLVMPassManagerBuilderCreate();
953 config.opt_size.map(|x| to_llvm_opt_settings(x).1).unwrap_or(llvm::CodeGenOptSizeNone);
954 let inline_threshold = config.inline_threshold;
955 let pgo_gen_path = get_pgo_gen_path(config);
956 let pgo_use_path = get_pgo_use_path(config);
958 llvm::LLVMRustConfigurePassManagerBuilder(
961 config.merge_functions,
962 config.vectorize_slp,
963 config.vectorize_loop,
964 prepare_for_thin_lto,
965 pgo_gen_path.as_ref().map_or(ptr::null(), |s| s.as_ptr()),
966 pgo_use_path.as_ref().map_or(ptr::null(), |s| s.as_ptr()),
969 llvm::LLVMPassManagerBuilderSetSizeLevel(builder, opt_size as u32);
971 if opt_size != llvm::CodeGenOptSizeNone {
972 llvm::LLVMPassManagerBuilderSetDisableUnrollLoops(builder, 1);
975 llvm::LLVMRustAddBuilderLibraryInfo(builder, llmod, config.no_builtins);
977 // Here we match what clang does (kinda). For O0 we only inline
978 // always-inline functions (but don't add lifetime intrinsics), at O1 we
979 // inline with lifetime intrinsics, and O2+ we add an inliner with a
980 // thresholds copied from clang.
981 match (opt_level, opt_size, inline_threshold) {
983 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, t as u32);
985 (llvm::CodeGenOptLevel::Aggressive, ..) => {
986 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 275);
988 (_, llvm::CodeGenOptSizeDefault, _) => {
989 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 75);
991 (_, llvm::CodeGenOptSizeAggressive, _) => {
992 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 25);
994 (llvm::CodeGenOptLevel::None, ..) => {
995 llvm::LLVMRustAddAlwaysInlinePass(builder, config.emit_lifetime_markers);
997 (llvm::CodeGenOptLevel::Less, ..) => {
998 llvm::LLVMRustAddAlwaysInlinePass(builder, config.emit_lifetime_markers);
1000 (llvm::CodeGenOptLevel::Default, ..) => {
1001 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 225);
1006 llvm::LLVMPassManagerBuilderDispose(builder);
1009 // Create a `__imp_<symbol> = &symbol` global for every public static `symbol`.
1010 // This is required to satisfy `dllimport` references to static data in .rlibs
1011 // when using MSVC linker. We do this only for data, as linker can fix up
1012 // code references on its own.
1013 // See #26591, #27438
1014 fn create_msvc_imps(
1015 cgcx: &CodegenContext<LlvmCodegenBackend>,
1016 llcx: &llvm::Context,
1017 llmod: &llvm::Module,
1019 if !cgcx.msvc_imps_needed {
1022 // The x86 ABI seems to require that leading underscores are added to symbol
1023 // names, so we need an extra underscore on x86. There's also a leading
1024 // '\x01' here which disables LLVM's symbol mangling (e.g., no extra
1025 // underscores added in front).
1026 let prefix = if cgcx.target_arch == "x86" { "\x01__imp__" } else { "\x01__imp_" };
1029 let i8p_ty = Type::i8p_llcx(llcx);
1030 let globals = base::iter_globals(llmod)
1032 llvm::LLVMRustGetLinkage(val) == llvm::Linkage::ExternalLinkage
1033 && llvm::LLVMIsDeclaration(val) == 0
1036 // Exclude some symbols that we know are not Rust symbols.
1037 let name = llvm::get_value_name(val);
1038 if ignored(name) { None } else { Some((val, name)) }
1040 .map(move |(val, name)| {
1041 let mut imp_name = prefix.as_bytes().to_vec();
1042 imp_name.extend(name);
1043 let imp_name = CString::new(imp_name).unwrap();
1046 .collect::<Vec<_>>();
1048 for (imp_name, val) in globals {
1049 let imp = llvm::LLVMAddGlobal(llmod, i8p_ty, imp_name.as_ptr().cast());
1050 llvm::LLVMSetInitializer(imp, consts::ptrcast(val, i8p_ty));
1051 llvm::LLVMRustSetLinkage(imp, llvm::Linkage::ExternalLinkage);
1055 // Use this function to exclude certain symbols from `__imp` generation.
1056 fn ignored(symbol_name: &[u8]) -> bool {
1057 // These are symbols generated by LLVM's profiling instrumentation
1058 symbol_name.starts_with(b"__llvm_profile_")