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};
78use object::read::archive::ArchiveFile;
9use object::{Object, ObjectSection};
10use rustc_codegen_ssa::back::lto::{SerializedModule, ThinModule, ThinShared};
11use rustc_codegen_ssa::back::write::{
12 CodegenContext, FatLtoInput, SharedEmitter, TargetMachineFactoryFn, ThinLtoInput,
13};
14use rustc_codegen_ssa::traits::*;
15use rustc_codegen_ssa::{CompiledModule, ModuleCodegen, ModuleKind, looks_like_rust_object_file};
16use rustc_data_structures::fx::FxHashMap;
17use rustc_data_structures::memmap::Mmap;
18use rustc_data_structures::profiling::SelfProfilerRef;
19use rustc_errors::{DiagCtxt, DiagCtxtHandle};
20use rustc_hir::attrs::SanitizerSet;
21use rustc_middle::bug;
22use rustc_middle::dep_graph::WorkProduct;
23use rustc_session::config;
24use tracing::{debug, info};
2526use crate::back::write::{
27self, CodegenDiagnosticsStage, DiagnosticHandlers, bitcode_section_name, codegen,
28save_temp_bitcode,
29};
30use crate::errors::{LlvmError, LtoBitcodeFromRlib};
31use crate::llvm::{self, build_string};
32use crate::{LlvmCodegenBackend, ModuleLlvm};
3334/// We keep track of the computed LTO cache keys from the previous
35/// session to determine which CGUs we can reuse.
36const THIN_LTO_KEYS_INCR_COMP_FILE_NAME: &str = "thin-lto-past-keys.bin";
3738fn prepare_lto(
39 cgcx: &CodegenContext,
40 exported_symbols_for_lto: &[String],
41 each_linked_rlib_for_lto: &[PathBuf],
42 dcx: DiagCtxtHandle<'_>,
43) -> (Vec<CString>, Vec<(SerializedModule<ModuleBuffer>, CString)>) {
44let mut symbols_below_threshold = exported_symbols_for_lto45 .iter()
46 .map(|symbol| CString::new(symbol.to_owned()).unwrap())
47 .collect::<Vec<CString>>();
4849if cgcx.module_config.instrument_coverage || cgcx.module_config.pgo_gen.enabled() {
50// These are weak symbols that point to the profile version and the
51 // profile name, which need to be treated as exported so LTO doesn't nix
52 // them.
53const PROFILER_WEAK_SYMBOLS: [&CStr; 2] =
54 [c"__llvm_profile_raw_version", c"__llvm_profile_filename"];
5556symbols_below_threshold.extend(PROFILER_WEAK_SYMBOLS.iter().map(|&sym| sym.to_owned()));
57 }
5859if cgcx.module_config.sanitizer.contains(SanitizerSet::MEMORY) {
60let mut msan_weak_symbols = Vec::new();
6162// Similar to profiling, preserve weak msan symbol during LTO.
63if cgcx.module_config.sanitizer_recover.contains(SanitizerSet::MEMORY) {
64msan_weak_symbols.push(c"__msan_keep_going");
65 }
6667if cgcx.module_config.sanitizer_memory_track_origins != 0 {
68msan_weak_symbols.push(c"__msan_track_origins");
69 }
7071symbols_below_threshold.extend(msan_weak_symbols.into_iter().map(|sym| sym.to_owned()));
72 }
7374// Preserve LLVM-injected, ASAN-related symbols.
75 // See also https://github.com/rust-lang/rust/issues/113404.
76symbols_below_threshold.push(c"___asan_globals_registered".to_owned());
7778// __llvm_profile_counter_bias is pulled in at link time by an undefined reference to
79 // __llvm_profile_runtime, therefore we won't know until link time if this symbol
80 // should have default visibility.
81symbols_below_threshold.push(c"__llvm_profile_counter_bias".to_owned());
8283// LTO seems to discard this otherwise under certain circumstances.
84symbols_below_threshold.push(c"rust_eh_personality".to_owned());
8586// If we're performing LTO for the entire crate graph, then for each of our
87 // upstream dependencies, find the corresponding rlib and load the bitcode
88 // from the archive.
89 //
90 // We save off all the bytecode and LLVM module ids for later processing
91 // with either fat or thin LTO
92let mut upstream_modules = Vec::new();
93for path in each_linked_rlib_for_lto {
94let archive_data = unsafe {
95 Mmap::map(std::fs::File::open(&path).expect("couldn't open rlib"))
96 .expect("couldn't map rlib")
97 };
98let archive = ArchiveFile::parse(&*archive_data).expect("wanted an rlib");
99let obj_files = archive
100 .members()
101 .filter_map(|child| {
102 child
103 .ok()
104 .and_then(|c| std::str::from_utf8(c.name()).ok().map(|name| (name.trim(), c)))
105 })
106 .filter(|&(name, _)| looks_like_rust_object_file(name));
107for (name, child) in obj_files {
108{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_llvm/src/back/lto.rs:108",
"rustc_codegen_llvm::back::lto", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/back/lto.rs"),
::tracing_core::__macro_support::Option::Some(108u32),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("adding bitcode from {0}",
name) as &dyn Value))])
});
} else { ; }
};info!("adding bitcode from {}", name);
109match get_bitcode_slice_from_object_data(
110 child.data(&*archive_data).expect("corrupt rlib"),
111 cgcx,
112 ) {
113Ok(data) => {
114let module = SerializedModule::FromRlib(data.to_vec());
115 upstream_modules.push((module, CString::new(name).unwrap()));
116 }
117Err(e) => dcx.emit_fatal(e),
118 }
119 }
120 }
121122 (symbols_below_threshold, upstream_modules)
123}
124125fn get_bitcode_slice_from_object_data<'a>(
126 obj: &'a [u8],
127 cgcx: &CodegenContext,
128) -> Result<&'a [u8], LtoBitcodeFromRlib> {
129// We're about to assume the data here is an object file with sections, but if it's raw LLVM IR
130 // that won't work. Fortunately, if that's what we have we can just return the object directly,
131 // so we sniff the relevant magic strings here and return.
132if obj.starts_with(b"\xDE\xC0\x17\x0B") || obj.starts_with(b"BC\xC0\xDE") {
133return Ok(obj);
134 }
135// We drop the "__LLVM," prefix here because on Apple platforms there's a notion of "segment
136 // name" which in the public API for sections gets treated as part of the section name, but
137 // internally in MachOObjectFile.cpp gets treated separately.
138let section_name = bitcode_section_name(cgcx).to_str().unwrap().trim_start_matches("__LLVM,");
139140let obj =
141 object::File::parse(obj).map_err(|err| LtoBitcodeFromRlib { err: err.to_string() })?;
142143let section = obj144 .section_by_name(section_name)
145 .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}") })?;
146147section.data().map_err(|err| LtoBitcodeFromRlib { err: err.to_string() })
148}
149150/// Performs fat LTO by merging all modules into a single one and returning it
151/// for further optimization.
152pub(crate) fn run_fat(
153 cgcx: &CodegenContext,
154 prof: &SelfProfilerRef,
155 shared_emitter: &SharedEmitter,
156 tm_factory: TargetMachineFactoryFn<LlvmCodegenBackend>,
157 exported_symbols_for_lto: &[String],
158 each_linked_rlib_for_lto: &[PathBuf],
159 modules: Vec<FatLtoInput<LlvmCodegenBackend>>,
160) -> ModuleCodegen<ModuleLlvm> {
161let dcx = DiagCtxt::new(Box::new(shared_emitter.clone()));
162let dcx = dcx.handle();
163let (symbols_below_threshold, upstream_modules) =
164prepare_lto(cgcx, exported_symbols_for_lto, each_linked_rlib_for_lto, dcx);
165let symbols_below_threshold =
166symbols_below_threshold.iter().map(|c| c.as_ptr()).collect::<Vec<_>>();
167fat_lto(
168cgcx,
169prof,
170dcx,
171shared_emitter,
172tm_factory,
173modules,
174upstream_modules,
175&symbols_below_threshold,
176 )
177}
178179/// Performs thin LTO by performing necessary global analysis and returning two
180/// lists, one of the modules that need optimization and another for modules that
181/// can simply be copied over from the incr. comp. cache.
182pub(crate) fn run_thin(
183 cgcx: &CodegenContext,
184 prof: &SelfProfilerRef,
185 dcx: DiagCtxtHandle<'_>,
186 exported_symbols_for_lto: &[String],
187 each_linked_rlib_for_lto: &[PathBuf],
188 modules: Vec<ThinLtoInput<LlvmCodegenBackend>>,
189) -> (Vec<ThinModule<LlvmCodegenBackend>>, Vec<WorkProduct>) {
190let (symbols_below_threshold, upstream_modules) =
191prepare_lto(cgcx, exported_symbols_for_lto, each_linked_rlib_for_lto, dcx);
192let symbols_below_threshold =
193symbols_below_threshold.iter().map(|c| c.as_ptr()).collect::<Vec<_>>();
194if cgcx.use_linker_plugin_lto {
195{
::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!(
196"We should never reach this case if the LTO step \
197 is deferred to the linker"
198);
199 }
200thin_lto(cgcx, prof, dcx, modules, upstream_modules, &symbols_below_threshold)
201}
202203fn fat_lto(
204 cgcx: &CodegenContext,
205 prof: &SelfProfilerRef,
206 dcx: DiagCtxtHandle<'_>,
207 shared_emitter: &SharedEmitter,
208 tm_factory: TargetMachineFactoryFn<LlvmCodegenBackend>,
209 modules: Vec<FatLtoInput<LlvmCodegenBackend>>,
210mut serialized_modules: Vec<(SerializedModule<ModuleBuffer>, CString)>,
211 symbols_below_threshold: &[*const libc::c_char],
212) -> ModuleCodegen<ModuleLlvm> {
213let _timer = prof.generic_activity("LLVM_fat_lto_build_monolithic_module");
214{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_llvm/src/back/lto.rs:214",
"rustc_codegen_llvm::back::lto", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/back/lto.rs"),
::tracing_core::__macro_support::Option::Some(214u32),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("going for a fat lto")
as &dyn Value))])
});
} else { ; }
};info!("going for a fat lto");
215216// Sort out all our lists of incoming modules into two lists.
217 //
218 // * `serialized_modules` (also and argument to this function) contains all
219 // modules that are serialized in-memory.
220 // * `in_memory` contains modules which are already parsed and in-memory,
221 // such as from multi-CGU builds.
222let mut in_memory = Vec::new();
223for module in modules {
224match module {
225 FatLtoInput::InMemory(m) => in_memory.push(m),
226 FatLtoInput::Serialized { name, buffer } => {
227{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_llvm/src/back/lto.rs:227",
"rustc_codegen_llvm::back::lto", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/back/lto.rs"),
::tracing_core::__macro_support::Option::Some(227u32),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("pushing serialized module {0:?}",
name) as &dyn Value))])
});
} else { ; }
};info!("pushing serialized module {:?}", name);
228 serialized_modules.push((buffer, CString::new(name).unwrap()));
229 }
230 }
231 }
232233// Find the "costliest" module and merge everything into that codegen unit.
234 // All the other modules will be serialized and reparsed into the new
235 // context, so this hopefully avoids serializing and parsing the largest
236 // codegen unit.
237 //
238 // Additionally use a regular module as the base here to ensure that various
239 // file copy operations in the backend work correctly. The only other kind
240 // of module here should be an allocator one, and if your crate is smaller
241 // than the allocator module then the size doesn't really matter anyway.
242let costliest_module = in_memory243 .iter()
244 .enumerate()
245 .filter(|&(_, module)| module.kind == ModuleKind::Regular)
246 .map(|(i, module)| {
247let cost = unsafe { llvm::LLVMRustModuleCost(module.module_llvm.llmod()) };
248 (cost, i)
249 })
250 .max();
251252// If we found a costliest module, we're good to go. Otherwise all our
253 // inputs were serialized which could happen in the case, for example, that
254 // all our inputs were incrementally reread from the cache and we're just
255 // re-executing the LTO passes. If that's the case deserialize the first
256 // module and create a linker with it.
257let module: ModuleCodegen<ModuleLlvm> = match costliest_module {
258Some((_cost, i)) => in_memory.remove(i),
259None => {
260if !!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");
261let (buffer, name) = serialized_modules.remove(0);
262{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_llvm/src/back/lto.rs:262",
"rustc_codegen_llvm::back::lto", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/back/lto.rs"),
::tracing_core::__macro_support::Option::Some(262u32),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("no in-memory regular modules to choose from, parsing {0:?}",
name) as &dyn Value))])
});
} else { ; }
};info!("no in-memory regular modules to choose from, parsing {:?}", name);
263let llvm_module = ModuleLlvm::parse(cgcx, tm_factory, &name, buffer.data(), dcx);
264 ModuleCodegen::new_regular(name.into_string().unwrap(), llvm_module)
265 }
266 };
267 {
268let (llcx, llmod) = {
269let llvm = &module.module_llvm;
270 (&llvm.llcx, llvm.llmod())
271 };
272{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_llvm/src/back/lto.rs:272",
"rustc_codegen_llvm::back::lto", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("using {0:?} as a base module",
module.name) as &dyn Value))])
});
} else { ; }
};info!("using {:?} as a base module", module.name);
273274// The linking steps below may produce errors and diagnostics within LLVM
275 // which we'd like to handle and print, so set up our diagnostic handlers
276 // (which get unregistered when they go out of scope below).
277let _handler = DiagnosticHandlers::new(
278cgcx,
279shared_emitter,
280llcx,
281&module,
282 CodegenDiagnosticsStage::LTO,
283 );
284285// For all other modules we codegened we'll need to link them into our own
286 // bitcode. All modules were codegened in their own LLVM context, however,
287 // and we want to move everything to the same LLVM context. Currently the
288 // way we know of to do that is to serialize them to a string and them parse
289 // them later. Not great but hey, that's why it's "fat" LTO, right?
290for module in in_memory {
291let buffer = ModuleBuffer::new(module.module_llvm.llmod(), false);
292let llmod_id = CString::new(&module.name[..]).unwrap();
293 serialized_modules.push((SerializedModule::Local(buffer), llmod_id));
294 }
295// Sort the modules to ensure we produce deterministic results.
296serialized_modules.sort_by(|module1, module2| module1.1.cmp(&module2.1));
297298// For all serialized bitcode files we parse them and link them in as we did
299 // above, this is all mostly handled in C++.
300let linker = unsafe { llvm::LLVMRustLinkerNew(llmod) };
301for (bc_decoded, name) in serialized_modules {
302let _timer = prof
303 .generic_activity_with_arg_recorder("LLVM_fat_lto_link_module", |recorder| {
304 recorder.record_arg(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}", name))
})format!("{name:?}"))
305 });
306{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_llvm/src/back/lto.rs:306",
"rustc_codegen_llvm::back::lto", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/back/lto.rs"),
::tracing_core::__macro_support::Option::Some(306u32),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("linking {0:?}",
name) as &dyn Value))])
});
} else { ; }
};info!("linking {:?}", name);
307let data = bc_decoded.data();
308309unsafe {
310if !llvm::LLVMRustLinkerAdd(
311 linker,
312 data.as_ptr() as *const libc::c_char,
313 data.len(),
314 ) {
315 llvm::LLVMRustLinkerFree(linker);
316 write::llvm_err(dcx, LlvmError::LoadBitcode { name })
317 }
318 }
319 }
320unsafe { llvm::LLVMRustLinkerFree(linker) };
321save_temp_bitcode(cgcx, &module, "lto.input");
322323// Internalize everything below threshold to help strip out more modules and such.
324unsafe {
325let ptr = symbols_below_threshold.as_ptr();
326 llvm::LLVMRustRunRestrictionPass(
327llmod,
328ptras *const *const libc::c_char,
329symbols_below_threshold.len() as libc::size_t,
330 );
331 }
332save_temp_bitcode(cgcx, &module, "lto.after-restriction");
333 }
334335module336}
337338/// Prepare "thin" LTO to get run on these modules.
339///
340/// The general structure of ThinLTO is quite different from the structure of
341/// "fat" LTO above. With "fat" LTO all LLVM modules in question are merged into
342/// one giant LLVM module, and then we run more optimization passes over this
343/// big module after internalizing most symbols. Thin LTO, on the other hand,
344/// avoid this large bottleneck through more targeted optimization.
345///
346/// At a high level Thin LTO looks like:
347///
348/// 1. Prepare a "summary" of each LLVM module in question which describes
349/// the values inside, cost of the values, etc.
350/// 2. Merge the summaries of all modules in question into one "index"
351/// 3. Perform some global analysis on this index
352/// 4. For each module, use the index and analysis calculated previously to
353/// perform local transformations on the module, for example inlining
354/// small functions from other modules.
355/// 5. Run thin-specific optimization passes over each module, and then code
356/// generate everything at the end.
357///
358/// The summary for each module is intended to be quite cheap, and the global
359/// index is relatively quite cheap to create as well. As a result, the goal of
360/// ThinLTO is to reduce the bottleneck on LTO and enable LTO to be used in more
361/// situations. For example one cheap optimization is that we can parallelize
362/// all codegen modules, easily making use of all the cores on a machine.
363///
364/// With all that in mind, the function here is designed at specifically just
365/// calculating the *index* for ThinLTO. This index will then be shared amongst
366/// all of the `LtoModuleCodegen` units returned below and destroyed once
367/// they all go out of scope.
368fn thin_lto(
369 cgcx: &CodegenContext,
370 prof: &SelfProfilerRef,
371 dcx: DiagCtxtHandle<'_>,
372 modules: Vec<ThinLtoInput<LlvmCodegenBackend>>,
373 serialized_modules: Vec<(SerializedModule<ModuleBuffer>, CString)>,
374 symbols_below_threshold: &[*const libc::c_char],
375) -> (Vec<ThinModule<LlvmCodegenBackend>>, Vec<WorkProduct>) {
376let _timer = prof.generic_activity("LLVM_thin_lto_global_analysis");
377unsafe {
378{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_llvm/src/back/lto.rs:378",
"rustc_codegen_llvm::back::lto", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/back/lto.rs"),
::tracing_core::__macro_support::Option::Some(378u32),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("going for that thin, thin LTO")
as &dyn Value))])
});
} else { ; }
};info!("going for that thin, thin LTO");
379380let green_modules: FxHashMap<_, _> = modules381 .iter()
382 .filter_map(|module| {
383if let ThinLtoInput::Green { wp, .. } = module {
384Some((wp.cgu_name.clone(), wp.clone()))
385 } else {
386None387 }
388 })
389 .collect();
390391let full_scope_len = modules.len();
392let mut thin_buffers = Vec::with_capacity(modules.len());
393let mut module_names = Vec::with_capacity(full_scope_len);
394let mut thin_modules = Vec::with_capacity(full_scope_len);
395396for (i, module) in modules.into_iter().enumerate() {
397let (name, buffer) = match module {
398 ThinLtoInput::Red { name, buffer } => (name, buffer),
399 ThinLtoInput::Green { wp, buffer } => (wp.cgu_name, buffer),
400 };
401{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_llvm/src/back/lto.rs:401",
"rustc_codegen_llvm::back::lto", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/back/lto.rs"),
::tracing_core::__macro_support::Option::Some(401u32),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("local module: {0} - {1}",
i, name) as &dyn Value))])
});
} else { ; }
};info!("local module: {} - {}", i, name);
402let cname = CString::new(name.as_bytes()).unwrap();
403 thin_modules.push(llvm::ThinLTOModule {
404 identifier: cname.as_ptr(),
405 data: buffer.data().as_ptr(),
406 len: buffer.data().len(),
407 });
408 thin_buffers.push(buffer);
409 module_names.push(cname);
410 }
411412// FIXME: All upstream crates are deserialized internally in the
413 // function below to extract their summary and modules. Note that
414 // unlike the loop above we *must* decode and/or read something
415 // here as these are all just serialized files on disk. An
416 // improvement, however, to make here would be to store the
417 // module summary separately from the actual module itself. Right
418 // now this is store in one large bitcode file, and the entire
419 // file is deflate-compressed. We could try to bypass some of the
420 // decompression by storing the index uncompressed and only
421 // lazily decompressing the bytecode if necessary.
422 //
423 // Note that truly taking advantage of this optimization will
424 // likely be further down the road. We'd have to implement
425 // incremental ThinLTO first where we could actually avoid
426 // looking at upstream modules entirely sometimes (the contents,
427 // we must always unconditionally look at the index).
428429for (module, name) in serialized_modules {
430{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_llvm/src/back/lto.rs:430",
"rustc_codegen_llvm::back::lto", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/back/lto.rs"),
::tracing_core::__macro_support::Option::Some(430u32),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("upstream module {0:?}",
name) as &dyn Value))])
});
} else { ; }
};info!("upstream module {:?}", name);
431 thin_modules.push(llvm::ThinLTOModule {
432 identifier: name.as_ptr(),
433 data: module.data().as_ptr(),
434 len: module.data().len(),
435 });
436 thin_buffers.push(module);
437 module_names.push(name);
438 }
439440// Sanity check
441match (&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());
442443// Delegate to the C++ bindings to create some data here. Once this is a
444 // tried-and-true interface we may wish to try to upstream some of this
445 // to LLVM itself, right now we reimplement a lot of what they do
446 // upstream...
447let data = llvm::LLVMRustCreateThinLTOData(
448thin_modules.as_ptr(),
449thin_modules.len(),
450symbols_below_threshold.as_ptr(),
451symbols_below_threshold.len(),
452 )
453 .unwrap_or_else(|| write::llvm_err(dcx, LlvmError::PrepareThinLtoContext));
454455let data = ThinData(data);
456457{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_llvm/src/back/lto.rs:457",
"rustc_codegen_llvm::back::lto", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/back/lto.rs"),
::tracing_core::__macro_support::Option::Some(457u32),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("thin LTO data created")
as &dyn Value))])
});
} else { ; }
};info!("thin LTO data created");
458459let (key_map_path, prev_key_map, curr_key_map) = if let Some(ref incr_comp_session_dir) =
460cgcx.incr_comp_session_dir
461 {
462let path = incr_comp_session_dir.join(THIN_LTO_KEYS_INCR_COMP_FILE_NAME);
463// If the previous file was deleted, or we get an IO error
464 // reading the file, then we'll just use `None` as the
465 // prev_key_map, which will force the code to be recompiled.
466let prev =
467if path.exists() { ThinLTOKeysMap::load_from_file(&path).ok() } else { None };
468let curr = ThinLTOKeysMap::from_thin_lto_modules(&data, &thin_modules, &module_names);
469 (Some(path), prev, curr)
470 } else {
471// If we don't compile incrementally, we don't need to load the
472 // import data from LLVM.
473if !green_modules.is_empty() {
::core::panicking::panic("assertion failed: green_modules.is_empty()")
};assert!(green_modules.is_empty());
474let curr = ThinLTOKeysMap::default();
475 (None, None, curr)
476 };
477{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_llvm/src/back/lto.rs:477",
"rustc_codegen_llvm::back::lto", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/back/lto.rs"),
::tracing_core::__macro_support::Option::Some(477u32),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("thin LTO cache key map loaded")
as &dyn Value))])
});
} else { ; }
};info!("thin LTO cache key map loaded");
478{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_llvm/src/back/lto.rs:478",
"rustc_codegen_llvm::back::lto", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/back/lto.rs"),
::tracing_core::__macro_support::Option::Some(478u32),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("prev_key_map: {0:#?}",
prev_key_map) as &dyn Value))])
});
} else { ; }
};info!("prev_key_map: {:#?}", prev_key_map);
479{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_llvm/src/back/lto.rs:479",
"rustc_codegen_llvm::back::lto", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/back/lto.rs"),
::tracing_core::__macro_support::Option::Some(479u32),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("curr_key_map: {0:#?}",
curr_key_map) as &dyn Value))])
});
} else { ; }
};info!("curr_key_map: {:#?}", curr_key_map);
480481// Throw our data in an `Arc` as we'll be sharing it across threads. We
482 // also put all memory referenced by the C++ data (buffers, ids, etc)
483 // into the arc as well. After this we'll create a thin module
484 // codegen per module in this data.
485let shared = Arc::new(ThinShared { data, modules: thin_buffers, module_names });
486487let mut copy_jobs = ::alloc::vec::Vec::new()vec![];
488let mut opt_jobs = ::alloc::vec::Vec::new()vec![];
489490{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_llvm/src/back/lto.rs:490",
"rustc_codegen_llvm::back::lto", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/back/lto.rs"),
::tracing_core::__macro_support::Option::Some(490u32),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("checking which modules can be-reused and which have to be re-optimized.")
as &dyn Value))])
});
} else { ; }
};info!("checking which modules can be-reused and which have to be re-optimized.");
491for (module_index, module_name) in shared.module_names.iter().enumerate() {
492let module_name = module_name_to_str(module_name);
493if let (Some(prev_key_map), true) =
494 (prev_key_map.as_ref(), green_modules.contains_key(module_name))
495 {
496if !cgcx.incr_comp_session_dir.is_some() {
::core::panicking::panic("assertion failed: cgcx.incr_comp_session_dir.is_some()")
};assert!(cgcx.incr_comp_session_dir.is_some());
497498// If a module exists in both the current and the previous session,
499 // and has the same LTO cache key in both sessions, then we can re-use it
500if prev_key_map.keys.get(module_name) == curr_key_map.keys.get(module_name) {
501let work_product = green_modules[module_name].clone();
502 copy_jobs.push(work_product);
503{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_llvm/src/back/lto.rs:503",
"rustc_codegen_llvm::back::lto", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/back/lto.rs"),
::tracing_core::__macro_support::Option::Some(503u32),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!(" - {0}: re-used",
module_name) as &dyn Value))])
});
} else { ; }
};info!(" - {}: re-used", module_name);
504if !cgcx.incr_comp_session_dir.is_some() {
::core::panicking::panic("assertion failed: cgcx.incr_comp_session_dir.is_some()")
};assert!(cgcx.incr_comp_session_dir.is_some());
505continue;
506 }
507 }
508509{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_llvm/src/back/lto.rs:509",
"rustc_codegen_llvm::back::lto", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/back/lto.rs"),
::tracing_core::__macro_support::Option::Some(509u32),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!(" - {0}: re-compiled",
module_name) as &dyn Value))])
});
} else { ; }
};info!(" - {}: re-compiled", module_name);
510 opt_jobs.push(ThinModule { shared: Arc::clone(&shared), idx: module_index });
511 }
512513// Save the current ThinLTO import information for the next compilation
514 // session, overwriting the previous serialized data (if any).
515if let Some(path) = key_map_path516 && let Err(err) = curr_key_map.save_to_file(&path)
517 {
518 write::llvm_err(dcx, LlvmError::WriteThinLtoKey { err });
519 }
520521 (opt_jobs, copy_jobs)
522 }
523}
524525pub(crate) fn enable_autodiff_settings(ad: &[config::AutoDiff]) {
526let mut enzyme = llvm::EnzymeWrapper::get_instance();
527528for val in ad {
529// We intentionally don't use a wildcard, to not forget handling anything new.
530match val {
531 config::AutoDiff::PrintPerf => {
532 enzyme.set_print_perf(true);
533 }
534 config::AutoDiff::PrintAA => {
535 enzyme.set_print_activity(true);
536 }
537 config::AutoDiff::PrintTA => {
538 enzyme.set_print_type(true);
539 }
540 config::AutoDiff::PrintTAFn(fun) => {
541 enzyme.set_print_type(true); // Enable general type printing
542enzyme.set_print_type_fun(&fun); // Set specific function to analyze
543}
544 config::AutoDiff::Inline => {
545 enzyme.set_inline(true);
546 }
547 config::AutoDiff::LooseTypes => {
548 enzyme.set_loose_types(true);
549 }
550 config::AutoDiff::PrintSteps => {
551 enzyme.set_print(true);
552 }
553// We handle this in the PassWrapper.cpp
554config::AutoDiff::PrintPasses => {}
555// We handle this in the PassWrapper.cpp
556config::AutoDiff::PrintModBefore => {}
557// We handle this in the PassWrapper.cpp
558config::AutoDiff::PrintModAfter => {}
559// We handle this in the PassWrapper.cpp
560config::AutoDiff::PrintModFinal => {}
561// This is required and already checked
562config::AutoDiff::Enable => {}
563// We handle this below
564config::AutoDiff::NoPostopt => {}
565// Disables TypeTree generation
566config::AutoDiff::NoTT => {}
567 }
568 }
569// This helps with handling enums for now.
570enzyme.set_strict_aliasing(false);
571// FIXME(ZuseZ4): Test this, since it was added a long time ago.
572enzyme.set_rust_rules(true);
573}
574575pub(crate) fn run_pass_manager(
576 cgcx: &CodegenContext,
577 prof: &SelfProfilerRef,
578 dcx: DiagCtxtHandle<'_>,
579 module: &mut ModuleCodegen<ModuleLlvm>,
580 thin: bool,
581) {
582let _timer = prof.generic_activity_with_arg("LLVM_lto_optimize", &*module.name);
583let config = &cgcx.module_config;
584585// Now we have one massive module inside of llmod. Time to run the
586 // LTO-specific optimization passes that LLVM provides.
587 //
588 // This code is based off the code found in llvm's LTO code generator:
589 // llvm/lib/LTO/LTOCodeGenerator.cpp
590{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_llvm/src/back/lto.rs:590",
"rustc_codegen_llvm::back::lto", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/back/lto.rs"),
::tracing_core::__macro_support::Option::Some(590u32),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("running the pass manager")
as &dyn Value))])
});
} else { ; }
};debug!("running the pass manager");
591let opt_stage = if thin { llvm::OptStage::ThinLTO } else { llvm::OptStage::FatLTO };
592let opt_level = config.opt_level.unwrap_or(config::OptLevel::No);
593594// The PostAD behavior is the same that we would have if no autodiff was used.
595 // It will run the default optimization pipeline. If AD is enabled we select
596 // the DuringAD stage, which will disable vectorization and loop unrolling, and
597 // schedule two autodiff optimization + differentiation passes.
598 // We then run the llvm_optimize function a second time, to optimize the code which we generated
599 // in the enzyme differentiation pass.
600let enable_ad = config.autodiff.contains(&config::AutoDiff::Enable);
601let stage = if thin {
602 write::AutodiffStage::PreAD603 } else {
604if enable_ad { write::AutodiffStage::DuringAD } else { write::AutodiffStage::PostAD }
605 };
606607unsafe {
608 write::llvm_optimize(
609cgcx, prof, dcx, module, None, None, config, opt_level, opt_stage, stage,
610 );
611 }
612613if falsecfg!(feature = "llvm_enzyme") && enable_ad && !thin {
614let opt_stage = llvm::OptStage::FatLTO;
615let stage = write::AutodiffStage::PostAD;
616if !config.autodiff.contains(&config::AutoDiff::NoPostopt) {
617unsafe {
618 write::llvm_optimize(
619cgcx, prof, dcx, module, None, None, config, opt_level, opt_stage, stage,
620 );
621 }
622 }
623624// This is the final IR, so people should be able to inspect the optimized autodiff output,
625 // for manual inspection.
626if config.autodiff.contains(&config::AutoDiff::PrintModFinal) {
627unsafe { llvm::LLVMDumpModule(module.module_llvm.llmod()) };
628 }
629 }
630631{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_llvm/src/back/lto.rs:631",
"rustc_codegen_llvm::back::lto", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/back/lto.rs"),
::tracing_core::__macro_support::Option::Some(631u32),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("lto done")
as &dyn Value))])
});
} else { ; }
};debug!("lto done");
632}
633634#[repr(transparent)]
635pub(crate) struct Buffer(&'static mut llvm::Buffer);
636637unsafe impl Sendfor Buffer {}
638unsafe impl Syncfor Buffer {}
639640impl Buffer {
641pub(crate) fn data(&self) -> &[u8] {
642unsafe {
643let ptr = llvm::LLVMRustBufferPtr(self.0);
644let len = llvm::LLVMRustBufferLen(self.0);
645 slice::from_raw_parts(ptr, len)
646 }
647 }
648}
649650impl Dropfor Buffer {
651fn drop(&mut self) {
652unsafe {
653 llvm::LLVMRustBufferFree(&mut *(self.0 as *mut _));
654 }
655 }
656}
657658pub struct ThinData(&'static mut llvm::ThinLTOData);
659660unsafe impl Sendfor ThinData {}
661unsafe impl Syncfor ThinData {}
662663impl Dropfor ThinData {
664fn drop(&mut self) {
665unsafe {
666 llvm::LLVMRustFreeThinLTOData(&mut *(self.0 as *mut _));
667 }
668 }
669}
670671pub struct ModuleBuffer {
672 data: Buffer,
673}
674675impl ModuleBuffer {
676pub(crate) fn new(m: &llvm::Module, is_thin: bool) -> ModuleBuffer {
677unsafe {
678let buffer = llvm::LLVMRustModuleSerialize(m, is_thin);
679ModuleBuffer { data: Buffer(buffer) }
680 }
681 }
682}
683684impl ModuleBufferMethods for ModuleBuffer {
685fn data(&self) -> &[u8] {
686self.data.data()
687 }
688}
689690pub(crate) fn optimize_and_codegen_thin_module(
691 cgcx: &CodegenContext,
692 prof: &SelfProfilerRef,
693 shared_emitter: &SharedEmitter,
694 tm_factory: TargetMachineFactoryFn<LlvmCodegenBackend>,
695 thin_module: ThinModule<LlvmCodegenBackend>,
696) -> CompiledModule {
697let dcx = DiagCtxt::new(Box::new(shared_emitter.clone()));
698let dcx = dcx.handle();
699700let module_name = &thin_module.shared.module_names[thin_module.idx];
701702// Right now the implementation we've got only works over serialized
703 // modules, so we create a fresh new LLVM context and parse the module
704 // into that context. One day, however, we may do this for upstream
705 // crates but for locally codegened modules we may be able to reuse
706 // that LLVM Context and Module.
707let module_llvm = ModuleLlvm::parse(cgcx, tm_factory, module_name, thin_module.data(), dcx);
708let mut module = ModuleCodegen::new_regular(thin_module.name(), module_llvm);
709// Given that the newly created module lacks a thinlto buffer for embedding, we need to re-add it here.
710if cgcx.module_config.embed_bitcode() {
711module.thin_lto_buffer = Some(thin_module.data().to_vec());
712 }
713 {
714let target = &*module.module_llvm.tm;
715let llmod = module.module_llvm.llmod();
716save_temp_bitcode(cgcx, &module, "thin-lto-input");
717718// Up next comes the per-module local analyses that we do for Thin LTO.
719 // Each of these functions is basically copied from the LLVM
720 // implementation and then tailored to suit this implementation. Ideally
721 // each of these would be supported by upstream LLVM but that's perhaps
722 // a patch for another day!
723 //
724 // You can find some more comments about these functions in the LLVM
725 // bindings we've got (currently `PassWrapper.cpp`)
726{
727let _timer = prof.generic_activity_with_arg("LLVM_thin_lto_rename", thin_module.name());
728unsafe {
729 llvm::LLVMRustPrepareThinLTORename(thin_module.shared.data.0, llmod, target.raw())
730 };
731save_temp_bitcode(cgcx, &module, "thin-lto-after-rename");
732 }
733734 {
735let _timer =
736prof.generic_activity_with_arg("LLVM_thin_lto_resolve_weak", thin_module.name());
737if unsafe { !llvm::LLVMRustPrepareThinLTOResolveWeak(thin_module.shared.data.0, llmod) }
738 {
739 write::llvm_err(dcx, LlvmError::PrepareThinLtoModule);
740 }
741save_temp_bitcode(cgcx, &module, "thin-lto-after-resolve");
742 }
743744 {
745let _timer =
746prof.generic_activity_with_arg("LLVM_thin_lto_internalize", thin_module.name());
747if unsafe { !llvm::LLVMRustPrepareThinLTOInternalize(thin_module.shared.data.0, llmod) }
748 {
749 write::llvm_err(dcx, LlvmError::PrepareThinLtoModule);
750 }
751save_temp_bitcode(cgcx, &module, "thin-lto-after-internalize");
752 }
753754 {
755let _timer = prof.generic_activity_with_arg("LLVM_thin_lto_import", thin_module.name());
756if unsafe {
757 !llvm::LLVMRustPrepareThinLTOImport(thin_module.shared.data.0, llmod, target.raw())
758 } {
759 write::llvm_err(dcx, LlvmError::PrepareThinLtoModule);
760 }
761save_temp_bitcode(cgcx, &module, "thin-lto-after-import");
762 }
763764// Alright now that we've done everything related to the ThinLTO
765 // analysis it's time to run some optimizations! Here we use the same
766 // `run_pass_manager` as the "fat" LTO above except that we tell it to
767 // populate a thin-specific pass manager, which presumably LLVM treats a
768 // little differently.
769{
770{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_llvm/src/back/lto.rs:770",
"rustc_codegen_llvm::back::lto", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/back/lto.rs"),
::tracing_core::__macro_support::Option::Some(770u32),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("running thin lto passes over {0}",
module.name) as &dyn Value))])
});
} else { ; }
};info!("running thin lto passes over {}", module.name);
771run_pass_manager(cgcx, prof, dcx, &mut module, true);
772save_temp_bitcode(cgcx, &module, "thin-lto-after-pm");
773 }
774 }
775codegen(cgcx, prof, shared_emitter, module, &cgcx.module_config)
776}
777778/// Maps LLVM module identifiers to their corresponding LLVM LTO cache keys
779#[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() -> ThinLTOKeysMap {
ThinLTOKeysMap { keys: ::core::default::Default::default() }
}
}Default)]
780struct ThinLTOKeysMap {
781// key = llvm name of importing module, value = LLVM cache key
782keys: BTreeMap<String, String>,
783}
784785impl ThinLTOKeysMap {
786fn save_to_file(&self, path: &Path) -> io::Result<()> {
787use std::io::Write;
788let mut writer = File::create_buffered(path)?;
789// The entries are loaded back into a hash map in `load_from_file()`, so
790 // the order in which we write them to file here does not matter.
791for (module, key) in &self.keys {
792writer.write_fmt(format_args!("{0} {1}\n", module, key))writeln!(writer, "{module} {key}")?;
793 }
794Ok(())
795 }
796797fn load_from_file(path: &Path) -> io::Result<Self> {
798use std::io::BufRead;
799let mut keys = BTreeMap::default();
800let file = File::open_buffered(path)?;
801for line in file.lines() {
802let line = line?;
803let mut split = line.split(' ');
804let module = split.next().unwrap();
805let key = split.next().unwrap();
806match (&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:?}");
807 keys.insert(module.to_string(), key.to_string());
808 }
809Ok(Self { keys })
810 }
811812fn from_thin_lto_modules(
813 data: &ThinData,
814 modules: &[llvm::ThinLTOModule],
815 names: &[CString],
816 ) -> Self {
817let keys = iter::zip(modules, names)
818 .map(|(module, name)| {
819let key = build_string(|rust_str| unsafe {
820 llvm::LLVMRustComputeLTOCacheKey(rust_str, module.identifier, data.0);
821 })
822 .expect("Invalid ThinLTO module key");
823 (module_name_to_str(name).to_string(), key)
824 })
825 .collect();
826Self { keys }
827 }
828}
829830fn module_name_to_str(c_str: &CStr) -> &str {
831c_str.to_str().unwrap_or_else(|e| {
832::rustc_middle::util::bug::bug_fmt(format_args!("Encountered non-utf8 LLVM module name `{0}`: {1}",
c_str.to_string_lossy(), e))bug!("Encountered non-utf8 LLVM module name `{}`: {}", c_str.to_string_lossy(), e)833 })
834}
835836pub(crate) fn parse_module<'a>(
837 cx: &'a llvm::Context,
838 name: &CStr,
839 data: &[u8],
840 dcx: DiagCtxtHandle<'_>,
841) -> &'a llvm::Module {
842unsafe {
843 llvm::LLVMRustParseBitcodeForLTO(cx, data.as_ptr(), data.len(), name.as_ptr())
844 .unwrap_or_else(|| write::llvm_err(dcx, LlvmError::ParseBitcode))
845 }
846}