rustc_codegen_llvm/back/
lto.rs

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, 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
31/// We keep track of the computed LTO cache keys from the previous
32/// session to determine which CGUs we can reuse.
33const 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.module_config.instrument_coverage || cgcx.module_config.pgo_gen.enabled() {
47        // These are weak symbols that point to the profile version and the
48        // profile name, which need to be treated as exported so LTO doesn't nix
49        // them.
50        const PROFILER_WEAK_SYMBOLS: [&CStr; 2] =
51            [c"__llvm_profile_raw_version", c"__llvm_profile_filename"];
52
53        symbols_below_threshold.extend(PROFILER_WEAK_SYMBOLS.iter().map(|&sym| sym.to_owned()));
54    }
55
56    if cgcx.module_config.sanitizer.contains(SanitizerSet::MEMORY) {
57        let mut msan_weak_symbols = Vec::new();
58
59        // Similar to profiling, preserve weak msan symbol during LTO.
60        if cgcx.module_config.sanitizer_recover.contains(SanitizerSet::MEMORY) {
61            msan_weak_symbols.push(c"__msan_keep_going");
62        }
63
64        if cgcx.module_config.sanitizer_memory_track_origins != 0 {
65            msan_weak_symbols.push(c"__msan_track_origins");
66        }
67
68        symbols_below_threshold.extend(msan_weak_symbols.into_iter().map(|sym| sym.to_owned()));
69    }
70
71    // Preserve LLVM-injected, ASAN-related symbols.
72    // See also https://github.com/rust-lang/rust/issues/113404.
73    symbols_below_threshold.push(c"___asan_globals_registered".to_owned());
74
75    // __llvm_profile_counter_bias is pulled in at link time by an undefined reference to
76    // __llvm_profile_runtime, therefore we won't know until link time if this symbol
77    // should have default visibility.
78    symbols_below_threshold.push(c"__llvm_profile_counter_bias".to_owned());
79
80    // If we're performing LTO for the entire crate graph, then for each of our
81    // upstream dependencies, find the corresponding rlib and load the bitcode
82    // from the archive.
83    //
84    // We save off all the bytecode and LLVM module ids for later processing
85    // with either fat or thin LTO
86    let mut upstream_modules = Vec::new();
87    if cgcx.lto != Lto::ThinLocal {
88        for path in each_linked_rlib_for_lto {
89            let archive_data = unsafe {
90                Mmap::map(std::fs::File::open(&path).expect("couldn't open rlib"))
91                    .expect("couldn't map rlib")
92            };
93            let archive = ArchiveFile::parse(&*archive_data).expect("wanted an rlib");
94            let obj_files = archive
95                .members()
96                .filter_map(|child| {
97                    child.ok().and_then(|c| {
98                        std::str::from_utf8(c.name()).ok().map(|name| (name.trim(), c))
99                    })
100                })
101                .filter(|&(name, _)| looks_like_rust_object_file(name));
102            for (name, child) in obj_files {
103                info!("adding bitcode from {}", name);
104                match get_bitcode_slice_from_object_data(
105                    child.data(&*archive_data).expect("corrupt rlib"),
106                    cgcx,
107                ) {
108                    Ok(data) => {
109                        let module = SerializedModule::FromRlib(data.to_vec());
110                        upstream_modules.push((module, CString::new(name).unwrap()));
111                    }
112                    Err(e) => dcx.emit_fatal(e),
113                }
114            }
115        }
116    }
117
118    (symbols_below_threshold, upstream_modules)
119}
120
121fn get_bitcode_slice_from_object_data<'a>(
122    obj: &'a [u8],
123    cgcx: &CodegenContext<LlvmCodegenBackend>,
124) -> Result<&'a [u8], LtoBitcodeFromRlib> {
125    // We're about to assume the data here is an object file with sections, but if it's raw LLVM IR
126    // that won't work. Fortunately, if that's what we have we can just return the object directly,
127    // so we sniff the relevant magic strings here and return.
128    if obj.starts_with(b"\xDE\xC0\x17\x0B") || obj.starts_with(b"BC\xC0\xDE") {
129        return Ok(obj);
130    }
131    // We drop the "__LLVM," prefix here because on Apple platforms there's a notion of "segment
132    // name" which in the public API for sections gets treated as part of the section name, but
133    // internally in MachOObjectFile.cpp gets treated separately.
134    let section_name = bitcode_section_name(cgcx).to_str().unwrap().trim_start_matches("__LLVM,");
135
136    let obj =
137        object::File::parse(obj).map_err(|err| LtoBitcodeFromRlib { err: err.to_string() })?;
138
139    let section = obj
140        .section_by_name(section_name)
141        .ok_or_else(|| LtoBitcodeFromRlib { err: format!("Can't find section {section_name}") })?;
142
143    section.data().map_err(|err| LtoBitcodeFromRlib { err: err.to_string() })
144}
145
146/// Performs fat LTO by merging all modules into a single one and returning it
147/// for further optimization.
148pub(crate) fn run_fat(
149    cgcx: &CodegenContext<LlvmCodegenBackend>,
150    exported_symbols_for_lto: &[String],
151    each_linked_rlib_for_lto: &[PathBuf],
152    modules: Vec<FatLtoInput<LlvmCodegenBackend>>,
153) -> ModuleCodegen<ModuleLlvm> {
154    let dcx = cgcx.create_dcx();
155    let dcx = dcx.handle();
156    let (symbols_below_threshold, upstream_modules) =
157        prepare_lto(cgcx, exported_symbols_for_lto, each_linked_rlib_for_lto, dcx);
158    let symbols_below_threshold =
159        symbols_below_threshold.iter().map(|c| c.as_ptr()).collect::<Vec<_>>();
160    fat_lto(cgcx, dcx, modules, upstream_modules, &symbols_below_threshold)
161}
162
163/// Performs thin LTO by performing necessary global analysis and returning two
164/// lists, one of the modules that need optimization and another for modules that
165/// can simply be copied over from the incr. comp. cache.
166pub(crate) fn run_thin(
167    cgcx: &CodegenContext<LlvmCodegenBackend>,
168    exported_symbols_for_lto: &[String],
169    each_linked_rlib_for_lto: &[PathBuf],
170    modules: Vec<(String, ThinBuffer)>,
171    cached_modules: Vec<(SerializedModule<ModuleBuffer>, WorkProduct)>,
172) -> (Vec<ThinModule<LlvmCodegenBackend>>, Vec<WorkProduct>) {
173    let dcx = cgcx.create_dcx();
174    let dcx = dcx.handle();
175    let (symbols_below_threshold, upstream_modules) =
176        prepare_lto(cgcx, exported_symbols_for_lto, each_linked_rlib_for_lto, dcx);
177    let symbols_below_threshold =
178        symbols_below_threshold.iter().map(|c| c.as_ptr()).collect::<Vec<_>>();
179    if cgcx.opts.cg.linker_plugin_lto.enabled() {
180        unreachable!(
181            "We should never reach this case if the LTO step \
182                      is deferred to the linker"
183        );
184    }
185    thin_lto(cgcx, dcx, modules, upstream_modules, cached_modules, &symbols_below_threshold)
186}
187
188pub(crate) fn prepare_thin(
189    module: ModuleCodegen<ModuleLlvm>,
190    emit_summary: bool,
191) -> (String, ThinBuffer) {
192    let name = module.name;
193    let buffer = ThinBuffer::new(module.module_llvm.llmod(), true, emit_summary);
194    (name, buffer)
195}
196
197fn fat_lto(
198    cgcx: &CodegenContext<LlvmCodegenBackend>,
199    dcx: DiagCtxtHandle<'_>,
200    modules: Vec<FatLtoInput<LlvmCodegenBackend>>,
201    mut serialized_modules: Vec<(SerializedModule<ModuleBuffer>, CString)>,
202    symbols_below_threshold: &[*const libc::c_char],
203) -> ModuleCodegen<ModuleLlvm> {
204    let _timer = cgcx.prof.generic_activity("LLVM_fat_lto_build_monolithic_module");
205    info!("going for a fat lto");
206
207    // Sort out all our lists of incoming modules into two lists.
208    //
209    // * `serialized_modules` (also and argument to this function) contains all
210    //   modules that are serialized in-memory.
211    // * `in_memory` contains modules which are already parsed and in-memory,
212    //   such as from multi-CGU builds.
213    let mut in_memory = Vec::new();
214    for module in modules {
215        match module {
216            FatLtoInput::InMemory(m) => in_memory.push(m),
217            FatLtoInput::Serialized { name, buffer } => {
218                info!("pushing serialized module {:?}", name);
219                serialized_modules.push((buffer, CString::new(name).unwrap()));
220            }
221        }
222    }
223
224    // Find the "costliest" module and merge everything into that codegen unit.
225    // All the other modules will be serialized and reparsed into the new
226    // context, so this hopefully avoids serializing and parsing the largest
227    // codegen unit.
228    let costliest_module = in_memory
229        .iter()
230        .enumerate()
231        .map(|(i, module)| {
232            let cost = unsafe { llvm::LLVMRustModuleCost(module.module_llvm.llmod()) };
233            (cost, i)
234        })
235        .max();
236
237    // If we found a costliest module, we're good to go. Otherwise all our
238    // inputs were serialized which could happen in the case, for example, that
239    // all our inputs were incrementally reread from the cache and we're just
240    // re-executing the LTO passes. If that's the case deserialize the first
241    // module and create a linker with it.
242    let module: ModuleCodegen<ModuleLlvm> = match costliest_module {
243        Some((_cost, i)) => in_memory.remove(i),
244        None => {
245            assert!(!serialized_modules.is_empty(), "must have at least one serialized module");
246            let (buffer, name) = serialized_modules.remove(0);
247            info!("no in-memory regular modules to choose from, parsing {:?}", name);
248            let llvm_module = ModuleLlvm::parse(cgcx, &name, buffer.data(), dcx);
249            ModuleCodegen::new_regular(name.into_string().unwrap(), llvm_module)
250        }
251    };
252    {
253        let (llcx, llmod) = {
254            let llvm = &module.module_llvm;
255            (&llvm.llcx, llvm.llmod())
256        };
257        info!("using {:?} as a base module", module.name);
258
259        // The linking steps below may produce errors and diagnostics within LLVM
260        // which we'd like to handle and print, so set up our diagnostic handlers
261        // (which get unregistered when they go out of scope below).
262        let _handler =
263            DiagnosticHandlers::new(cgcx, dcx, llcx, &module, CodegenDiagnosticsStage::LTO);
264
265        // For all other modules we codegened we'll need to link them into our own
266        // bitcode. All modules were codegened in their own LLVM context, however,
267        // and we want to move everything to the same LLVM context. Currently the
268        // way we know of to do that is to serialize them to a string and them parse
269        // them later. Not great but hey, that's why it's "fat" LTO, right?
270        for module in in_memory {
271            let buffer = ModuleBuffer::new(module.module_llvm.llmod());
272            let llmod_id = CString::new(&module.name[..]).unwrap();
273            serialized_modules.push((SerializedModule::Local(buffer), llmod_id));
274        }
275        // Sort the modules to ensure we produce deterministic results.
276        serialized_modules.sort_by(|module1, module2| module1.1.cmp(&module2.1));
277
278        // For all serialized bitcode files we parse them and link them in as we did
279        // above, this is all mostly handled in C++.
280        let mut linker = Linker::new(llmod);
281        for (bc_decoded, name) in serialized_modules {
282            let _timer = cgcx
283                .prof
284                .generic_activity_with_arg_recorder("LLVM_fat_lto_link_module", |recorder| {
285                    recorder.record_arg(format!("{name:?}"))
286                });
287            info!("linking {:?}", name);
288            let data = bc_decoded.data();
289            linker
290                .add(data)
291                .unwrap_or_else(|()| write::llvm_err(dcx, LlvmError::LoadBitcode { name }));
292        }
293        drop(linker);
294        save_temp_bitcode(cgcx, &module, "lto.input");
295
296        // Internalize everything below threshold to help strip out more modules and such.
297        unsafe {
298            let ptr = symbols_below_threshold.as_ptr();
299            llvm::LLVMRustRunRestrictionPass(
300                llmod,
301                ptr as *const *const libc::c_char,
302                symbols_below_threshold.len() as libc::size_t,
303            );
304        }
305        save_temp_bitcode(cgcx, &module, "lto.after-restriction");
306    }
307
308    module
309}
310
311pub(crate) struct Linker<'a>(&'a mut llvm::Linker<'a>);
312
313impl<'a> Linker<'a> {
314    pub(crate) fn new(llmod: &'a llvm::Module) -> Self {
315        unsafe { Linker(llvm::LLVMRustLinkerNew(llmod)) }
316    }
317
318    pub(crate) fn add(&mut self, bytecode: &[u8]) -> Result<(), ()> {
319        unsafe {
320            if llvm::LLVMRustLinkerAdd(
321                self.0,
322                bytecode.as_ptr() as *const libc::c_char,
323                bytecode.len(),
324            ) {
325                Ok(())
326            } else {
327                Err(())
328            }
329        }
330    }
331}
332
333impl Drop for Linker<'_> {
334    fn drop(&mut self) {
335        unsafe {
336            llvm::LLVMRustLinkerFree(&mut *(self.0 as *mut _));
337        }
338    }
339}
340
341/// Prepare "thin" LTO to get run on these modules.
342///
343/// The general structure of ThinLTO is quite different from the structure of
344/// "fat" LTO above. With "fat" LTO all LLVM modules in question are merged into
345/// one giant LLVM module, and then we run more optimization passes over this
346/// big module after internalizing most symbols. Thin LTO, on the other hand,
347/// avoid this large bottleneck through more targeted optimization.
348///
349/// At a high level Thin LTO looks like:
350///
351///    1. Prepare a "summary" of each LLVM module in question which describes
352///       the values inside, cost of the values, etc.
353///    2. Merge the summaries of all modules in question into one "index"
354///    3. Perform some global analysis on this index
355///    4. For each module, use the index and analysis calculated previously to
356///       perform local transformations on the module, for example inlining
357///       small functions from other modules.
358///    5. Run thin-specific optimization passes over each module, and then code
359///       generate everything at the end.
360///
361/// The summary for each module is intended to be quite cheap, and the global
362/// index is relatively quite cheap to create as well. As a result, the goal of
363/// ThinLTO is to reduce the bottleneck on LTO and enable LTO to be used in more
364/// situations. For example one cheap optimization is that we can parallelize
365/// all codegen modules, easily making use of all the cores on a machine.
366///
367/// With all that in mind, the function here is designed at specifically just
368/// calculating the *index* for ThinLTO. This index will then be shared amongst
369/// all of the `LtoModuleCodegen` units returned below and destroyed once
370/// they all go out of scope.
371fn thin_lto(
372    cgcx: &CodegenContext<LlvmCodegenBackend>,
373    dcx: DiagCtxtHandle<'_>,
374    modules: Vec<(String, ThinBuffer)>,
375    serialized_modules: Vec<(SerializedModule<ModuleBuffer>, CString)>,
376    cached_modules: Vec<(SerializedModule<ModuleBuffer>, WorkProduct)>,
377    symbols_below_threshold: &[*const libc::c_char],
378) -> (Vec<ThinModule<LlvmCodegenBackend>>, Vec<WorkProduct>) {
379    let _timer = cgcx.prof.generic_activity("LLVM_thin_lto_global_analysis");
380    unsafe {
381        info!("going for that thin, thin LTO");
382
383        let green_modules: FxHashMap<_, _> =
384            cached_modules.iter().map(|(_, wp)| (wp.cgu_name.clone(), wp.clone())).collect();
385
386        let full_scope_len = modules.len() + serialized_modules.len() + cached_modules.len();
387        let mut thin_buffers = Vec::with_capacity(modules.len());
388        let mut module_names = Vec::with_capacity(full_scope_len);
389        let mut thin_modules = Vec::with_capacity(full_scope_len);
390
391        for (i, (name, buffer)) in modules.into_iter().enumerate() {
392            info!("local module: {} - {}", i, name);
393            let cname = CString::new(name.as_bytes()).unwrap();
394            thin_modules.push(llvm::ThinLTOModule {
395                identifier: cname.as_ptr(),
396                data: buffer.data().as_ptr(),
397                len: buffer.data().len(),
398            });
399            thin_buffers.push(buffer);
400            module_names.push(cname);
401        }
402
403        // FIXME: All upstream crates are deserialized internally in the
404        //        function below to extract their summary and modules. Note that
405        //        unlike the loop above we *must* decode and/or read something
406        //        here as these are all just serialized files on disk. An
407        //        improvement, however, to make here would be to store the
408        //        module summary separately from the actual module itself. Right
409        //        now this is store in one large bitcode file, and the entire
410        //        file is deflate-compressed. We could try to bypass some of the
411        //        decompression by storing the index uncompressed and only
412        //        lazily decompressing the bytecode if necessary.
413        //
414        //        Note that truly taking advantage of this optimization will
415        //        likely be further down the road. We'd have to implement
416        //        incremental ThinLTO first where we could actually avoid
417        //        looking at upstream modules entirely sometimes (the contents,
418        //        we must always unconditionally look at the index).
419        let mut serialized = Vec::with_capacity(serialized_modules.len() + cached_modules.len());
420
421        let cached_modules =
422            cached_modules.into_iter().map(|(sm, wp)| (sm, CString::new(wp.cgu_name).unwrap()));
423
424        for (module, name) in serialized_modules.into_iter().chain(cached_modules) {
425            info!("upstream or cached module {:?}", name);
426            thin_modules.push(llvm::ThinLTOModule {
427                identifier: name.as_ptr(),
428                data: module.data().as_ptr(),
429                len: module.data().len(),
430            });
431            serialized.push(module);
432            module_names.push(name);
433        }
434
435        // Sanity check
436        assert_eq!(thin_modules.len(), module_names.len());
437
438        // Delegate to the C++ bindings to create some data here. Once this is a
439        // tried-and-true interface we may wish to try to upstream some of this
440        // to LLVM itself, right now we reimplement a lot of what they do
441        // upstream...
442        let data = llvm::LLVMRustCreateThinLTOData(
443            thin_modules.as_ptr(),
444            thin_modules.len(),
445            symbols_below_threshold.as_ptr(),
446            symbols_below_threshold.len(),
447        )
448        .unwrap_or_else(|| write::llvm_err(dcx, LlvmError::PrepareThinLtoContext));
449
450        let data = ThinData(data);
451
452        info!("thin LTO data created");
453
454        let (key_map_path, prev_key_map, curr_key_map) = if let Some(ref incr_comp_session_dir) =
455            cgcx.incr_comp_session_dir
456        {
457            let path = incr_comp_session_dir.join(THIN_LTO_KEYS_INCR_COMP_FILE_NAME);
458            // If the previous file was deleted, or we get an IO error
459            // reading the file, then we'll just use `None` as the
460            // prev_key_map, which will force the code to be recompiled.
461            let prev =
462                if path.exists() { ThinLTOKeysMap::load_from_file(&path).ok() } else { None };
463            let curr = ThinLTOKeysMap::from_thin_lto_modules(&data, &thin_modules, &module_names);
464            (Some(path), prev, curr)
465        } else {
466            // If we don't compile incrementally, we don't need to load the
467            // import data from LLVM.
468            assert!(green_modules.is_empty());
469            let curr = ThinLTOKeysMap::default();
470            (None, None, curr)
471        };
472        info!("thin LTO cache key map loaded");
473        info!("prev_key_map: {:#?}", prev_key_map);
474        info!("curr_key_map: {:#?}", curr_key_map);
475
476        // Throw our data in an `Arc` as we'll be sharing it across threads. We
477        // also put all memory referenced by the C++ data (buffers, ids, etc)
478        // into the arc as well. After this we'll create a thin module
479        // codegen per module in this data.
480        let shared = Arc::new(ThinShared {
481            data,
482            thin_buffers,
483            serialized_modules: serialized,
484            module_names,
485        });
486
487        let mut copy_jobs = vec![];
488        let mut opt_jobs = vec![];
489
490        info!("checking which modules can be-reused and which have to be re-optimized.");
491        for (module_index, module_name) in shared.module_names.iter().enumerate() {
492            let module_name = module_name_to_str(module_name);
493            if let (Some(prev_key_map), true) =
494                (prev_key_map.as_ref(), green_modules.contains_key(module_name))
495            {
496                assert!(cgcx.incr_comp_session_dir.is_some());
497
498                // If a module exists in both the current and the previous session,
499                // and has the same LTO cache key in both sessions, then we can re-use it
500                if prev_key_map.keys.get(module_name) == curr_key_map.keys.get(module_name) {
501                    let work_product = green_modules[module_name].clone();
502                    copy_jobs.push(work_product);
503                    info!(" - {}: re-used", module_name);
504                    assert!(cgcx.incr_comp_session_dir.is_some());
505                    continue;
506                }
507            }
508
509            info!(" - {}: re-compiled", module_name);
510            opt_jobs.push(ThinModule { shared: Arc::clone(&shared), idx: module_index });
511        }
512
513        // Save the current ThinLTO import information for the next compilation
514        // session, overwriting the previous serialized data (if any).
515        if let Some(path) = key_map_path
516            && let Err(err) = curr_key_map.save_to_file(&path)
517        {
518            write::llvm_err(dcx, LlvmError::WriteThinLtoKey { err });
519        }
520
521        (opt_jobs, copy_jobs)
522    }
523}
524
525fn enable_autodiff_settings(ad: &[config::AutoDiff]) {
526    for val in ad {
527        // We intentionally don't use a wildcard, to not forget handling anything new.
528        match val {
529            config::AutoDiff::PrintPerf => {
530                llvm::set_print_perf(true);
531            }
532            config::AutoDiff::PrintAA => {
533                llvm::set_print_activity(true);
534            }
535            config::AutoDiff::PrintTA => {
536                llvm::set_print_type(true);
537            }
538            config::AutoDiff::PrintTAFn(fun) => {
539                llvm::set_print_type(true); // Enable general type printing
540                llvm::set_print_type_fun(&fun); // Set specific function to analyze
541            }
542            config::AutoDiff::Inline => {
543                llvm::set_inline(true);
544            }
545            config::AutoDiff::LooseTypes => {
546                llvm::set_loose_types(true);
547            }
548            config::AutoDiff::PrintSteps => {
549                llvm::set_print(true);
550            }
551            // We handle this in the PassWrapper.cpp
552            config::AutoDiff::PrintPasses => {}
553            // We handle this in the PassWrapper.cpp
554            config::AutoDiff::PrintModBefore => {}
555            // We handle this in the PassWrapper.cpp
556            config::AutoDiff::PrintModAfter => {}
557            // We handle this in the PassWrapper.cpp
558            config::AutoDiff::PrintModFinal => {}
559            // This is required and already checked
560            config::AutoDiff::Enable => {}
561            // We handle this below
562            config::AutoDiff::NoPostopt => {}
563        }
564    }
565    // This helps with handling enums for now.
566    llvm::set_strict_aliasing(false);
567    // FIXME(ZuseZ4): Test this, since it was added a long time ago.
568    llvm::set_rust_rules(true);
569}
570
571pub(crate) fn run_pass_manager(
572    cgcx: &CodegenContext<LlvmCodegenBackend>,
573    dcx: DiagCtxtHandle<'_>,
574    module: &mut ModuleCodegen<ModuleLlvm>,
575    thin: bool,
576) {
577    let _timer = cgcx.prof.generic_activity_with_arg("LLVM_lto_optimize", &*module.name);
578    let config = &cgcx.module_config;
579
580    // Now we have one massive module inside of llmod. Time to run the
581    // LTO-specific optimization passes that LLVM provides.
582    //
583    // This code is based off the code found in llvm's LTO code generator:
584    //      llvm/lib/LTO/LTOCodeGenerator.cpp
585    debug!("running the pass manager");
586    let opt_stage = if thin { llvm::OptStage::ThinLTO } else { llvm::OptStage::FatLTO };
587    let opt_level = config.opt_level.unwrap_or(config::OptLevel::No);
588
589    // The PostAD behavior is the same that we would have if no autodiff was used.
590    // It will run the default optimization pipeline. If AD is enabled we select
591    // the DuringAD stage, which will disable vectorization and loop unrolling, and
592    // schedule two autodiff optimization + differentiation passes.
593    // We then run the llvm_optimize function a second time, to optimize the code which we generated
594    // in the enzyme differentiation pass.
595    let enable_ad = config.autodiff.contains(&config::AutoDiff::Enable);
596    let enable_gpu = config.offload.contains(&config::Offload::Enable);
597    let stage = if thin {
598        write::AutodiffStage::PreAD
599    } else {
600        if enable_ad { write::AutodiffStage::DuringAD } else { write::AutodiffStage::PostAD }
601    };
602
603    if enable_ad {
604        enable_autodiff_settings(&config.autodiff);
605    }
606
607    unsafe {
608        write::llvm_optimize(cgcx, dcx, module, None, config, opt_level, opt_stage, stage);
609    }
610
611    if enable_gpu && !thin {
612        let cx =
613            SimpleCx::new(module.module_llvm.llmod(), &module.module_llvm.llcx, cgcx.pointer_size);
614        crate::builder::gpu_offload::handle_gpu_code(cgcx, &cx);
615    }
616
617    if cfg!(llvm_enzyme) && enable_ad && !thin {
618        let opt_stage = llvm::OptStage::FatLTO;
619        let stage = write::AutodiffStage::PostAD;
620        if !config.autodiff.contains(&config::AutoDiff::NoPostopt) {
621            unsafe {
622                write::llvm_optimize(cgcx, dcx, module, None, config, opt_level, opt_stage, stage);
623            }
624        }
625
626        // This is the final IR, so people should be able to inspect the optimized autodiff output,
627        // for manual inspection.
628        if config.autodiff.contains(&config::AutoDiff::PrintModFinal) {
629            unsafe { llvm::LLVMDumpModule(module.module_llvm.llmod()) };
630        }
631    }
632
633    debug!("lto done");
634}
635
636pub struct ModuleBuffer(&'static mut llvm::ModuleBuffer);
637
638unsafe impl Send for ModuleBuffer {}
639unsafe impl Sync for ModuleBuffer {}
640
641impl ModuleBuffer {
642    pub(crate) fn new(m: &llvm::Module) -> ModuleBuffer {
643        ModuleBuffer(unsafe { llvm::LLVMRustModuleBufferCreate(m) })
644    }
645}
646
647impl ModuleBufferMethods for ModuleBuffer {
648    fn data(&self) -> &[u8] {
649        unsafe {
650            let ptr = llvm::LLVMRustModuleBufferPtr(self.0);
651            let len = llvm::LLVMRustModuleBufferLen(self.0);
652            slice::from_raw_parts(ptr, len)
653        }
654    }
655}
656
657impl Drop for ModuleBuffer {
658    fn drop(&mut self) {
659        unsafe {
660            llvm::LLVMRustModuleBufferFree(&mut *(self.0 as *mut _));
661        }
662    }
663}
664
665pub struct ThinData(&'static mut llvm::ThinLTOData);
666
667unsafe impl Send for ThinData {}
668unsafe impl Sync for ThinData {}
669
670impl Drop for ThinData {
671    fn drop(&mut self) {
672        unsafe {
673            llvm::LLVMRustFreeThinLTOData(&mut *(self.0 as *mut _));
674        }
675    }
676}
677
678pub struct ThinBuffer(&'static mut llvm::ThinLTOBuffer);
679
680unsafe impl Send for ThinBuffer {}
681unsafe impl Sync for ThinBuffer {}
682
683impl ThinBuffer {
684    pub(crate) fn new(m: &llvm::Module, is_thin: bool, emit_summary: bool) -> ThinBuffer {
685        unsafe {
686            let buffer = llvm::LLVMRustThinLTOBufferCreate(m, is_thin, emit_summary);
687            ThinBuffer(buffer)
688        }
689    }
690
691    pub(crate) unsafe fn from_raw_ptr(ptr: *mut llvm::ThinLTOBuffer) -> ThinBuffer {
692        let mut ptr = NonNull::new(ptr).unwrap();
693        ThinBuffer(unsafe { ptr.as_mut() })
694    }
695}
696
697impl ThinBufferMethods for ThinBuffer {
698    fn data(&self) -> &[u8] {
699        unsafe {
700            let ptr = llvm::LLVMRustThinLTOBufferPtr(self.0) as *const _;
701            let len = llvm::LLVMRustThinLTOBufferLen(self.0);
702            slice::from_raw_parts(ptr, len)
703        }
704    }
705
706    fn thin_link_data(&self) -> &[u8] {
707        unsafe {
708            let ptr = llvm::LLVMRustThinLTOBufferThinLinkDataPtr(self.0) as *const _;
709            let len = llvm::LLVMRustThinLTOBufferThinLinkDataLen(self.0);
710            slice::from_raw_parts(ptr, len)
711        }
712    }
713}
714
715impl Drop for ThinBuffer {
716    fn drop(&mut self) {
717        unsafe {
718            llvm::LLVMRustThinLTOBufferFree(&mut *(self.0 as *mut _));
719        }
720    }
721}
722
723pub(crate) fn optimize_thin_module(
724    thin_module: ThinModule<LlvmCodegenBackend>,
725    cgcx: &CodegenContext<LlvmCodegenBackend>,
726) -> ModuleCodegen<ModuleLlvm> {
727    let dcx = cgcx.create_dcx();
728    let dcx = dcx.handle();
729
730    let module_name = &thin_module.shared.module_names[thin_module.idx];
731
732    // Right now the implementation we've got only works over serialized
733    // modules, so we create a fresh new LLVM context and parse the module
734    // into that context. One day, however, we may do this for upstream
735    // crates but for locally codegened modules we may be able to reuse
736    // that LLVM Context and Module.
737    let module_llvm = ModuleLlvm::parse(cgcx, module_name, thin_module.data(), dcx);
738    let mut module = ModuleCodegen::new_regular(thin_module.name(), module_llvm);
739    // Given that the newly created module lacks a thinlto buffer for embedding, we need to re-add it here.
740    if cgcx.module_config.embed_bitcode() {
741        module.thin_lto_buffer = Some(thin_module.data().to_vec());
742    }
743    {
744        let target = &*module.module_llvm.tm;
745        let llmod = module.module_llvm.llmod();
746        save_temp_bitcode(cgcx, &module, "thin-lto-input");
747
748        // Up next comes the per-module local analyses that we do for Thin LTO.
749        // Each of these functions is basically copied from the LLVM
750        // implementation and then tailored to suit this implementation. Ideally
751        // each of these would be supported by upstream LLVM but that's perhaps
752        // a patch for another day!
753        //
754        // You can find some more comments about these functions in the LLVM
755        // bindings we've got (currently `PassWrapper.cpp`)
756        {
757            let _timer =
758                cgcx.prof.generic_activity_with_arg("LLVM_thin_lto_rename", thin_module.name());
759            unsafe {
760                llvm::LLVMRustPrepareThinLTORename(thin_module.shared.data.0, llmod, target.raw())
761            };
762            save_temp_bitcode(cgcx, &module, "thin-lto-after-rename");
763        }
764
765        {
766            let _timer = cgcx
767                .prof
768                .generic_activity_with_arg("LLVM_thin_lto_resolve_weak", thin_module.name());
769            if unsafe { !llvm::LLVMRustPrepareThinLTOResolveWeak(thin_module.shared.data.0, llmod) }
770            {
771                write::llvm_err(dcx, LlvmError::PrepareThinLtoModule);
772            }
773            save_temp_bitcode(cgcx, &module, "thin-lto-after-resolve");
774        }
775
776        {
777            let _timer = cgcx
778                .prof
779                .generic_activity_with_arg("LLVM_thin_lto_internalize", thin_module.name());
780            if unsafe { !llvm::LLVMRustPrepareThinLTOInternalize(thin_module.shared.data.0, llmod) }
781            {
782                write::llvm_err(dcx, LlvmError::PrepareThinLtoModule);
783            }
784            save_temp_bitcode(cgcx, &module, "thin-lto-after-internalize");
785        }
786
787        {
788            let _timer =
789                cgcx.prof.generic_activity_with_arg("LLVM_thin_lto_import", thin_module.name());
790            if unsafe {
791                !llvm::LLVMRustPrepareThinLTOImport(thin_module.shared.data.0, llmod, target.raw())
792            } {
793                write::llvm_err(dcx, LlvmError::PrepareThinLtoModule);
794            }
795            save_temp_bitcode(cgcx, &module, "thin-lto-after-import");
796        }
797
798        // Alright now that we've done everything related to the ThinLTO
799        // analysis it's time to run some optimizations! Here we use the same
800        // `run_pass_manager` as the "fat" LTO above except that we tell it to
801        // populate a thin-specific pass manager, which presumably LLVM treats a
802        // little differently.
803        {
804            info!("running thin lto passes over {}", module.name);
805            run_pass_manager(cgcx, dcx, &mut module, true);
806            save_temp_bitcode(cgcx, &module, "thin-lto-after-pm");
807        }
808    }
809    module
810}
811
812/// Maps LLVM module identifiers to their corresponding LLVM LTO cache keys
813#[derive(Debug, Default)]
814struct ThinLTOKeysMap {
815    // key = llvm name of importing module, value = LLVM cache key
816    keys: BTreeMap<String, String>,
817}
818
819impl ThinLTOKeysMap {
820    fn save_to_file(&self, path: &Path) -> io::Result<()> {
821        use std::io::Write;
822        let mut writer = File::create_buffered(path)?;
823        // The entries are loaded back into a hash map in `load_from_file()`, so
824        // the order in which we write them to file here does not matter.
825        for (module, key) in &self.keys {
826            writeln!(writer, "{module} {key}")?;
827        }
828        Ok(())
829    }
830
831    fn load_from_file(path: &Path) -> io::Result<Self> {
832        use std::io::BufRead;
833        let mut keys = BTreeMap::default();
834        let file = File::open_buffered(path)?;
835        for line in file.lines() {
836            let line = line?;
837            let mut split = line.split(' ');
838            let module = split.next().unwrap();
839            let key = split.next().unwrap();
840            assert_eq!(split.next(), None, "Expected two space-separated values, found {line:?}");
841            keys.insert(module.to_string(), key.to_string());
842        }
843        Ok(Self { keys })
844    }
845
846    fn from_thin_lto_modules(
847        data: &ThinData,
848        modules: &[llvm::ThinLTOModule],
849        names: &[CString],
850    ) -> Self {
851        let keys = iter::zip(modules, names)
852            .map(|(module, name)| {
853                let key = build_string(|rust_str| unsafe {
854                    llvm::LLVMRustComputeLTOCacheKey(rust_str, module.identifier, data.0);
855                })
856                .expect("Invalid ThinLTO module key");
857                (module_name_to_str(name).to_string(), key)
858            })
859            .collect();
860        Self { keys }
861    }
862}
863
864fn module_name_to_str(c_str: &CStr) -> &str {
865    c_str.to_str().unwrap_or_else(|e| {
866        bug!("Encountered non-utf8 LLVM module name `{}`: {}", c_str.to_string_lossy(), e)
867    })
868}
869
870pub(crate) fn parse_module<'a>(
871    cx: &'a llvm::Context,
872    name: &CStr,
873    data: &[u8],
874    dcx: DiagCtxtHandle<'_>,
875) -> &'a llvm::Module {
876    unsafe {
877        llvm::LLVMRustParseBitcodeForLTO(cx, data.as_ptr(), data.len(), name.as_ptr())
878            .unwrap_or_else(|| write::llvm_err(dcx, LlvmError::ParseBitcode))
879    }
880}