Skip to main content

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