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, 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
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.regular_module_config.instrument_coverage
47        || cgcx.regular_module_config.pgo_gen.enabled()
48    {
49        // These are weak symbols that point to the profile version and the
50        // profile name, which need to be treated as exported so LTO doesn't nix
51        // them.
52        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        // Similar to profiling, preserve weak msan symbol during LTO.
62        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    // Preserve LLVM-injected, ASAN-related symbols.
74    // See also https://github.com/rust-lang/rust/issues/113404.
75    symbols_below_threshold.push(c"___asan_globals_registered".to_owned());
76
77    // __llvm_profile_counter_bias is pulled in at link time by an undefined reference to
78    // __llvm_profile_runtime, therefore we won't know until link time if this symbol
79    // should have default visibility.
80    symbols_below_threshold.push(c"__llvm_profile_counter_bias".to_owned());
81
82    // If we're performing LTO for the entire crate graph, then for each of our
83    // upstream dependencies, find the corresponding rlib and load the bitcode
84    // from the archive.
85    //
86    // We save off all the bytecode and LLVM module ids for later processing
87    // with either fat or thin LTO
88    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    // We're about to assume the data here is an object file with sections, but if it's raw LLVM IR
128    // that won't work. Fortunately, if that's what we have we can just return the object directly,
129    // so we sniff the relevant magic strings here and return.
130    if obj.starts_with(b"\xDE\xC0\x17\x0B") || obj.starts_with(b"BC\xC0\xDE") {
131        return Ok(obj);
132    }
133    // We drop the "__LLVM," prefix here because on Apple platforms there's a notion of "segment
134    // name" which in the public API for sections gets treated as part of the section name, but
135    // internally in MachOObjectFile.cpp gets treated separately.
136    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
148/// Performs fat LTO by merging all modules into a single one and returning it
149/// for further optimization.
150pub(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
165/// Performs thin LTO by performing necessary global analysis and returning two
166/// lists, one of the modules that need optimization and another for modules that
167/// can simply be copied over from the incr. comp. cache.
168pub(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    // Sort out all our lists of incoming modules into two lists.
210    //
211    // * `serialized_modules` (also and argument to this function) contains all
212    //   modules that are serialized in-memory.
213    // * `in_memory` contains modules which are already parsed and in-memory,
214    //   such as from multi-CGU builds.
215    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    // Find the "costliest" module and merge everything into that codegen unit.
227    // All the other modules will be serialized and reparsed into the new
228    // context, so this hopefully avoids serializing and parsing the largest
229    // codegen unit.
230    //
231    // Additionally use a regular module as the base here to ensure that various
232    // file copy operations in the backend work correctly. The only other kind
233    // of module here should be an allocator one, and if your crate is smaller
234    // than the allocator module then the size doesn't really matter anyway.
235    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    // If we found a costliest module, we're good to go. Otherwise all our
246    // inputs were serialized which could happen in the case, for example, that
247    // all our inputs were incrementally reread from the cache and we're just
248    // re-executing the LTO passes. If that's the case deserialize the first
249    // module and create a linker with it.
250    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        // The linking steps below may produce errors and diagnostics within LLVM
268        // which we'd like to handle and print, so set up our diagnostic handlers
269        // (which get unregistered when they go out of scope below).
270        let _handler =
271            DiagnosticHandlers::new(cgcx, dcx, llcx, &module, CodegenDiagnosticsStage::LTO);
272
273        // For all other modules we codegened we'll need to link them into our own
274        // bitcode. All modules were codegened in their own LLVM context, however,
275        // and we want to move everything to the same LLVM context. Currently the
276        // way we know of to do that is to serialize them to a string and them parse
277        // them later. Not great but hey, that's why it's "fat" LTO, right?
278        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        // Sort the modules to ensure we produce deterministic results.
284        serialized_modules.sort_by(|module1, module2| module1.1.cmp(&module2.1));
285
286        // For all serialized bitcode files we parse them and link them in as we did
287        // above, this is all mostly handled in C++.
288        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        // Internalize everything below threshold to help strip out more modules and such.
305        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
349/// Prepare "thin" LTO to get run on these modules.
350///
351/// The general structure of ThinLTO is quite different from the structure of
352/// "fat" LTO above. With "fat" LTO all LLVM modules in question are merged into
353/// one giant LLVM module, and then we run more optimization passes over this
354/// big module after internalizing most symbols. Thin LTO, on the other hand,
355/// avoid this large bottleneck through more targeted optimization.
356///
357/// At a high level Thin LTO looks like:
358///
359///    1. Prepare a "summary" of each LLVM module in question which describes
360///       the values inside, cost of the values, etc.
361///    2. Merge the summaries of all modules in question into one "index"
362///    3. Perform some global analysis on this index
363///    4. For each module, use the index and analysis calculated previously to
364///       perform local transformations on the module, for example inlining
365///       small functions from other modules.
366///    5. Run thin-specific optimization passes over each module, and then code
367///       generate everything at the end.
368///
369/// The summary for each module is intended to be quite cheap, and the global
370/// index is relatively quite cheap to create as well. As a result, the goal of
371/// ThinLTO is to reduce the bottleneck on LTO and enable LTO to be used in more
372/// situations. For example one cheap optimization is that we can parallelize
373/// all codegen modules, easily making use of all the cores on a machine.
374///
375/// With all that in mind, the function here is designed at specifically just
376/// calculating the *index* for ThinLTO. This index will then be shared amongst
377/// all of the `LtoModuleCodegen` units returned below and destroyed once
378/// they all go out of scope.
379fn 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        // FIXME: All upstream crates are deserialized internally in the
412        //        function below to extract their summary and modules. Note that
413        //        unlike the loop above we *must* decode and/or read something
414        //        here as these are all just serialized files on disk. An
415        //        improvement, however, to make here would be to store the
416        //        module summary separately from the actual module itself. Right
417        //        now this is store in one large bitcode file, and the entire
418        //        file is deflate-compressed. We could try to bypass some of the
419        //        decompression by storing the index uncompressed and only
420        //        lazily decompressing the bytecode if necessary.
421        //
422        //        Note that truly taking advantage of this optimization will
423        //        likely be further down the road. We'd have to implement
424        //        incremental ThinLTO first where we could actually avoid
425        //        looking at upstream modules entirely sometimes (the contents,
426        //        we must always unconditionally look at the index).
427        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        // Sanity check
444        assert_eq!(thin_modules.len(), module_names.len());
445
446        // Delegate to the C++ bindings to create some data here. Once this is a
447        // tried-and-true interface we may wish to try to upstream some of this
448        // to LLVM itself, right now we reimplement a lot of what they do
449        // upstream...
450        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            // If the previous file was deleted, or we get an IO error
467            // reading the file, then we'll just use `None` as the
468            // prev_key_map, which will force the code to be recompiled.
469            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            // If we don't compile incrementally, we don't need to load the
475            // import data from LLVM.
476            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        // Throw our data in an `Arc` as we'll be sharing it across threads. We
485        // also put all memory referenced by the C++ data (buffers, ids, etc)
486        // into the arc as well. After this we'll create a thin module
487        // codegen per module in this data.
488        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 a module exists in both the current and the previous session,
507                // and has the same LTO cache key in both sessions, then we can re-use it
508                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        // Save the current ThinLTO import information for the next compilation
522        // session, overwriting the previous serialized data (if any).
523        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        // We intentionally don't use a wildcard, to not forget handling anything new.
536        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); // Enable general type printing
548                llvm::set_print_type_fun(&fun); // Set specific function to analyze
549            }
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            // We handle this in the PassWrapper.cpp
560            config::AutoDiff::PrintPasses => {}
561            // We handle this in the PassWrapper.cpp
562            config::AutoDiff::PrintModBefore => {}
563            // We handle this in the PassWrapper.cpp
564            config::AutoDiff::PrintModAfter => {}
565            // We handle this in the PassWrapper.cpp
566            config::AutoDiff::PrintModFinal => {}
567            // This is required and already checked
568            config::AutoDiff::Enable => {}
569            // We handle this below
570            config::AutoDiff::NoPostopt => {}
571        }
572    }
573    // This helps with handling enums for now.
574    llvm::set_strict_aliasing(false);
575    // FIXME(ZuseZ4): Test this, since it was added a long time ago.
576    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    // Now we have one massive module inside of llmod. Time to run the
589    // LTO-specific optimization passes that LLVM provides.
590    //
591    // This code is based off the code found in llvm's LTO code generator:
592    //      llvm/lib/LTO/LTOCodeGenerator.cpp
593    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    // The PostAD behavior is the same that we would have if no autodiff was used.
598    // It will run the default optimization pipeline. If AD is enabled we select
599    // the DuringAD stage, which will disable vectorization and loop unrolling, and
600    // schedule two autodiff optimization + differentiation passes.
601    // We then run the llvm_optimize function a second time, to optimize the code which we generated
602    // in the enzyme differentiation pass.
603    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        // This is the final IR, so people should be able to inspect the optimized autodiff output,
635        // for manual inspection.
636        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    // Right now the implementation we've got only works over serialized
741    // modules, so we create a fresh new LLVM context and parse the module
742    // into that context. One day, however, we may do this for upstream
743    // crates but for locally codegened modules we may be able to reuse
744    // that LLVM Context and Module.
745    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    // Given that the newly created module lacks a thinlto buffer for embedding, we need to re-add it here.
748    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        // Up next comes the per-module local analyses that we do for Thin LTO.
757        // Each of these functions is basically copied from the LLVM
758        // implementation and then tailored to suit this implementation. Ideally
759        // each of these would be supported by upstream LLVM but that's perhaps
760        // a patch for another day!
761        //
762        // You can find some more comments about these functions in the LLVM
763        // bindings we've got (currently `PassWrapper.cpp`)
764        {
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        // Alright now that we've done everything related to the ThinLTO
807        // analysis it's time to run some optimizations! Here we use the same
808        // `run_pass_manager` as the "fat" LTO above except that we tell it to
809        // populate a thin-specific pass manager, which presumably LLVM treats a
810        // little differently.
811        {
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/// Maps LLVM module identifiers to their corresponding LLVM LTO cache keys
821#[derive(Debug, Default)]
822struct ThinLTOKeysMap {
823    // key = llvm name of importing module, value = LLVM cache key
824    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        // The entries are loaded back into a hash map in `load_from_file()`, so
832        // the order in which we write them to file here does not matter.
833        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}