1use std::collections::BTreeMap;
2use std::ffi::{CStr, CString};
3use std::fs::File;
4use std::path::{Path, PathBuf};
5use std::ptr::NonNull;
6use std::sync::Arc;
7use std::{io, iter, slice};
89use object::read::archive::ArchiveFile;
10use object::{Object, ObjectSection};
11use rustc_codegen_ssa::back::lto::{SerializedModule, ThinModule, ThinShared};
12use rustc_codegen_ssa::back::write::{CodegenContext, FatLtoInput};
13use rustc_codegen_ssa::traits::*;
14use rustc_codegen_ssa::{ModuleCodegen, ModuleKind, looks_like_rust_object_file};
15use rustc_data_structures::fx::FxHashMap;
16use rustc_data_structures::memmap::Mmap;
17use rustc_errors::DiagCtxtHandle;
18use rustc_hir::attrs::SanitizerSet;
19use rustc_middle::bug;
20use rustc_middle::dep_graph::WorkProduct;
21use rustc_session::config::{self, Lto};
22use tracing::{debug, info};
2324use crate::back::write::{
25self, CodegenDiagnosticsStage, DiagnosticHandlers, bitcode_section_name, save_temp_bitcode,
26};
27use crate::errors::{LlvmError, LtoBitcodeFromRlib};
28use crate::llvm::{self, build_string};
29use crate::{LlvmCodegenBackend, ModuleLlvm};
3031/// We keep track of the computed LTO cache keys from the previous
32/// session to determine which CGUs we can reuse.
33const THIN_LTO_KEYS_INCR_COMP_FILE_NAME: &str = "thin-lto-past-keys.bin";
3435fn prepare_lto(
36 cgcx: &CodegenContext<LlvmCodegenBackend>,
37 exported_symbols_for_lto: &[String],
38 each_linked_rlib_for_lto: &[PathBuf],
39 dcx: DiagCtxtHandle<'_>,
40) -> (Vec<CString>, Vec<(SerializedModule<ModuleBuffer>, CString)>) {
41let mut symbols_below_threshold = exported_symbols_for_lto42 .iter()
43 .map(|symbol| CString::new(symbol.to_owned()).unwrap())
44 .collect::<Vec<CString>>();
4546if cgcx.module_config.instrument_coverage || cgcx.module_config.pgo_gen.enabled() {
47// These are weak symbols that point to the profile version and the
48 // profile name, which need to be treated as exported so LTO doesn't nix
49 // them.
50const PROFILER_WEAK_SYMBOLS: [&CStr; 2] =
51 [c"__llvm_profile_raw_version", c"__llvm_profile_filename"];
5253symbols_below_threshold.extend(PROFILER_WEAK_SYMBOLS.iter().map(|&sym| sym.to_owned()));
54 }
5556if cgcx.module_config.sanitizer.contains(SanitizerSet::MEMORY) {
57let mut msan_weak_symbols = Vec::new();
5859// Similar to profiling, preserve weak msan symbol during LTO.
60if cgcx.module_config.sanitizer_recover.contains(SanitizerSet::MEMORY) {
61msan_weak_symbols.push(c"__msan_keep_going");
62 }
6364if cgcx.module_config.sanitizer_memory_track_origins != 0 {
65msan_weak_symbols.push(c"__msan_track_origins");
66 }
6768symbols_below_threshold.extend(msan_weak_symbols.into_iter().map(|sym| sym.to_owned()));
69 }
7071// Preserve LLVM-injected, ASAN-related symbols.
72 // See also https://github.com/rust-lang/rust/issues/113404.
73symbols_below_threshold.push(c"___asan_globals_registered".to_owned());
7475// __llvm_profile_counter_bias is pulled in at link time by an undefined reference to
76 // __llvm_profile_runtime, therefore we won't know until link time if this symbol
77 // should have default visibility.
78symbols_below_threshold.push(c"__llvm_profile_counter_bias".to_owned());
7980// LTO seems to discard this otherwise under certain circumstances.
81symbols_below_threshold.push(c"rust_eh_personality".to_owned());
8283// If we're performing LTO for the entire crate graph, then for each of our
84 // upstream dependencies, find the corresponding rlib and load the bitcode
85 // from the archive.
86 //
87 // We save off all the bytecode and LLVM module ids for later processing
88 // with either fat or thin LTO
89let mut upstream_modules = Vec::new();
90if cgcx.lto != Lto::ThinLocal {
91for path in each_linked_rlib_for_lto {
92let archive_data = unsafe {
93 Mmap::map(std::fs::File::open(&path).expect("couldn't open rlib"))
94 .expect("couldn't map rlib")
95 };
96let archive = ArchiveFile::parse(&*archive_data).expect("wanted an rlib");
97let obj_files = archive
98 .members()
99 .filter_map(|child| {
100 child.ok().and_then(|c| {
101 std::str::from_utf8(c.name()).ok().map(|name| (name.trim(), c))
102 })
103 })
104 .filter(|&(name, _)| looks_like_rust_object_file(name));
105for (name, child) in obj_files {
106{
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:106",
"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(106u32),
::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);
107match get_bitcode_slice_from_object_data(
108 child.data(&*archive_data).expect("corrupt rlib"),
109 cgcx,
110 ) {
111Ok(data) => {
112let module = SerializedModule::FromRlib(data.to_vec());
113 upstream_modules.push((module, CString::new(name).unwrap()));
114 }
115Err(e) => dcx.emit_fatal(e),
116 }
117 }
118 }
119 }
120121 (symbols_below_threshold, upstream_modules)
122}
123124fn get_bitcode_slice_from_object_data<'a>(
125 obj: &'a [u8],
126 cgcx: &CodegenContext<LlvmCodegenBackend>,
127) -> Result<&'a [u8], LtoBitcodeFromRlib> {
128// We're about to assume the data here is an object file with sections, but if it's raw LLVM IR
129 // that won't work. Fortunately, if that's what we have we can just return the object directly,
130 // so we sniff the relevant magic strings here and return.
131if obj.starts_with(b"\xDE\xC0\x17\x0B") || obj.starts_with(b"BC\xC0\xDE") {
132return Ok(obj);
133 }
134// We drop the "__LLVM," prefix here because on Apple platforms there's a notion of "segment
135 // name" which in the public API for sections gets treated as part of the section name, but
136 // internally in MachOObjectFile.cpp gets treated separately.
137let section_name = bitcode_section_name(cgcx).to_str().unwrap().trim_start_matches("__LLVM,");
138139let obj =
140 object::File::parse(obj).map_err(|err| LtoBitcodeFromRlib { err: err.to_string() })?;
141142let section = obj143 .section_by_name(section_name)
144 .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}") })?;
145146section.data().map_err(|err| LtoBitcodeFromRlib { err: err.to_string() })
147}
148149/// Performs fat LTO by merging all modules into a single one and returning it
150/// for further optimization.
151pub(crate) fn run_fat(
152 cgcx: &CodegenContext<LlvmCodegenBackend>,
153 exported_symbols_for_lto: &[String],
154 each_linked_rlib_for_lto: &[PathBuf],
155 modules: Vec<FatLtoInput<LlvmCodegenBackend>>,
156) -> ModuleCodegen<ModuleLlvm> {
157let dcx = cgcx.create_dcx();
158let dcx = dcx.handle();
159let (symbols_below_threshold, upstream_modules) =
160prepare_lto(cgcx, exported_symbols_for_lto, each_linked_rlib_for_lto, dcx);
161let symbols_below_threshold =
162symbols_below_threshold.iter().map(|c| c.as_ptr()).collect::<Vec<_>>();
163fat_lto(cgcx, dcx, modules, upstream_modules, &symbols_below_threshold)
164}
165166/// Performs thin LTO by performing necessary global analysis and returning two
167/// lists, one of the modules that need optimization and another for modules that
168/// can simply be copied over from the incr. comp. cache.
169pub(crate) fn run_thin(
170 cgcx: &CodegenContext<LlvmCodegenBackend>,
171 exported_symbols_for_lto: &[String],
172 each_linked_rlib_for_lto: &[PathBuf],
173 modules: Vec<(String, ThinBuffer)>,
174 cached_modules: Vec<(SerializedModule<ModuleBuffer>, WorkProduct)>,
175) -> (Vec<ThinModule<LlvmCodegenBackend>>, Vec<WorkProduct>) {
176let dcx = cgcx.create_dcx();
177let dcx = dcx.handle();
178let (symbols_below_threshold, upstream_modules) =
179prepare_lto(cgcx, exported_symbols_for_lto, each_linked_rlib_for_lto, dcx);
180let symbols_below_threshold =
181symbols_below_threshold.iter().map(|c| c.as_ptr()).collect::<Vec<_>>();
182if cgcx.opts.cg.linker_plugin_lto.enabled() {
183{
::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!(
184"We should never reach this case if the LTO step \
185 is deferred to the linker"
186);
187 }
188thin_lto(cgcx, dcx, modules, upstream_modules, cached_modules, &symbols_below_threshold)
189}
190191pub(crate) fn prepare_thin(module: ModuleCodegen<ModuleLlvm>) -> (String, ThinBuffer) {
192let name = module.name;
193let buffer = ThinBuffer::new(module.module_llvm.llmod(), true);
194 (name, buffer)
195}
196197fn fat_lto(
198 cgcx: &CodegenContext<LlvmCodegenBackend>,
199 dcx: DiagCtxtHandle<'_>,
200 modules: Vec<FatLtoInput<LlvmCodegenBackend>>,
201mut serialized_modules: Vec<(SerializedModule<ModuleBuffer>, CString)>,
202 symbols_below_threshold: &[*const libc::c_char],
203) -> ModuleCodegen<ModuleLlvm> {
204let _timer = cgcx.prof.generic_activity("LLVM_fat_lto_build_monolithic_module");
205{
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:205",
"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(205u32),
::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");
206207// Sort out all our lists of incoming modules into two lists.
208 //
209 // * `serialized_modules` (also and argument to this function) contains all
210 // modules that are serialized in-memory.
211 // * `in_memory` contains modules which are already parsed and in-memory,
212 // such as from multi-CGU builds.
213let mut in_memory = Vec::new();
214for module in modules {
215match module {
216 FatLtoInput::InMemory(m) => in_memory.push(m),
217 FatLtoInput::Serialized { name, buffer } => {
218{
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:218",
"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(218u32),
::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);
219 serialized_modules.push((buffer, CString::new(name).unwrap()));
220 }
221 }
222 }
223224// Find the "costliest" module and merge everything into that codegen unit.
225 // All the other modules will be serialized and reparsed into the new
226 // context, so this hopefully avoids serializing and parsing the largest
227 // codegen unit.
228 //
229 // Additionally use a regular module as the base here to ensure that various
230 // file copy operations in the backend work correctly. The only other kind
231 // of module here should be an allocator one, and if your crate is smaller
232 // than the allocator module then the size doesn't really matter anyway.
233let costliest_module = in_memory234 .iter()
235 .enumerate()
236 .filter(|&(_, module)| module.kind == ModuleKind::Regular)
237 .map(|(i, module)| {
238let cost = unsafe { llvm::LLVMRustModuleCost(module.module_llvm.llmod()) };
239 (cost, i)
240 })
241 .max();
242243// If we found a costliest module, we're good to go. Otherwise all our
244 // inputs were serialized which could happen in the case, for example, that
245 // all our inputs were incrementally reread from the cache and we're just
246 // re-executing the LTO passes. If that's the case deserialize the first
247 // module and create a linker with it.
248let module: ModuleCodegen<ModuleLlvm> = match costliest_module {
249Some((_cost, i)) => in_memory.remove(i),
250None => {
251if !!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");
252let (buffer, name) = serialized_modules.remove(0);
253{
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:253",
"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(253u32),
::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);
254let llvm_module = ModuleLlvm::parse(cgcx, &name, buffer.data(), dcx);
255 ModuleCodegen::new_regular(name.into_string().unwrap(), llvm_module)
256 }
257 };
258 {
259let (llcx, llmod) = {
260let llvm = &module.module_llvm;
261 (&llvm.llcx, llvm.llmod())
262 };
263{
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:263",
"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(263u32),
::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);
264265// The linking steps below may produce errors and diagnostics within LLVM
266 // which we'd like to handle and print, so set up our diagnostic handlers
267 // (which get unregistered when they go out of scope below).
268let _handler =
269DiagnosticHandlers::new(cgcx, dcx, llcx, &module, CodegenDiagnosticsStage::LTO);
270271// For all other modules we codegened we'll need to link them into our own
272 // bitcode. All modules were codegened in their own LLVM context, however,
273 // and we want to move everything to the same LLVM context. Currently the
274 // way we know of to do that is to serialize them to a string and them parse
275 // them later. Not great but hey, that's why it's "fat" LTO, right?
276for module in in_memory {
277let buffer = ModuleBuffer::new(module.module_llvm.llmod());
278let llmod_id = CString::new(&module.name[..]).unwrap();
279 serialized_modules.push((SerializedModule::Local(buffer), llmod_id));
280 }
281// Sort the modules to ensure we produce deterministic results.
282serialized_modules.sort_by(|module1, module2| module1.1.cmp(&module2.1));
283284// For all serialized bitcode files we parse them and link them in as we did
285 // above, this is all mostly handled in C++.
286let mut linker = Linker::new(llmod);
287for (bc_decoded, name) in serialized_modules {
288let _timer = cgcx
289 .prof
290 .generic_activity_with_arg_recorder("LLVM_fat_lto_link_module", |recorder| {
291 recorder.record_arg(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}", name))
})format!("{name:?}"))
292 });
293{
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:293",
"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(293u32),
::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);
294let data = bc_decoded.data();
295 linker
296 .add(data)
297 .unwrap_or_else(|()| write::llvm_err(dcx, LlvmError::LoadBitcode { name }));
298 }
299drop(linker);
300save_temp_bitcode(cgcx, &module, "lto.input");
301302// Internalize everything below threshold to help strip out more modules and such.
303unsafe {
304let ptr = symbols_below_threshold.as_ptr();
305 llvm::LLVMRustRunRestrictionPass(
306llmod,
307ptras *const *const libc::c_char,
308symbols_below_threshold.len() as libc::size_t,
309 );
310 }
311save_temp_bitcode(cgcx, &module, "lto.after-restriction");
312 }
313314module315}
316317pub(crate) struct Linker<'a>(&'a mut llvm::Linker<'a>);
318319impl<'a> Linker<'a> {
320pub(crate) fn new(llmod: &'a llvm::Module) -> Self {
321unsafe { Linker(llvm::LLVMRustLinkerNew(llmod)) }
322 }
323324pub(crate) fn add(&mut self, bytecode: &[u8]) -> Result<(), ()> {
325unsafe {
326if llvm::LLVMRustLinkerAdd(
327self.0,
328bytecode.as_ptr() as *const libc::c_char,
329bytecode.len(),
330 ) {
331Ok(())
332 } else {
333Err(())
334 }
335 }
336 }
337}
338339impl Dropfor Linker<'_> {
340fn drop(&mut self) {
341unsafe {
342 llvm::LLVMRustLinkerFree(&mut *(self.0 as *mut _));
343 }
344 }
345}
346347/// Prepare "thin" LTO to get run on these modules.
348///
349/// The general structure of ThinLTO is quite different from the structure of
350/// "fat" LTO above. With "fat" LTO all LLVM modules in question are merged into
351/// one giant LLVM module, and then we run more optimization passes over this
352/// big module after internalizing most symbols. Thin LTO, on the other hand,
353/// avoid this large bottleneck through more targeted optimization.
354///
355/// At a high level Thin LTO looks like:
356///
357/// 1. Prepare a "summary" of each LLVM module in question which describes
358/// the values inside, cost of the values, etc.
359/// 2. Merge the summaries of all modules in question into one "index"
360/// 3. Perform some global analysis on this index
361/// 4. For each module, use the index and analysis calculated previously to
362/// perform local transformations on the module, for example inlining
363/// small functions from other modules.
364/// 5. Run thin-specific optimization passes over each module, and then code
365/// generate everything at the end.
366///
367/// The summary for each module is intended to be quite cheap, and the global
368/// index is relatively quite cheap to create as well. As a result, the goal of
369/// ThinLTO is to reduce the bottleneck on LTO and enable LTO to be used in more
370/// situations. For example one cheap optimization is that we can parallelize
371/// all codegen modules, easily making use of all the cores on a machine.
372///
373/// With all that in mind, the function here is designed at specifically just
374/// calculating the *index* for ThinLTO. This index will then be shared amongst
375/// all of the `LtoModuleCodegen` units returned below and destroyed once
376/// they all go out of scope.
377fn thin_lto(
378 cgcx: &CodegenContext<LlvmCodegenBackend>,
379 dcx: DiagCtxtHandle<'_>,
380 modules: Vec<(String, ThinBuffer)>,
381 serialized_modules: Vec<(SerializedModule<ModuleBuffer>, CString)>,
382 cached_modules: Vec<(SerializedModule<ModuleBuffer>, WorkProduct)>,
383 symbols_below_threshold: &[*const libc::c_char],
384) -> (Vec<ThinModule<LlvmCodegenBackend>>, Vec<WorkProduct>) {
385let _timer = cgcx.prof.generic_activity("LLVM_thin_lto_global_analysis");
386unsafe {
387{
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:387",
"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(387u32),
::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");
388389let green_modules: FxHashMap<_, _> =
390cached_modules.iter().map(|(_, wp)| (wp.cgu_name.clone(), wp.clone())).collect();
391392let full_scope_len = modules.len() + serialized_modules.len() + cached_modules.len();
393let mut thin_buffers = Vec::with_capacity(modules.len());
394let mut module_names = Vec::with_capacity(full_scope_len);
395let mut thin_modules = Vec::with_capacity(full_scope_len);
396397for (i, (name, buffer)) in modules.into_iter().enumerate() {
398{
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:398",
"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(398u32),
::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);
399let cname = CString::new(name.as_bytes()).unwrap();
400 thin_modules.push(llvm::ThinLTOModule {
401 identifier: cname.as_ptr(),
402 data: buffer.data().as_ptr(),
403 len: buffer.data().len(),
404 });
405 thin_buffers.push(buffer);
406 module_names.push(cname);
407 }
408409// FIXME: All upstream crates are deserialized internally in the
410 // function below to extract their summary and modules. Note that
411 // unlike the loop above we *must* decode and/or read something
412 // here as these are all just serialized files on disk. An
413 // improvement, however, to make here would be to store the
414 // module summary separately from the actual module itself. Right
415 // now this is store in one large bitcode file, and the entire
416 // file is deflate-compressed. We could try to bypass some of the
417 // decompression by storing the index uncompressed and only
418 // lazily decompressing the bytecode if necessary.
419 //
420 // Note that truly taking advantage of this optimization will
421 // likely be further down the road. We'd have to implement
422 // incremental ThinLTO first where we could actually avoid
423 // looking at upstream modules entirely sometimes (the contents,
424 // we must always unconditionally look at the index).
425let mut serialized = Vec::with_capacity(serialized_modules.len() + cached_modules.len());
426427let cached_modules =
428cached_modules.into_iter().map(|(sm, wp)| (sm, CString::new(wp.cgu_name).unwrap()));
429430for (module, name) in serialized_modules.into_iter().chain(cached_modules) {
431{
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:431",
"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(431u32),
::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 or cached module {0:?}",
name) as &dyn Value))])
});
} else { ; }
};info!("upstream or cached module {:?}", name);
432 thin_modules.push(llvm::ThinLTOModule {
433 identifier: name.as_ptr(),
434 data: module.data().as_ptr(),
435 len: module.data().len(),
436 });
437 serialized.push(module);
438 module_names.push(name);
439 }
440441// Sanity check
442match (&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());
443444// Delegate to the C++ bindings to create some data here. Once this is a
445 // tried-and-true interface we may wish to try to upstream some of this
446 // to LLVM itself, right now we reimplement a lot of what they do
447 // upstream...
448let data = llvm::LLVMRustCreateThinLTOData(
449thin_modules.as_ptr(),
450thin_modules.len(),
451symbols_below_threshold.as_ptr(),
452symbols_below_threshold.len(),
453 )
454 .unwrap_or_else(|| write::llvm_err(dcx, LlvmError::PrepareThinLtoContext));
455456let data = ThinData(data);
457458{
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:458",
"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(458u32),
::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");
459460let (key_map_path, prev_key_map, curr_key_map) = if let Some(ref incr_comp_session_dir) =
461cgcx.incr_comp_session_dir
462 {
463let path = incr_comp_session_dir.join(THIN_LTO_KEYS_INCR_COMP_FILE_NAME);
464// If the previous file was deleted, or we get an IO error
465 // reading the file, then we'll just use `None` as the
466 // prev_key_map, which will force the code to be recompiled.
467let prev =
468if path.exists() { ThinLTOKeysMap::load_from_file(&path).ok() } else { None };
469let curr = ThinLTOKeysMap::from_thin_lto_modules(&data, &thin_modules, &module_names);
470 (Some(path), prev, curr)
471 } else {
472// If we don't compile incrementally, we don't need to load the
473 // import data from LLVM.
474if !green_modules.is_empty() {
::core::panicking::panic("assertion failed: green_modules.is_empty()")
};assert!(green_modules.is_empty());
475let curr = ThinLTOKeysMap::default();
476 (None, None, curr)
477 };
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!("thin LTO cache key map loaded")
as &dyn Value))])
});
} else { ; }
};info!("thin LTO cache key map loaded");
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!("prev_key_map: {0:#?}",
prev_key_map) as &dyn Value))])
});
} else { ; }
};info!("prev_key_map: {:#?}", prev_key_map);
480{
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:480",
"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(480u32),
::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);
481482// Throw our data in an `Arc` as we'll be sharing it across threads. We
483 // also put all memory referenced by the C++ data (buffers, ids, etc)
484 // into the arc as well. After this we'll create a thin module
485 // codegen per module in this data.
486let shared = Arc::new(ThinShared {
487data,
488thin_buffers,
489 serialized_modules: serialized,
490module_names,
491 });
492493let mut copy_jobs = ::alloc::vec::Vec::new()vec![];
494let mut opt_jobs = ::alloc::vec::Vec::new()vec![];
495496{
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:496",
"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(496u32),
::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.");
497for (module_index, module_name) in shared.module_names.iter().enumerate() {
498let module_name = module_name_to_str(module_name);
499if let (Some(prev_key_map), true) =
500 (prev_key_map.as_ref(), green_modules.contains_key(module_name))
501 {
502if !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());
503504// If a module exists in both the current and the previous session,
505 // and has the same LTO cache key in both sessions, then we can re-use it
506if prev_key_map.keys.get(module_name) == curr_key_map.keys.get(module_name) {
507let work_product = green_modules[module_name].clone();
508 copy_jobs.push(work_product);
509{
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-used",
module_name) as &dyn Value))])
});
} else { ; }
};info!(" - {}: re-used", module_name);
510if !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());
511continue;
512 }
513 }
514515{
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:515",
"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(515u32),
::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);
516 opt_jobs.push(ThinModule { shared: Arc::clone(&shared), idx: module_index });
517 }
518519// Save the current ThinLTO import information for the next compilation
520 // session, overwriting the previous serialized data (if any).
521if let Some(path) = key_map_path522 && let Err(err) = curr_key_map.save_to_file(&path)
523 {
524 write::llvm_err(dcx, LlvmError::WriteThinLtoKey { err });
525 }
526527 (opt_jobs, copy_jobs)
528 }
529}
530531#[cfg(feature = "llvm_enzyme")]
532pub(crate) fn enable_autodiff_settings(ad: &[config::AutoDiff]) {
533let mut enzyme = llvm::EnzymeWrapper::get_instance();
534535for val in ad {
536// We intentionally don't use a wildcard, to not forget handling anything new.
537match val {
538 config::AutoDiff::PrintPerf => {
539 enzyme.set_print_perf(true);
540 }
541 config::AutoDiff::PrintAA => {
542 enzyme.set_print_activity(true);
543 }
544 config::AutoDiff::PrintTA => {
545 enzyme.set_print_type(true);
546 }
547 config::AutoDiff::PrintTAFn(fun) => {
548 enzyme.set_print_type(true); // Enable general type printing
549enzyme.set_print_type_fun(&fun); // Set specific function to analyze
550}
551 config::AutoDiff::Inline => {
552 enzyme.set_inline(true);
553 }
554 config::AutoDiff::LooseTypes => {
555 enzyme.set_loose_types(true);
556 }
557 config::AutoDiff::PrintSteps => {
558 enzyme.set_print(true);
559 }
560// We handle this in the PassWrapper.cpp
561config::AutoDiff::PrintPasses => {}
562// We handle this in the PassWrapper.cpp
563config::AutoDiff::PrintModBefore => {}
564// We handle this in the PassWrapper.cpp
565config::AutoDiff::PrintModAfter => {}
566// We handle this in the PassWrapper.cpp
567config::AutoDiff::PrintModFinal => {}
568// This is required and already checked
569config::AutoDiff::Enable => {}
570// We handle this below
571config::AutoDiff::NoPostopt => {}
572// Disables TypeTree generation
573config::AutoDiff::NoTT => {}
574 }
575 }
576// This helps with handling enums for now.
577enzyme.set_strict_aliasing(false);
578// FIXME(ZuseZ4): Test this, since it was added a long time ago.
579enzyme.set_rust_rules(true);
580}
581582pub(crate) fn run_pass_manager(
583 cgcx: &CodegenContext<LlvmCodegenBackend>,
584 dcx: DiagCtxtHandle<'_>,
585 module: &mut ModuleCodegen<ModuleLlvm>,
586 thin: bool,
587) {
588let _timer = cgcx.prof.generic_activity_with_arg("LLVM_lto_optimize", &*module.name);
589let config = &cgcx.module_config;
590591// Now we have one massive module inside of llmod. Time to run the
592 // LTO-specific optimization passes that LLVM provides.
593 //
594 // This code is based off the code found in llvm's LTO code generator:
595 // llvm/lib/LTO/LTOCodeGenerator.cpp
596{
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:596",
"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(596u32),
::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");
597let opt_stage = if thin { llvm::OptStage::ThinLTO } else { llvm::OptStage::FatLTO };
598let opt_level = config.opt_level.unwrap_or(config::OptLevel::No);
599600// The PostAD behavior is the same that we would have if no autodiff was used.
601 // It will run the default optimization pipeline. If AD is enabled we select
602 // the DuringAD stage, which will disable vectorization and loop unrolling, and
603 // schedule two autodiff optimization + differentiation passes.
604 // We then run the llvm_optimize function a second time, to optimize the code which we generated
605 // in the enzyme differentiation pass.
606let enable_ad = config.autodiff.contains(&config::AutoDiff::Enable);
607let stage = if thin {
608 write::AutodiffStage::PreAD609 } else {
610if enable_ad { write::AutodiffStage::DuringAD } else { write::AutodiffStage::PostAD }
611 };
612613unsafe {
614 write::llvm_optimize(cgcx, dcx, module, None, config, opt_level, opt_stage, stage);
615 }
616617if falsecfg!(feature = "llvm_enzyme") && enable_ad && !thin {
618let opt_stage = llvm::OptStage::FatLTO;
619let stage = write::AutodiffStage::PostAD;
620if !config.autodiff.contains(&config::AutoDiff::NoPostopt) {
621unsafe {
622 write::llvm_optimize(cgcx, dcx, module, None, config, opt_level, opt_stage, stage);
623 }
624 }
625626// This is the final IR, so people should be able to inspect the optimized autodiff output,
627 // for manual inspection.
628if config.autodiff.contains(&config::AutoDiff::PrintModFinal) {
629unsafe { llvm::LLVMDumpModule(module.module_llvm.llmod()) };
630 }
631 }
632633{
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:633",
"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(633u32),
::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");
634}
635636pub struct ModuleBuffer(&'static mut llvm::ModuleBuffer);
637638unsafe impl Sendfor ModuleBuffer {}
639unsafe impl Syncfor ModuleBuffer {}
640641impl ModuleBuffer {
642pub(crate) fn new(m: &llvm::Module) -> ModuleBuffer {
643ModuleBuffer(unsafe { llvm::LLVMRustModuleBufferCreate(m) })
644 }
645}
646647impl ModuleBufferMethods for ModuleBuffer {
648fn data(&self) -> &[u8] {
649unsafe {
650let ptr = llvm::LLVMRustModuleBufferPtr(self.0);
651let len = llvm::LLVMRustModuleBufferLen(self.0);
652 slice::from_raw_parts(ptr, len)
653 }
654 }
655}
656657impl Dropfor ModuleBuffer {
658fn drop(&mut self) {
659unsafe {
660 llvm::LLVMRustModuleBufferFree(&mut *(self.0 as *mut _));
661 }
662 }
663}
664665pub struct ThinData(&'static mut llvm::ThinLTOData);
666667unsafe impl Sendfor ThinData {}
668unsafe impl Syncfor ThinData {}
669670impl Dropfor ThinData {
671fn drop(&mut self) {
672unsafe {
673 llvm::LLVMRustFreeThinLTOData(&mut *(self.0 as *mut _));
674 }
675 }
676}
677678pub struct ThinBuffer(&'static mut llvm::ThinLTOBuffer);
679680unsafe impl Sendfor ThinBuffer {}
681unsafe impl Syncfor ThinBuffer {}
682683impl ThinBuffer {
684pub(crate) fn new(m: &llvm::Module, is_thin: bool) -> ThinBuffer {
685unsafe {
686let buffer = llvm::LLVMRustThinLTOBufferCreate(m, is_thin);
687ThinBuffer(buffer)
688 }
689 }
690691pub(crate) unsafe fn from_raw_ptr(ptr: *mut llvm::ThinLTOBuffer) -> ThinBuffer {
692let mut ptr = NonNull::new(ptr).unwrap();
693ThinBuffer(unsafe { ptr.as_mut() })
694 }
695696pub(crate) fn thin_link_data(&self) -> &[u8] {
697unsafe {
698let ptr = llvm::LLVMRustThinLTOBufferThinLinkDataPtr(self.0) as *const _;
699let len = llvm::LLVMRustThinLTOBufferThinLinkDataLen(self.0);
700 slice::from_raw_parts(ptr, len)
701 }
702 }
703}
704705impl ThinBufferMethods for ThinBuffer {
706fn data(&self) -> &[u8] {
707unsafe {
708let ptr = llvm::LLVMRustThinLTOBufferPtr(self.0) as *const _;
709let len = llvm::LLVMRustThinLTOBufferLen(self.0);
710 slice::from_raw_parts(ptr, len)
711 }
712 }
713}
714715impl Dropfor ThinBuffer {
716fn drop(&mut self) {
717unsafe {
718 llvm::LLVMRustThinLTOBufferFree(&mut *(self.0 as *mut _));
719 }
720 }
721}
722723pub(crate) fn optimize_thin_module(
724 thin_module: ThinModule<LlvmCodegenBackend>,
725 cgcx: &CodegenContext<LlvmCodegenBackend>,
726) -> ModuleCodegen<ModuleLlvm> {
727let dcx = cgcx.create_dcx();
728let dcx = dcx.handle();
729730let module_name = &thin_module.shared.module_names[thin_module.idx];
731732// Right now the implementation we've got only works over serialized
733 // modules, so we create a fresh new LLVM context and parse the module
734 // into that context. One day, however, we may do this for upstream
735 // crates but for locally codegened modules we may be able to reuse
736 // that LLVM Context and Module.
737let module_llvm = ModuleLlvm::parse(cgcx, module_name, thin_module.data(), dcx);
738let mut module = ModuleCodegen::new_regular(thin_module.name(), module_llvm);
739// Given that the newly created module lacks a thinlto buffer for embedding, we need to re-add it here.
740if cgcx.module_config.embed_bitcode() {
741module.thin_lto_buffer = Some(thin_module.data().to_vec());
742 }
743 {
744let target = &*module.module_llvm.tm;
745let llmod = module.module_llvm.llmod();
746save_temp_bitcode(cgcx, &module, "thin-lto-input");
747748// Up next comes the per-module local analyses that we do for Thin LTO.
749 // Each of these functions is basically copied from the LLVM
750 // implementation and then tailored to suit this implementation. Ideally
751 // each of these would be supported by upstream LLVM but that's perhaps
752 // a patch for another day!
753 //
754 // You can find some more comments about these functions in the LLVM
755 // bindings we've got (currently `PassWrapper.cpp`)
756{
757let _timer =
758cgcx.prof.generic_activity_with_arg("LLVM_thin_lto_rename", thin_module.name());
759unsafe {
760 llvm::LLVMRustPrepareThinLTORename(thin_module.shared.data.0, llmod, target.raw())
761 };
762save_temp_bitcode(cgcx, &module, "thin-lto-after-rename");
763 }
764765 {
766let _timer = cgcx767 .prof
768 .generic_activity_with_arg("LLVM_thin_lto_resolve_weak", thin_module.name());
769if unsafe { !llvm::LLVMRustPrepareThinLTOResolveWeak(thin_module.shared.data.0, llmod) }
770 {
771 write::llvm_err(dcx, LlvmError::PrepareThinLtoModule);
772 }
773save_temp_bitcode(cgcx, &module, "thin-lto-after-resolve");
774 }
775776 {
777let _timer = cgcx778 .prof
779 .generic_activity_with_arg("LLVM_thin_lto_internalize", thin_module.name());
780if unsafe { !llvm::LLVMRustPrepareThinLTOInternalize(thin_module.shared.data.0, llmod) }
781 {
782 write::llvm_err(dcx, LlvmError::PrepareThinLtoModule);
783 }
784save_temp_bitcode(cgcx, &module, "thin-lto-after-internalize");
785 }
786787 {
788let _timer =
789cgcx.prof.generic_activity_with_arg("LLVM_thin_lto_import", thin_module.name());
790if unsafe {
791 !llvm::LLVMRustPrepareThinLTOImport(thin_module.shared.data.0, llmod, target.raw())
792 } {
793 write::llvm_err(dcx, LlvmError::PrepareThinLtoModule);
794 }
795save_temp_bitcode(cgcx, &module, "thin-lto-after-import");
796 }
797798// Alright now that we've done everything related to the ThinLTO
799 // analysis it's time to run some optimizations! Here we use the same
800 // `run_pass_manager` as the "fat" LTO above except that we tell it to
801 // populate a thin-specific pass manager, which presumably LLVM treats a
802 // little differently.
803{
804{
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:804",
"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(804u32),
::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);
805run_pass_manager(cgcx, dcx, &mut module, true);
806save_temp_bitcode(cgcx, &module, "thin-lto-after-pm");
807 }
808 }
809module810}
811812/// Maps LLVM module identifiers to their corresponding LLVM LTO cache keys
813#[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)]
814struct ThinLTOKeysMap {
815// key = llvm name of importing module, value = LLVM cache key
816keys: BTreeMap<String, String>,
817}
818819impl ThinLTOKeysMap {
820fn save_to_file(&self, path: &Path) -> io::Result<()> {
821use std::io::Write;
822let mut writer = File::create_buffered(path)?;
823// The entries are loaded back into a hash map in `load_from_file()`, so
824 // the order in which we write them to file here does not matter.
825for (module, key) in &self.keys {
826writer.write_fmt(format_args!("{0} {1}\n", module, key))writeln!(writer, "{module} {key}")?;
827 }
828Ok(())
829 }
830831fn load_from_file(path: &Path) -> io::Result<Self> {
832use std::io::BufRead;
833let mut keys = BTreeMap::default();
834let file = File::open_buffered(path)?;
835for line in file.lines() {
836let line = line?;
837let mut split = line.split(' ');
838let module = split.next().unwrap();
839let key = split.next().unwrap();
840match (&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:?}");
841 keys.insert(module.to_string(), key.to_string());
842 }
843Ok(Self { keys })
844 }
845846fn from_thin_lto_modules(
847 data: &ThinData,
848 modules: &[llvm::ThinLTOModule],
849 names: &[CString],
850 ) -> Self {
851let keys = iter::zip(modules, names)
852 .map(|(module, name)| {
853let key = build_string(|rust_str| unsafe {
854 llvm::LLVMRustComputeLTOCacheKey(rust_str, module.identifier, data.0);
855 })
856 .expect("Invalid ThinLTO module key");
857 (module_name_to_str(name).to_string(), key)
858 })
859 .collect();
860Self { keys }
861 }
862}
863864fn module_name_to_str(c_str: &CStr) -> &str {
865c_str.to_str().unwrap_or_else(|e| {
866::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)867 })
868}
869870pub(crate) fn parse_module<'a>(
871 cx: &'a llvm::Context,
872 name: &CStr,
873 data: &[u8],
874 dcx: DiagCtxtHandle<'_>,
875) -> &'a llvm::Module {
876unsafe {
877 llvm::LLVMRustParseBitcodeForLTO(cx, data.as_ptr(), data.len(), name.as_ptr())
878 .unwrap_or_else(|| write::llvm_err(dcx, LlvmError::ParseBitcode))
879 }
880}