1use std::collections::BTreeMap;
2use std::ffi::{CStr, CString};
3use std::fs::File;
4use std::path::{Path, PathBuf};
5use std::ptr::NonNull;
6use std::sync::Arc;
7use std::{io, iter, slice};
8
9use object::read::archive::ArchiveFile;
10use object::{Object, ObjectSection};
11use rustc_codegen_ssa::back::lto::{SerializedModule, ThinModule, ThinShared};
12use rustc_codegen_ssa::back::write::{CodegenContext, FatLtoInput};
13use rustc_codegen_ssa::traits::*;
14use rustc_codegen_ssa::{ModuleCodegen, ModuleKind, looks_like_rust_object_file};
15use rustc_data_structures::fx::FxHashMap;
16use rustc_data_structures::memmap::Mmap;
17use rustc_errors::DiagCtxtHandle;
18use rustc_hir::attrs::SanitizerSet;
19use rustc_middle::bug;
20use rustc_middle::dep_graph::WorkProduct;
21use rustc_session::config::{self, Lto};
22use tracing::{debug, info};
23
24use crate::back::write::{
25 self, CodegenDiagnosticsStage, DiagnosticHandlers, bitcode_section_name, save_temp_bitcode,
26};
27use crate::errors::{LlvmError, LtoBitcodeFromRlib};
28use crate::llvm::{self, build_string};
29use crate::{LlvmCodegenBackend, ModuleLlvm, SimpleCx};
30
31const THIN_LTO_KEYS_INCR_COMP_FILE_NAME: &str = "thin-lto-past-keys.bin";
34
35fn prepare_lto(
36 cgcx: &CodegenContext<LlvmCodegenBackend>,
37 exported_symbols_for_lto: &[String],
38 each_linked_rlib_for_lto: &[PathBuf],
39 dcx: DiagCtxtHandle<'_>,
40) -> (Vec<CString>, Vec<(SerializedModule<ModuleBuffer>, CString)>) {
41 let mut symbols_below_threshold = exported_symbols_for_lto
42 .iter()
43 .map(|symbol| CString::new(symbol.to_owned()).unwrap())
44 .collect::<Vec<CString>>();
45
46 if cgcx.regular_module_config.instrument_coverage
47 || cgcx.regular_module_config.pgo_gen.enabled()
48 {
49 const PROFILER_WEAK_SYMBOLS: [&CStr; 2] =
53 [c"__llvm_profile_raw_version", c"__llvm_profile_filename"];
54
55 symbols_below_threshold.extend(PROFILER_WEAK_SYMBOLS.iter().map(|&sym| sym.to_owned()));
56 }
57
58 if cgcx.regular_module_config.sanitizer.contains(SanitizerSet::MEMORY) {
59 let mut msan_weak_symbols = Vec::new();
60
61 if cgcx.regular_module_config.sanitizer_recover.contains(SanitizerSet::MEMORY) {
63 msan_weak_symbols.push(c"__msan_keep_going");
64 }
65
66 if cgcx.regular_module_config.sanitizer_memory_track_origins != 0 {
67 msan_weak_symbols.push(c"__msan_track_origins");
68 }
69
70 symbols_below_threshold.extend(msan_weak_symbols.into_iter().map(|sym| sym.to_owned()));
71 }
72
73 symbols_below_threshold.push(c"___asan_globals_registered".to_owned());
76
77 symbols_below_threshold.push(c"__llvm_profile_counter_bias".to_owned());
81
82 let mut upstream_modules = Vec::new();
89 if cgcx.lto != Lto::ThinLocal {
90 for path in each_linked_rlib_for_lto {
91 let archive_data = unsafe {
92 Mmap::map(std::fs::File::open(&path).expect("couldn't open rlib"))
93 .expect("couldn't map rlib")
94 };
95 let archive = ArchiveFile::parse(&*archive_data).expect("wanted an rlib");
96 let obj_files = archive
97 .members()
98 .filter_map(|child| {
99 child.ok().and_then(|c| {
100 std::str::from_utf8(c.name()).ok().map(|name| (name.trim(), c))
101 })
102 })
103 .filter(|&(name, _)| looks_like_rust_object_file(name));
104 for (name, child) in obj_files {
105 info!("adding bitcode from {}", name);
106 match get_bitcode_slice_from_object_data(
107 child.data(&*archive_data).expect("corrupt rlib"),
108 cgcx,
109 ) {
110 Ok(data) => {
111 let module = SerializedModule::FromRlib(data.to_vec());
112 upstream_modules.push((module, CString::new(name).unwrap()));
113 }
114 Err(e) => dcx.emit_fatal(e),
115 }
116 }
117 }
118 }
119
120 (symbols_below_threshold, upstream_modules)
121}
122
123fn get_bitcode_slice_from_object_data<'a>(
124 obj: &'a [u8],
125 cgcx: &CodegenContext<LlvmCodegenBackend>,
126) -> Result<&'a [u8], LtoBitcodeFromRlib> {
127 if obj.starts_with(b"\xDE\xC0\x17\x0B") || obj.starts_with(b"BC\xC0\xDE") {
131 return Ok(obj);
132 }
133 let section_name = bitcode_section_name(cgcx).to_str().unwrap().trim_start_matches("__LLVM,");
137
138 let obj =
139 object::File::parse(obj).map_err(|err| LtoBitcodeFromRlib { err: err.to_string() })?;
140
141 let section = obj
142 .section_by_name(section_name)
143 .ok_or_else(|| LtoBitcodeFromRlib { err: format!("Can't find section {section_name}") })?;
144
145 section.data().map_err(|err| LtoBitcodeFromRlib { err: err.to_string() })
146}
147
148pub(crate) fn run_fat(
151 cgcx: &CodegenContext<LlvmCodegenBackend>,
152 exported_symbols_for_lto: &[String],
153 each_linked_rlib_for_lto: &[PathBuf],
154 modules: Vec<FatLtoInput<LlvmCodegenBackend>>,
155) -> ModuleCodegen<ModuleLlvm> {
156 let dcx = cgcx.create_dcx();
157 let dcx = dcx.handle();
158 let (symbols_below_threshold, upstream_modules) =
159 prepare_lto(cgcx, exported_symbols_for_lto, each_linked_rlib_for_lto, dcx);
160 let symbols_below_threshold =
161 symbols_below_threshold.iter().map(|c| c.as_ptr()).collect::<Vec<_>>();
162 fat_lto(cgcx, dcx, modules, upstream_modules, &symbols_below_threshold)
163}
164
165pub(crate) fn run_thin(
169 cgcx: &CodegenContext<LlvmCodegenBackend>,
170 exported_symbols_for_lto: &[String],
171 each_linked_rlib_for_lto: &[PathBuf],
172 modules: Vec<(String, ThinBuffer)>,
173 cached_modules: Vec<(SerializedModule<ModuleBuffer>, WorkProduct)>,
174) -> (Vec<ThinModule<LlvmCodegenBackend>>, Vec<WorkProduct>) {
175 let dcx = cgcx.create_dcx();
176 let dcx = dcx.handle();
177 let (symbols_below_threshold, upstream_modules) =
178 prepare_lto(cgcx, exported_symbols_for_lto, each_linked_rlib_for_lto, dcx);
179 let symbols_below_threshold =
180 symbols_below_threshold.iter().map(|c| c.as_ptr()).collect::<Vec<_>>();
181 if cgcx.opts.cg.linker_plugin_lto.enabled() {
182 unreachable!(
183 "We should never reach this case if the LTO step \
184 is deferred to the linker"
185 );
186 }
187 thin_lto(cgcx, dcx, modules, upstream_modules, cached_modules, &symbols_below_threshold)
188}
189
190pub(crate) fn prepare_thin(
191 module: ModuleCodegen<ModuleLlvm>,
192 emit_summary: bool,
193) -> (String, ThinBuffer) {
194 let name = module.name;
195 let buffer = ThinBuffer::new(module.module_llvm.llmod(), true, emit_summary);
196 (name, buffer)
197}
198
199fn fat_lto(
200 cgcx: &CodegenContext<LlvmCodegenBackend>,
201 dcx: DiagCtxtHandle<'_>,
202 modules: Vec<FatLtoInput<LlvmCodegenBackend>>,
203 mut serialized_modules: Vec<(SerializedModule<ModuleBuffer>, CString)>,
204 symbols_below_threshold: &[*const libc::c_char],
205) -> ModuleCodegen<ModuleLlvm> {
206 let _timer = cgcx.prof.generic_activity("LLVM_fat_lto_build_monolithic_module");
207 info!("going for a fat lto");
208
209 let mut in_memory = Vec::new();
216 for module in modules {
217 match module {
218 FatLtoInput::InMemory(m) => in_memory.push(m),
219 FatLtoInput::Serialized { name, buffer } => {
220 info!("pushing serialized module {:?}", name);
221 serialized_modules.push((buffer, CString::new(name).unwrap()));
222 }
223 }
224 }
225
226 let costliest_module = in_memory
236 .iter()
237 .enumerate()
238 .filter(|&(_, module)| module.kind == ModuleKind::Regular)
239 .map(|(i, module)| {
240 let cost = unsafe { llvm::LLVMRustModuleCost(module.module_llvm.llmod()) };
241 (cost, i)
242 })
243 .max();
244
245 let module: ModuleCodegen<ModuleLlvm> = match costliest_module {
251 Some((_cost, i)) => in_memory.remove(i),
252 None => {
253 assert!(!serialized_modules.is_empty(), "must have at least one serialized module");
254 let (buffer, name) = serialized_modules.remove(0);
255 info!("no in-memory regular modules to choose from, parsing {:?}", name);
256 let llvm_module = ModuleLlvm::parse(cgcx, &name, buffer.data(), dcx);
257 ModuleCodegen::new_regular(name.into_string().unwrap(), llvm_module)
258 }
259 };
260 {
261 let (llcx, llmod) = {
262 let llvm = &module.module_llvm;
263 (&llvm.llcx, llvm.llmod())
264 };
265 info!("using {:?} as a base module", module.name);
266
267 let _handler =
271 DiagnosticHandlers::new(cgcx, dcx, llcx, &module, CodegenDiagnosticsStage::LTO);
272
273 for module in in_memory {
279 let buffer = ModuleBuffer::new(module.module_llvm.llmod());
280 let llmod_id = CString::new(&module.name[..]).unwrap();
281 serialized_modules.push((SerializedModule::Local(buffer), llmod_id));
282 }
283 serialized_modules.sort_by(|module1, module2| module1.1.cmp(&module2.1));
285
286 let mut linker = Linker::new(llmod);
289 for (bc_decoded, name) in serialized_modules {
290 let _timer = cgcx
291 .prof
292 .generic_activity_with_arg_recorder("LLVM_fat_lto_link_module", |recorder| {
293 recorder.record_arg(format!("{name:?}"))
294 });
295 info!("linking {:?}", name);
296 let data = bc_decoded.data();
297 linker
298 .add(data)
299 .unwrap_or_else(|()| write::llvm_err(dcx, LlvmError::LoadBitcode { name }));
300 }
301 drop(linker);
302 save_temp_bitcode(cgcx, &module, "lto.input");
303
304 unsafe {
306 let ptr = symbols_below_threshold.as_ptr();
307 llvm::LLVMRustRunRestrictionPass(
308 llmod,
309 ptr as *const *const libc::c_char,
310 symbols_below_threshold.len() as libc::size_t,
311 );
312 }
313 save_temp_bitcode(cgcx, &module, "lto.after-restriction");
314 }
315
316 module
317}
318
319pub(crate) struct Linker<'a>(&'a mut llvm::Linker<'a>);
320
321impl<'a> Linker<'a> {
322 pub(crate) fn new(llmod: &'a llvm::Module) -> Self {
323 unsafe { Linker(llvm::LLVMRustLinkerNew(llmod)) }
324 }
325
326 pub(crate) fn add(&mut self, bytecode: &[u8]) -> Result<(), ()> {
327 unsafe {
328 if llvm::LLVMRustLinkerAdd(
329 self.0,
330 bytecode.as_ptr() as *const libc::c_char,
331 bytecode.len(),
332 ) {
333 Ok(())
334 } else {
335 Err(())
336 }
337 }
338 }
339}
340
341impl Drop for Linker<'_> {
342 fn drop(&mut self) {
343 unsafe {
344 llvm::LLVMRustLinkerFree(&mut *(self.0 as *mut _));
345 }
346 }
347}
348
349fn thin_lto(
380 cgcx: &CodegenContext<LlvmCodegenBackend>,
381 dcx: DiagCtxtHandle<'_>,
382 modules: Vec<(String, ThinBuffer)>,
383 serialized_modules: Vec<(SerializedModule<ModuleBuffer>, CString)>,
384 cached_modules: Vec<(SerializedModule<ModuleBuffer>, WorkProduct)>,
385 symbols_below_threshold: &[*const libc::c_char],
386) -> (Vec<ThinModule<LlvmCodegenBackend>>, Vec<WorkProduct>) {
387 let _timer = cgcx.prof.generic_activity("LLVM_thin_lto_global_analysis");
388 unsafe {
389 info!("going for that thin, thin LTO");
390
391 let green_modules: FxHashMap<_, _> =
392 cached_modules.iter().map(|(_, wp)| (wp.cgu_name.clone(), wp.clone())).collect();
393
394 let full_scope_len = modules.len() + serialized_modules.len() + cached_modules.len();
395 let mut thin_buffers = Vec::with_capacity(modules.len());
396 let mut module_names = Vec::with_capacity(full_scope_len);
397 let mut thin_modules = Vec::with_capacity(full_scope_len);
398
399 for (i, (name, buffer)) in modules.into_iter().enumerate() {
400 info!("local module: {} - {}", i, name);
401 let cname = CString::new(name.as_bytes()).unwrap();
402 thin_modules.push(llvm::ThinLTOModule {
403 identifier: cname.as_ptr(),
404 data: buffer.data().as_ptr(),
405 len: buffer.data().len(),
406 });
407 thin_buffers.push(buffer);
408 module_names.push(cname);
409 }
410
411 let mut serialized = Vec::with_capacity(serialized_modules.len() + cached_modules.len());
428
429 let cached_modules =
430 cached_modules.into_iter().map(|(sm, wp)| (sm, CString::new(wp.cgu_name).unwrap()));
431
432 for (module, name) in serialized_modules.into_iter().chain(cached_modules) {
433 info!("upstream or cached module {:?}", name);
434 thin_modules.push(llvm::ThinLTOModule {
435 identifier: name.as_ptr(),
436 data: module.data().as_ptr(),
437 len: module.data().len(),
438 });
439 serialized.push(module);
440 module_names.push(name);
441 }
442
443 assert_eq!(thin_modules.len(), module_names.len());
445
446 let data = llvm::LLVMRustCreateThinLTOData(
451 thin_modules.as_ptr(),
452 thin_modules.len(),
453 symbols_below_threshold.as_ptr(),
454 symbols_below_threshold.len(),
455 )
456 .unwrap_or_else(|| write::llvm_err(dcx, LlvmError::PrepareThinLtoContext));
457
458 let data = ThinData(data);
459
460 info!("thin LTO data created");
461
462 let (key_map_path, prev_key_map, curr_key_map) = if let Some(ref incr_comp_session_dir) =
463 cgcx.incr_comp_session_dir
464 {
465 let path = incr_comp_session_dir.join(THIN_LTO_KEYS_INCR_COMP_FILE_NAME);
466 let prev =
470 if path.exists() { ThinLTOKeysMap::load_from_file(&path).ok() } else { None };
471 let curr = ThinLTOKeysMap::from_thin_lto_modules(&data, &thin_modules, &module_names);
472 (Some(path), prev, curr)
473 } else {
474 assert!(green_modules.is_empty());
477 let curr = ThinLTOKeysMap::default();
478 (None, None, curr)
479 };
480 info!("thin LTO cache key map loaded");
481 info!("prev_key_map: {:#?}", prev_key_map);
482 info!("curr_key_map: {:#?}", curr_key_map);
483
484 let shared = Arc::new(ThinShared {
489 data,
490 thin_buffers,
491 serialized_modules: serialized,
492 module_names,
493 });
494
495 let mut copy_jobs = vec![];
496 let mut opt_jobs = vec![];
497
498 info!("checking which modules can be-reused and which have to be re-optimized.");
499 for (module_index, module_name) in shared.module_names.iter().enumerate() {
500 let module_name = module_name_to_str(module_name);
501 if let (Some(prev_key_map), true) =
502 (prev_key_map.as_ref(), green_modules.contains_key(module_name))
503 {
504 assert!(cgcx.incr_comp_session_dir.is_some());
505
506 if prev_key_map.keys.get(module_name) == curr_key_map.keys.get(module_name) {
509 let work_product = green_modules[module_name].clone();
510 copy_jobs.push(work_product);
511 info!(" - {}: re-used", module_name);
512 assert!(cgcx.incr_comp_session_dir.is_some());
513 continue;
514 }
515 }
516
517 info!(" - {}: re-compiled", module_name);
518 opt_jobs.push(ThinModule { shared: Arc::clone(&shared), idx: module_index });
519 }
520
521 if let Some(path) = key_map_path
524 && let Err(err) = curr_key_map.save_to_file(&path)
525 {
526 write::llvm_err(dcx, LlvmError::WriteThinLtoKey { err });
527 }
528
529 (opt_jobs, copy_jobs)
530 }
531}
532
533fn enable_autodiff_settings(ad: &[config::AutoDiff]) {
534 for val in ad {
535 match val {
537 config::AutoDiff::PrintPerf => {
538 llvm::set_print_perf(true);
539 }
540 config::AutoDiff::PrintAA => {
541 llvm::set_print_activity(true);
542 }
543 config::AutoDiff::PrintTA => {
544 llvm::set_print_type(true);
545 }
546 config::AutoDiff::PrintTAFn(fun) => {
547 llvm::set_print_type(true); llvm::set_print_type_fun(&fun); }
550 config::AutoDiff::Inline => {
551 llvm::set_inline(true);
552 }
553 config::AutoDiff::LooseTypes => {
554 llvm::set_loose_types(true);
555 }
556 config::AutoDiff::PrintSteps => {
557 llvm::set_print(true);
558 }
559 config::AutoDiff::PrintPasses => {}
561 config::AutoDiff::PrintModBefore => {}
563 config::AutoDiff::PrintModAfter => {}
565 config::AutoDiff::PrintModFinal => {}
567 config::AutoDiff::Enable => {}
569 config::AutoDiff::NoPostopt => {}
571 }
572 }
573 llvm::set_strict_aliasing(false);
575 llvm::set_rust_rules(true);
577}
578
579pub(crate) fn run_pass_manager(
580 cgcx: &CodegenContext<LlvmCodegenBackend>,
581 dcx: DiagCtxtHandle<'_>,
582 module: &mut ModuleCodegen<ModuleLlvm>,
583 thin: bool,
584) {
585 let _timer = cgcx.prof.generic_activity_with_arg("LLVM_lto_optimize", &*module.name);
586 let config = cgcx.config(module.kind);
587
588 debug!("running the pass manager");
594 let opt_stage = if thin { llvm::OptStage::ThinLTO } else { llvm::OptStage::FatLTO };
595 let opt_level = config.opt_level.unwrap_or(config::OptLevel::No);
596
597 let enable_ad = config.autodiff.contains(&config::AutoDiff::Enable);
604 let enable_gpu = config.offload.contains(&config::Offload::Enable);
605 let stage = if thin {
606 write::AutodiffStage::PreAD
607 } else {
608 if enable_ad { write::AutodiffStage::DuringAD } else { write::AutodiffStage::PostAD }
609 };
610
611 if enable_ad {
612 enable_autodiff_settings(&config.autodiff);
613 }
614
615 unsafe {
616 write::llvm_optimize(cgcx, dcx, module, None, config, opt_level, opt_stage, stage);
617 }
618
619 if enable_gpu && !thin {
620 let cx =
621 SimpleCx::new(module.module_llvm.llmod(), &module.module_llvm.llcx, cgcx.pointer_size);
622 crate::builder::gpu_offload::handle_gpu_code(cgcx, &cx);
623 }
624
625 if cfg!(llvm_enzyme) && enable_ad && !thin {
626 let opt_stage = llvm::OptStage::FatLTO;
627 let stage = write::AutodiffStage::PostAD;
628 if !config.autodiff.contains(&config::AutoDiff::NoPostopt) {
629 unsafe {
630 write::llvm_optimize(cgcx, dcx, module, None, config, opt_level, opt_stage, stage);
631 }
632 }
633
634 if config.autodiff.contains(&config::AutoDiff::PrintModFinal) {
637 unsafe { llvm::LLVMDumpModule(module.module_llvm.llmod()) };
638 }
639 }
640
641 debug!("lto done");
642}
643
644pub struct ModuleBuffer(&'static mut llvm::ModuleBuffer);
645
646unsafe impl Send for ModuleBuffer {}
647unsafe impl Sync for ModuleBuffer {}
648
649impl ModuleBuffer {
650 pub(crate) fn new(m: &llvm::Module) -> ModuleBuffer {
651 ModuleBuffer(unsafe { llvm::LLVMRustModuleBufferCreate(m) })
652 }
653}
654
655impl ModuleBufferMethods for ModuleBuffer {
656 fn data(&self) -> &[u8] {
657 unsafe {
658 let ptr = llvm::LLVMRustModuleBufferPtr(self.0);
659 let len = llvm::LLVMRustModuleBufferLen(self.0);
660 slice::from_raw_parts(ptr, len)
661 }
662 }
663}
664
665impl Drop for ModuleBuffer {
666 fn drop(&mut self) {
667 unsafe {
668 llvm::LLVMRustModuleBufferFree(&mut *(self.0 as *mut _));
669 }
670 }
671}
672
673pub struct ThinData(&'static mut llvm::ThinLTOData);
674
675unsafe impl Send for ThinData {}
676unsafe impl Sync for ThinData {}
677
678impl Drop for ThinData {
679 fn drop(&mut self) {
680 unsafe {
681 llvm::LLVMRustFreeThinLTOData(&mut *(self.0 as *mut _));
682 }
683 }
684}
685
686pub struct ThinBuffer(&'static mut llvm::ThinLTOBuffer);
687
688unsafe impl Send for ThinBuffer {}
689unsafe impl Sync for ThinBuffer {}
690
691impl ThinBuffer {
692 pub(crate) fn new(m: &llvm::Module, is_thin: bool, emit_summary: bool) -> ThinBuffer {
693 unsafe {
694 let buffer = llvm::LLVMRustThinLTOBufferCreate(m, is_thin, emit_summary);
695 ThinBuffer(buffer)
696 }
697 }
698
699 pub(crate) unsafe fn from_raw_ptr(ptr: *mut llvm::ThinLTOBuffer) -> ThinBuffer {
700 let mut ptr = NonNull::new(ptr).unwrap();
701 ThinBuffer(unsafe { ptr.as_mut() })
702 }
703}
704
705impl ThinBufferMethods for ThinBuffer {
706 fn data(&self) -> &[u8] {
707 unsafe {
708 let ptr = llvm::LLVMRustThinLTOBufferPtr(self.0) as *const _;
709 let len = llvm::LLVMRustThinLTOBufferLen(self.0);
710 slice::from_raw_parts(ptr, len)
711 }
712 }
713
714 fn thin_link_data(&self) -> &[u8] {
715 unsafe {
716 let ptr = llvm::LLVMRustThinLTOBufferThinLinkDataPtr(self.0) as *const _;
717 let len = llvm::LLVMRustThinLTOBufferThinLinkDataLen(self.0);
718 slice::from_raw_parts(ptr, len)
719 }
720 }
721}
722
723impl Drop for ThinBuffer {
724 fn drop(&mut self) {
725 unsafe {
726 llvm::LLVMRustThinLTOBufferFree(&mut *(self.0 as *mut _));
727 }
728 }
729}
730
731pub(crate) fn optimize_thin_module(
732 thin_module: ThinModule<LlvmCodegenBackend>,
733 cgcx: &CodegenContext<LlvmCodegenBackend>,
734) -> ModuleCodegen<ModuleLlvm> {
735 let dcx = cgcx.create_dcx();
736 let dcx = dcx.handle();
737
738 let module_name = &thin_module.shared.module_names[thin_module.idx];
739
740 let module_llvm = ModuleLlvm::parse(cgcx, module_name, thin_module.data(), dcx);
746 let mut module = ModuleCodegen::new_regular(thin_module.name(), module_llvm);
747 if cgcx.config(ModuleKind::Regular).embed_bitcode() {
749 module.thin_lto_buffer = Some(thin_module.data().to_vec());
750 }
751 {
752 let target = &*module.module_llvm.tm;
753 let llmod = module.module_llvm.llmod();
754 save_temp_bitcode(cgcx, &module, "thin-lto-input");
755
756 {
765 let _timer =
766 cgcx.prof.generic_activity_with_arg("LLVM_thin_lto_rename", thin_module.name());
767 unsafe {
768 llvm::LLVMRustPrepareThinLTORename(thin_module.shared.data.0, llmod, target.raw())
769 };
770 save_temp_bitcode(cgcx, &module, "thin-lto-after-rename");
771 }
772
773 {
774 let _timer = cgcx
775 .prof
776 .generic_activity_with_arg("LLVM_thin_lto_resolve_weak", thin_module.name());
777 if unsafe { !llvm::LLVMRustPrepareThinLTOResolveWeak(thin_module.shared.data.0, llmod) }
778 {
779 write::llvm_err(dcx, LlvmError::PrepareThinLtoModule);
780 }
781 save_temp_bitcode(cgcx, &module, "thin-lto-after-resolve");
782 }
783
784 {
785 let _timer = cgcx
786 .prof
787 .generic_activity_with_arg("LLVM_thin_lto_internalize", thin_module.name());
788 if unsafe { !llvm::LLVMRustPrepareThinLTOInternalize(thin_module.shared.data.0, llmod) }
789 {
790 write::llvm_err(dcx, LlvmError::PrepareThinLtoModule);
791 }
792 save_temp_bitcode(cgcx, &module, "thin-lto-after-internalize");
793 }
794
795 {
796 let _timer =
797 cgcx.prof.generic_activity_with_arg("LLVM_thin_lto_import", thin_module.name());
798 if unsafe {
799 !llvm::LLVMRustPrepareThinLTOImport(thin_module.shared.data.0, llmod, target.raw())
800 } {
801 write::llvm_err(dcx, LlvmError::PrepareThinLtoModule);
802 }
803 save_temp_bitcode(cgcx, &module, "thin-lto-after-import");
804 }
805
806 {
812 info!("running thin lto passes over {}", module.name);
813 run_pass_manager(cgcx, dcx, &mut module, true);
814 save_temp_bitcode(cgcx, &module, "thin-lto-after-pm");
815 }
816 }
817 module
818}
819
820#[derive(Debug, Default)]
822struct ThinLTOKeysMap {
823 keys: BTreeMap<String, String>,
825}
826
827impl ThinLTOKeysMap {
828 fn save_to_file(&self, path: &Path) -> io::Result<()> {
829 use std::io::Write;
830 let mut writer = File::create_buffered(path)?;
831 for (module, key) in &self.keys {
834 writeln!(writer, "{module} {key}")?;
835 }
836 Ok(())
837 }
838
839 fn load_from_file(path: &Path) -> io::Result<Self> {
840 use std::io::BufRead;
841 let mut keys = BTreeMap::default();
842 let file = File::open_buffered(path)?;
843 for line in file.lines() {
844 let line = line?;
845 let mut split = line.split(' ');
846 let module = split.next().unwrap();
847 let key = split.next().unwrap();
848 assert_eq!(split.next(), None, "Expected two space-separated values, found {line:?}");
849 keys.insert(module.to_string(), key.to_string());
850 }
851 Ok(Self { keys })
852 }
853
854 fn from_thin_lto_modules(
855 data: &ThinData,
856 modules: &[llvm::ThinLTOModule],
857 names: &[CString],
858 ) -> Self {
859 let keys = iter::zip(modules, names)
860 .map(|(module, name)| {
861 let key = build_string(|rust_str| unsafe {
862 llvm::LLVMRustComputeLTOCacheKey(rust_str, module.identifier, data.0);
863 })
864 .expect("Invalid ThinLTO module key");
865 (module_name_to_str(name).to_string(), key)
866 })
867 .collect();
868 Self { keys }
869 }
870}
871
872fn module_name_to_str(c_str: &CStr) -> &str {
873 c_str.to_str().unwrap_or_else(|e| {
874 bug!("Encountered non-utf8 LLVM module name `{}`: {}", c_str.to_string_lossy(), e)
875 })
876}
877
878pub(crate) fn parse_module<'a>(
879 cx: &'a llvm::Context,
880 name: &CStr,
881 data: &[u8],
882 dcx: DiagCtxtHandle<'_>,
883) -> &'a llvm::Module {
884 unsafe {
885 llvm::LLVMRustParseBitcodeForLTO(cx, data.as_ptr(), data.len(), name.as_ptr())
886 .unwrap_or_else(|| write::llvm_err(dcx, LlvmError::ParseBitcode))
887 }
888}