1 use crate::back::bytecode::DecodedBytecode;
2 use crate::back::write::{self, DiagnosticHandlers, with_llvm_pmb, save_temp_bitcode,
4 use crate::llvm::archive_ro::ArchiveRO;
5 use crate::llvm::{self, True, False};
6 use crate::{ModuleLlvm, LlvmCodegenBackend};
7 use rustc_codegen_ssa::back::symbol_export;
8 use rustc_codegen_ssa::back::write::{ModuleConfig, CodegenContext, FatLTOInput};
9 use rustc_codegen_ssa::back::lto::{SerializedModule, LtoModuleCodegen, ThinShared, ThinModule};
10 use rustc_codegen_ssa::traits::*;
11 use errors::{FatalError, Handler};
12 use rustc::dep_graph::WorkProduct;
13 use rustc::dep_graph::cgu_reuse_tracker::CguReuse;
14 use rustc::hir::def_id::LOCAL_CRATE;
15 use rustc::middle::exported_symbols::SymbolExportLevel;
16 use rustc::session::config::{self, Lto};
17 use rustc::util::common::time_ext;
18 use rustc_data_structures::fx::FxHashMap;
19 use rustc_codegen_ssa::{RLIB_BYTECODE_EXTENSION, ModuleCodegen, ModuleKind};
21 use std::ffi::{CStr, CString};
26 pub fn crate_type_allows_lto(crate_type: config::CrateType) -> bool {
28 config::CrateType::Executable |
29 config::CrateType::Staticlib |
30 config::CrateType::Cdylib => true,
32 config::CrateType::Dylib |
33 config::CrateType::Rlib |
34 config::CrateType::ProcMacro => false,
38 fn prepare_lto(cgcx: &CodegenContext<LlvmCodegenBackend>,
39 diag_handler: &Handler)
40 -> Result<(Vec<CString>, Vec<(SerializedModule<ModuleBuffer>, CString)>), FatalError>
42 let export_threshold = match cgcx.lto {
43 // We're just doing LTO for our one crate
44 Lto::ThinLocal => SymbolExportLevel::Rust,
46 // We're doing LTO for the entire crate graph
47 Lto::Fat | Lto::Thin => {
48 symbol_export::crates_export_threshold(&cgcx.crate_types)
51 Lto::No => panic!("didn't request LTO but we're doing LTO"),
54 let symbol_filter = &|&(ref name, level): &(String, SymbolExportLevel)| {
55 if level.is_below_threshold(export_threshold) {
56 let mut bytes = Vec::with_capacity(name.len() + 1);
57 bytes.extend(name.bytes());
58 Some(CString::new(bytes).unwrap())
63 let exported_symbols = cgcx.exported_symbols
64 .as_ref().expect("needs exported symbols for LTO");
65 let mut symbol_white_list = {
66 let _timer = cgcx.prof.generic_activity("LLVM_lto_generate_symbol_white_list");
67 exported_symbols[&LOCAL_CRATE]
69 .filter_map(symbol_filter)
70 .collect::<Vec<CString>>()
72 info!("{} symbols to preserve in this crate", symbol_white_list.len());
74 // If we're performing LTO for the entire crate graph, then for each of our
75 // upstream dependencies, find the corresponding rlib and load the bitcode
78 // We save off all the bytecode and LLVM module ids for later processing
79 // with either fat or thin LTO
80 let mut upstream_modules = Vec::new();
81 if cgcx.lto != Lto::ThinLocal {
82 if cgcx.opts.cg.prefer_dynamic {
83 diag_handler.struct_err("cannot prefer dynamic linking when performing LTO")
84 .note("only 'staticlib', 'bin', and 'cdylib' outputs are \
87 return Err(FatalError)
90 // Make sure we actually can run LTO
91 for crate_type in cgcx.crate_types.iter() {
92 if !crate_type_allows_lto(*crate_type) {
93 let e = diag_handler.fatal("lto can only be run for executables, cdylibs and \
94 static library outputs");
99 for &(cnum, ref path) in cgcx.each_linked_rlib_for_lto.iter() {
100 let exported_symbols = cgcx.exported_symbols
101 .as_ref().expect("needs exported symbols for LTO");
103 let _timer = cgcx.prof.generic_activity("LLVM_lto_generate_symbol_white_list");
104 symbol_white_list.extend(
105 exported_symbols[&cnum]
107 .filter_map(symbol_filter));
110 let _timer = cgcx.prof.generic_activity("LLVM_lto_load_upstream_bitcode");
111 let archive = ArchiveRO::open(&path).expect("wanted an rlib");
112 let bytecodes = archive.iter().filter_map(|child| {
113 child.ok().and_then(|c| c.name().map(|name| (name, c)))
114 }).filter(|&(name, _)| name.ends_with(RLIB_BYTECODE_EXTENSION));
115 for (name, data) in bytecodes {
116 info!("adding bytecode {}", name);
117 let bc_encoded = data.data();
119 let (bc, id) = time_ext(cgcx.time_passes, &format!("decode {}", name), || {
120 match DecodedBytecode::new(bc_encoded) {
121 Ok(b) => Ok((b.bytecode(), b.identifier().to_string())),
122 Err(e) => Err(diag_handler.fatal(&e)),
125 let bc = SerializedModule::FromRlib(bc);
126 upstream_modules.push((bc, CString::new(id).unwrap()));
131 Ok((symbol_white_list, upstream_modules))
134 /// Performs fat LTO by merging all modules into a single one and returning it
135 /// for further optimization.
136 pub(crate) fn run_fat(cgcx: &CodegenContext<LlvmCodegenBackend>,
137 modules: Vec<FatLTOInput<LlvmCodegenBackend>>,
138 cached_modules: Vec<(SerializedModule<ModuleBuffer>, WorkProduct)>)
139 -> Result<LtoModuleCodegen<LlvmCodegenBackend>, FatalError>
141 let diag_handler = cgcx.create_diag_handler();
142 let (symbol_white_list, upstream_modules) = prepare_lto(cgcx, &diag_handler)?;
143 let symbol_white_list = symbol_white_list.iter()
145 .collect::<Vec<_>>();
156 /// Performs thin LTO by performing necessary global analysis and returning two
157 /// lists, one of the modules that need optimization and another for modules that
158 /// can simply be copied over from the incr. comp. cache.
159 pub(crate) fn run_thin(cgcx: &CodegenContext<LlvmCodegenBackend>,
160 modules: Vec<(String, ThinBuffer)>,
161 cached_modules: Vec<(SerializedModule<ModuleBuffer>, WorkProduct)>)
162 -> Result<(Vec<LtoModuleCodegen<LlvmCodegenBackend>>, Vec<WorkProduct>), FatalError>
164 let diag_handler = cgcx.create_diag_handler();
165 let (symbol_white_list, upstream_modules) = prepare_lto(cgcx, &diag_handler)?;
166 let symbol_white_list = symbol_white_list.iter()
168 .collect::<Vec<_>>();
169 if cgcx.opts.cg.linker_plugin_lto.enabled() {
170 unreachable!("We should never reach this case if the LTO step \
171 is deferred to the linker");
181 pub(crate) fn prepare_thin(
182 module: ModuleCodegen<ModuleLlvm>
183 ) -> (String, ThinBuffer) {
184 let name = module.name.clone();
185 let buffer = ThinBuffer::new(module.module_llvm.llmod());
189 fn fat_lto(cgcx: &CodegenContext<LlvmCodegenBackend>,
190 diag_handler: &Handler,
191 modules: Vec<FatLTOInput<LlvmCodegenBackend>>,
192 cached_modules: Vec<(SerializedModule<ModuleBuffer>, WorkProduct)>,
193 mut serialized_modules: Vec<(SerializedModule<ModuleBuffer>, CString)>,
194 symbol_white_list: &[*const libc::c_char])
195 -> Result<LtoModuleCodegen<LlvmCodegenBackend>, FatalError>
197 let _timer = cgcx.prof.generic_activity("LLVM_fat_lto_build_monolithic_module");
198 info!("going for a fat lto");
200 // Sort out all our lists of incoming modules into two lists.
202 // * `serialized_modules` (also and argument to this function) contains all
203 // modules that are serialized in-memory.
204 // * `in_memory` contains modules which are already parsed and in-memory,
205 // such as from multi-CGU builds.
207 // All of `cached_modules` (cached from previous incremental builds) can
208 // immediately go onto the `serialized_modules` modules list and then we can
209 // split the `modules` array into these two lists.
210 let mut in_memory = Vec::new();
211 serialized_modules.extend(cached_modules.into_iter().map(|(buffer, wp)| {
212 info!("pushing cached module {:?}", wp.cgu_name);
213 (buffer, CString::new(wp.cgu_name).unwrap())
215 for module in modules {
217 FatLTOInput::InMemory(m) => in_memory.push(m),
218 FatLTOInput::Serialized { name, buffer } => {
219 info!("pushing serialized module {:?}", name);
220 let buffer = SerializedModule::Local(buffer);
221 serialized_modules.push((buffer, CString::new(name).unwrap()));
226 // Find the "costliest" module and merge everything into that codegen unit.
227 // All the other modules will be serialized and reparsed into the new
228 // context, so this hopefully avoids serializing and parsing the largest
231 // Additionally use a regular module as the base here to ensure that various
232 // file copy operations in the backend work correctly. The only other kind
233 // of module here should be an allocator one, and if your crate is smaller
234 // than the allocator module then the size doesn't really matter anyway.
235 let costliest_module = in_memory.iter()
237 .filter(|&(_, module)| module.kind == ModuleKind::Regular)
240 llvm::LLVMRustModuleCost(module.module_llvm.llmod())
246 // If we found a costliest module, we're good to go. Otherwise all our
247 // inputs were serialized which could happen in the case, for example, that
248 // all our inputs were incrementally reread from the cache and we're just
249 // re-executing the LTO passes. If that's the case deserialize the first
250 // module and create a linker with it.
251 let module: ModuleCodegen<ModuleLlvm> = match costliest_module {
252 Some((_cost, i)) => in_memory.remove(i),
254 assert!(serialized_modules.len() > 0, "must have at least one serialized module");
255 let (buffer, name) = serialized_modules.remove(0);
256 info!("no in-memory regular modules to choose from, parsing {:?}", name);
258 module_llvm: ModuleLlvm::parse(cgcx, &name, buffer.data(), diag_handler)?,
259 name: name.into_string().unwrap(),
260 kind: ModuleKind::Regular,
264 let mut serialized_bitcode = Vec::new();
266 let (llcx, llmod) = {
267 let llvm = &module.module_llvm;
268 (&llvm.llcx, llvm.llmod())
270 info!("using {:?} as a base module", module.name);
272 // The linking steps below may produce errors and diagnostics within LLVM
273 // which we'd like to handle and print, so set up our diagnostic handlers
274 // (which get unregistered when they go out of scope below).
275 let _handler = DiagnosticHandlers::new(cgcx, diag_handler, llcx);
277 // For all other modules we codegened we'll need to link them into our own
278 // bitcode. All modules were codegened in their own LLVM context, however,
279 // and we want to move everything to the same LLVM context. Currently the
280 // way we know of to do that is to serialize them to a string and them parse
281 // them later. Not great but hey, that's why it's "fat" LTO, right?
282 for module in in_memory {
283 let buffer = ModuleBuffer::new(module.module_llvm.llmod());
284 let llmod_id = CString::new(&module.name[..]).unwrap();
285 serialized_modules.push((SerializedModule::Local(buffer), llmod_id));
287 // Sort the modules to ensure we produce deterministic results.
288 serialized_modules.sort_by(|module1, module2| module1.1.cmp(&module2.1));
290 // For all serialized bitcode files we parse them and link them in as we did
291 // above, this is all mostly handled in C++. Like above, though, we don't
292 // know much about the memory management here so we err on the side of being
293 // save and persist everything with the original module.
294 let mut linker = Linker::new(llmod);
295 for (bc_decoded, name) in serialized_modules {
296 let _timer = cgcx.prof.generic_activity("LLVM_fat_lto_link_module");
297 info!("linking {:?}", name);
298 time_ext(cgcx.time_passes, &format!("ll link {:?}", name), || {
299 let data = bc_decoded.data();
300 linker.add(&data).map_err(|()| {
301 let msg = format!("failed to load bc of {:?}", name);
302 write::llvm_err(&diag_handler, &msg)
305 serialized_bitcode.push(bc_decoded);
308 save_temp_bitcode(&cgcx, &module, "lto.input");
310 // Internalize everything that *isn't* in our whitelist to help strip out
311 // more modules and such
313 let ptr = symbol_white_list.as_ptr();
314 llvm::LLVMRustRunRestrictionPass(llmod,
315 ptr as *const *const libc::c_char,
316 symbol_white_list.len() as libc::size_t);
317 save_temp_bitcode(&cgcx, &module, "lto.after-restriction");
320 if cgcx.no_landing_pads {
322 llvm::LLVMRustMarkAllFunctionsNounwind(llmod);
324 save_temp_bitcode(&cgcx, &module, "lto.after-nounwind");
328 Ok(LtoModuleCodegen::Fat {
329 module: Some(module),
330 _serialized_bitcode: serialized_bitcode,
334 struct Linker<'a>(&'a mut llvm::Linker<'a>);
337 fn new(llmod: &'a llvm::Module) -> Self {
338 unsafe { Linker(llvm::LLVMRustLinkerNew(llmod)) }
341 fn add(&mut self, bytecode: &[u8]) -> Result<(), ()> {
343 if llvm::LLVMRustLinkerAdd(self.0,
344 bytecode.as_ptr() as *const libc::c_char,
354 impl Drop for Linker<'a> {
356 unsafe { llvm::LLVMRustLinkerFree(&mut *(self.0 as *mut _)); }
360 /// Prepare "thin" LTO to get run on these modules.
362 /// The general structure of ThinLTO is quite different from the structure of
363 /// "fat" LTO above. With "fat" LTO all LLVM modules in question are merged into
364 /// one giant LLVM module, and then we run more optimization passes over this
365 /// big module after internalizing most symbols. Thin LTO, on the other hand,
366 /// avoid this large bottleneck through more targeted optimization.
368 /// At a high level Thin LTO looks like:
370 /// 1. Prepare a "summary" of each LLVM module in question which describes
371 /// the values inside, cost of the values, etc.
372 /// 2. Merge the summaries of all modules in question into one "index"
373 /// 3. Perform some global analysis on this index
374 /// 4. For each module, use the index and analysis calculated previously to
375 /// perform local transformations on the module, for example inlining
376 /// small functions from other modules.
377 /// 5. Run thin-specific optimization passes over each module, and then code
378 /// generate everything at the end.
380 /// The summary for each module is intended to be quite cheap, and the global
381 /// index is relatively quite cheap to create as well. As a result, the goal of
382 /// ThinLTO is to reduce the bottleneck on LTO and enable LTO to be used in more
383 /// situations. For example one cheap optimization is that we can parallelize
384 /// all codegen modules, easily making use of all the cores on a machine.
386 /// With all that in mind, the function here is designed at specifically just
387 /// calculating the *index* for ThinLTO. This index will then be shared amongst
388 /// all of the `LtoModuleCodegen` units returned below and destroyed once
389 /// they all go out of scope.
390 fn thin_lto(cgcx: &CodegenContext<LlvmCodegenBackend>,
391 diag_handler: &Handler,
392 modules: Vec<(String, ThinBuffer)>,
393 serialized_modules: Vec<(SerializedModule<ModuleBuffer>, CString)>,
394 cached_modules: Vec<(SerializedModule<ModuleBuffer>, WorkProduct)>,
395 symbol_white_list: &[*const libc::c_char])
396 -> Result<(Vec<LtoModuleCodegen<LlvmCodegenBackend>>, Vec<WorkProduct>), FatalError>
398 let _timer = cgcx.prof.generic_activity("LLVM_thin_lto_global_analysis");
400 info!("going for that thin, thin LTO");
402 let green_modules: FxHashMap<_, _> = cached_modules
404 .map(|&(_, ref wp)| (wp.cgu_name.clone(), wp.clone()))
407 let full_scope_len = modules.len() + serialized_modules.len() + cached_modules.len();
408 let mut thin_buffers = Vec::with_capacity(modules.len());
409 let mut module_names = Vec::with_capacity(full_scope_len);
410 let mut thin_modules = Vec::with_capacity(full_scope_len);
412 for (i, (name, buffer)) in modules.into_iter().enumerate() {
413 info!("local module: {} - {}", i, name);
414 let cname = CString::new(name.clone()).unwrap();
415 thin_modules.push(llvm::ThinLTOModule {
416 identifier: cname.as_ptr(),
417 data: buffer.data().as_ptr(),
418 len: buffer.data().len(),
420 thin_buffers.push(buffer);
421 module_names.push(cname);
424 // FIXME: All upstream crates are deserialized internally in the
425 // function below to extract their summary and modules. Note that
426 // unlike the loop above we *must* decode and/or read something
427 // here as these are all just serialized files on disk. An
428 // improvement, however, to make here would be to store the
429 // module summary separately from the actual module itself. Right
430 // now this is store in one large bitcode file, and the entire
431 // file is deflate-compressed. We could try to bypass some of the
432 // decompression by storing the index uncompressed and only
433 // lazily decompressing the bytecode if necessary.
435 // Note that truly taking advantage of this optimization will
436 // likely be further down the road. We'd have to implement
437 // incremental ThinLTO first where we could actually avoid
438 // looking at upstream modules entirely sometimes (the contents,
439 // we must always unconditionally look at the index).
440 let mut serialized = Vec::with_capacity(serialized_modules.len() + cached_modules.len());
442 let cached_modules = cached_modules.into_iter().map(|(sm, wp)| {
443 (sm, CString::new(wp.cgu_name).unwrap())
446 for (module, name) in serialized_modules.into_iter().chain(cached_modules) {
447 info!("upstream or cached module {:?}", name);
448 thin_modules.push(llvm::ThinLTOModule {
449 identifier: name.as_ptr(),
450 data: module.data().as_ptr(),
451 len: module.data().len(),
453 serialized.push(module);
454 module_names.push(name);
458 assert_eq!(thin_modules.len(), module_names.len());
460 // Delegate to the C++ bindings to create some data here. Once this is a
461 // tried-and-true interface we may wish to try to upstream some of this
462 // to LLVM itself, right now we reimplement a lot of what they do
464 let data = llvm::LLVMRustCreateThinLTOData(
465 thin_modules.as_ptr(),
466 thin_modules.len() as u32,
467 symbol_white_list.as_ptr(),
468 symbol_white_list.len() as u32,
470 write::llvm_err(&diag_handler, "failed to prepare thin LTO context")
473 info!("thin LTO data created");
475 let import_map = if cgcx.incr_comp_session_dir.is_some() {
476 ThinLTOImports::from_thin_lto_data(data)
478 // If we don't compile incrementally, we don't need to load the
479 // import data from LLVM.
480 assert!(green_modules.is_empty());
481 ThinLTOImports::default()
483 info!("thin LTO import map loaded");
485 let data = ThinData(data);
487 // Throw our data in an `Arc` as we'll be sharing it across threads. We
488 // also put all memory referenced by the C++ data (buffers, ids, etc)
489 // into the arc as well. After this we'll create a thin module
490 // codegen per module in this data.
491 let shared = Arc::new(ThinShared {
494 serialized_modules: serialized,
498 let mut copy_jobs = vec![];
499 let mut opt_jobs = vec![];
501 info!("checking which modules can be-reused and which have to be re-optimized.");
502 for (module_index, module_name) in shared.module_names.iter().enumerate() {
503 let module_name = module_name_to_str(module_name);
505 // If the module hasn't changed and none of the modules it imports
506 // from has changed, we can re-use the post-ThinLTO version of the
508 if green_modules.contains_key(module_name) {
509 let imports_all_green = import_map.modules_imported_by(module_name)
511 .all(|imported_module| green_modules.contains_key(imported_module));
513 if imports_all_green {
514 let work_product = green_modules[module_name].clone();
515 copy_jobs.push(work_product);
516 info!(" - {}: re-used", module_name);
517 cgcx.cgu_reuse_tracker.set_actual_reuse(module_name,
523 info!(" - {}: re-compiled", module_name);
524 opt_jobs.push(LtoModuleCodegen::Thin(ThinModule {
525 shared: shared.clone(),
530 Ok((opt_jobs, copy_jobs))
534 pub(crate) fn run_pass_manager(cgcx: &CodegenContext<LlvmCodegenBackend>,
535 module: &ModuleCodegen<ModuleLlvm>,
536 config: &ModuleConfig,
538 // Now we have one massive module inside of llmod. Time to run the
539 // LTO-specific optimization passes that LLVM provides.
541 // This code is based off the code found in llvm's LTO code generator:
542 // tools/lto/LTOCodeGenerator.cpp
543 debug!("running the pass manager");
545 let pm = llvm::LLVMCreatePassManager();
546 llvm::LLVMRustAddAnalysisPasses(module.module_llvm.tm, pm, module.module_llvm.llmod());
548 if config.verify_llvm_ir {
549 let pass = llvm::LLVMRustFindAndCreatePass("verify\0".as_ptr().cast());
550 llvm::LLVMRustAddPass(pm, pass.unwrap());
553 // When optimizing for LTO we don't actually pass in `-O0`, but we force
554 // it to always happen at least with `-O1`.
556 // With ThinLTO we mess around a lot with symbol visibility in a way
557 // that will actually cause linking failures if we optimize at O0 which
558 // notable is lacking in dead code elimination. To ensure we at least
559 // get some optimizations and correctly link we forcibly switch to `-O1`
560 // to get dead code elimination.
562 // Note that in general this shouldn't matter too much as you typically
563 // only turn on ThinLTO when you're compiling with optimizations
565 let opt_level = config.opt_level.map(|x| to_llvm_opt_settings(x).0)
566 .unwrap_or(llvm::CodeGenOptLevel::None);
567 let opt_level = match opt_level {
568 llvm::CodeGenOptLevel::None => llvm::CodeGenOptLevel::Less,
571 with_llvm_pmb(module.module_llvm.llmod(), config, opt_level, false, &mut |b| {
573 llvm::LLVMRustPassManagerBuilderPopulateThinLTOPassManager(b, pm);
575 llvm::LLVMPassManagerBuilderPopulateLTOPassManager(b, pm,
576 /* Internalize = */ False,
577 /* RunInliner = */ True);
581 // We always generate bitcode through ThinLTOBuffers,
582 // which do not support anonymous globals
583 if config.bitcode_needed() {
584 let pass = llvm::LLVMRustFindAndCreatePass("name-anon-globals\0".as_ptr().cast());
585 llvm::LLVMRustAddPass(pm, pass.unwrap());
588 if config.verify_llvm_ir {
589 let pass = llvm::LLVMRustFindAndCreatePass("verify\0".as_ptr().cast());
590 llvm::LLVMRustAddPass(pm, pass.unwrap());
593 time_ext(cgcx.time_passes, "LTO passes", ||
594 llvm::LLVMRunPassManager(pm, module.module_llvm.llmod()));
596 llvm::LLVMDisposePassManager(pm);
601 pub struct ModuleBuffer(&'static mut llvm::ModuleBuffer);
603 unsafe impl Send for ModuleBuffer {}
604 unsafe impl Sync for ModuleBuffer {}
607 pub fn new(m: &llvm::Module) -> ModuleBuffer {
608 ModuleBuffer(unsafe {
609 llvm::LLVMRustModuleBufferCreate(m)
614 impl ModuleBufferMethods for ModuleBuffer {
615 fn data(&self) -> &[u8] {
617 let ptr = llvm::LLVMRustModuleBufferPtr(self.0);
618 let len = llvm::LLVMRustModuleBufferLen(self.0);
619 slice::from_raw_parts(ptr, len)
624 impl Drop for ModuleBuffer {
626 unsafe { llvm::LLVMRustModuleBufferFree(&mut *(self.0 as *mut _)); }
630 pub struct ThinData(&'static mut llvm::ThinLTOData);
632 unsafe impl Send for ThinData {}
633 unsafe impl Sync for ThinData {}
635 impl Drop for ThinData {
638 llvm::LLVMRustFreeThinLTOData(&mut *(self.0 as *mut _));
643 pub struct ThinBuffer(&'static mut llvm::ThinLTOBuffer);
645 unsafe impl Send for ThinBuffer {}
646 unsafe impl Sync for ThinBuffer {}
649 pub fn new(m: &llvm::Module) -> ThinBuffer {
651 let buffer = llvm::LLVMRustThinLTOBufferCreate(m);
657 impl ThinBufferMethods for ThinBuffer {
658 fn data(&self) -> &[u8] {
660 let ptr = llvm::LLVMRustThinLTOBufferPtr(self.0) as *const _;
661 let len = llvm::LLVMRustThinLTOBufferLen(self.0);
662 slice::from_raw_parts(ptr, len)
667 impl Drop for ThinBuffer {
670 llvm::LLVMRustThinLTOBufferFree(&mut *(self.0 as *mut _));
675 pub unsafe fn optimize_thin_module(
676 thin_module: &mut ThinModule<LlvmCodegenBackend>,
677 cgcx: &CodegenContext<LlvmCodegenBackend>,
678 ) -> Result<ModuleCodegen<ModuleLlvm>, FatalError> {
679 let diag_handler = cgcx.create_diag_handler();
680 let tm = (cgcx.tm_factory.0)().map_err(|e| {
681 write::llvm_err(&diag_handler, &e)
684 // Right now the implementation we've got only works over serialized
685 // modules, so we create a fresh new LLVM context and parse the module
686 // into that context. One day, however, we may do this for upstream
687 // crates but for locally codegened modules we may be able to reuse
688 // that LLVM Context and Module.
689 let llcx = llvm::LLVMRustContextCreate(cgcx.fewer_names);
690 let llmod_raw = parse_module(
692 &thin_module.shared.module_names[thin_module.idx],
696 let module = ModuleCodegen {
697 module_llvm: ModuleLlvm {
702 name: thin_module.name().to_string(),
703 kind: ModuleKind::Regular,
706 let llmod = module.module_llvm.llmod();
707 save_temp_bitcode(&cgcx, &module, "thin-lto-input");
709 // Before we do much else find the "main" `DICompileUnit` that we'll be
710 // using below. If we find more than one though then rustc has changed
711 // in a way we're not ready for, so generate an ICE by returning
713 let mut cu1 = ptr::null_mut();
714 let mut cu2 = ptr::null_mut();
715 llvm::LLVMRustThinLTOGetDICompileUnit(llmod, &mut cu1, &mut cu2);
717 let msg = "multiple source DICompileUnits found";
718 return Err(write::llvm_err(&diag_handler, msg))
721 // Like with "fat" LTO, get some better optimizations if landing pads
722 // are disabled by removing all landing pads.
723 if cgcx.no_landing_pads {
724 let _timer = cgcx.prof.generic_activity("LLVM_thin_lto_remove_landing_pads");
725 llvm::LLVMRustMarkAllFunctionsNounwind(llmod);
726 save_temp_bitcode(&cgcx, &module, "thin-lto-after-nounwind");
729 // Up next comes the per-module local analyses that we do for Thin LTO.
730 // Each of these functions is basically copied from the LLVM
731 // implementation and then tailored to suit this implementation. Ideally
732 // each of these would be supported by upstream LLVM but that's perhaps
733 // a patch for another day!
735 // You can find some more comments about these functions in the LLVM
736 // bindings we've got (currently `PassWrapper.cpp`)
738 let _timer = cgcx.prof.generic_activity("LLVM_thin_lto_rename");
739 if !llvm::LLVMRustPrepareThinLTORename(thin_module.shared.data.0, llmod) {
740 let msg = "failed to prepare thin LTO module";
741 return Err(write::llvm_err(&diag_handler, msg))
743 save_temp_bitcode(cgcx, &module, "thin-lto-after-rename");
747 let _timer = cgcx.prof.generic_activity("LLVM_thin_lto_resolve_weak");
748 if !llvm::LLVMRustPrepareThinLTOResolveWeak(thin_module.shared.data.0, llmod) {
749 let msg = "failed to prepare thin LTO module";
750 return Err(write::llvm_err(&diag_handler, msg))
752 save_temp_bitcode(cgcx, &module, "thin-lto-after-resolve");
756 let _timer = cgcx.prof.generic_activity("LLVM_thin_lto_internalize");
757 if !llvm::LLVMRustPrepareThinLTOInternalize(thin_module.shared.data.0, llmod) {
758 let msg = "failed to prepare thin LTO module";
759 return Err(write::llvm_err(&diag_handler, msg))
761 save_temp_bitcode(cgcx, &module, "thin-lto-after-internalize");
765 let _timer = cgcx.prof.generic_activity("LLVM_thin_lto_import");
766 if !llvm::LLVMRustPrepareThinLTOImport(thin_module.shared.data.0, llmod) {
767 let msg = "failed to prepare thin LTO module";
768 return Err(write::llvm_err(&diag_handler, msg))
770 save_temp_bitcode(cgcx, &module, "thin-lto-after-import");
773 // Ok now this is a bit unfortunate. This is also something you won't
774 // find upstream in LLVM's ThinLTO passes! This is a hack for now to
775 // work around bugs in LLVM.
777 // First discovered in #45511 it was found that as part of ThinLTO
778 // importing passes LLVM will import `DICompileUnit` metadata
779 // information across modules. This means that we'll be working with one
780 // LLVM module that has multiple `DICompileUnit` instances in it (a
781 // bunch of `llvm.dbg.cu` members). Unfortunately there's a number of
782 // bugs in LLVM's backend which generates invalid DWARF in a situation
785 // https://bugs.llvm.org/show_bug.cgi?id=35212
786 // https://bugs.llvm.org/show_bug.cgi?id=35562
788 // While the first bug there is fixed the second ended up causing #46346
789 // which was basically a resurgence of #45511 after LLVM's bug 35212 was
792 // This function below is a huge hack around this problem. The function
793 // below is defined in `PassWrapper.cpp` and will basically "merge"
794 // all `DICompileUnit` instances in a module. Basically it'll take all
795 // the objects, rewrite all pointers of `DISubprogram` to point to the
796 // first `DICompileUnit`, and then delete all the other units.
798 // This is probably mangling to the debug info slightly (but hopefully
799 // not too much) but for now at least gets LLVM to emit valid DWARF (or
800 // so it appears). Hopefully we can remove this once upstream bugs are
803 let _timer = cgcx.prof.generic_activity("LLVM_thin_lto_patch_debuginfo");
804 llvm::LLVMRustThinLTOPatchDICompileUnit(llmod, cu1);
805 save_temp_bitcode(cgcx, &module, "thin-lto-after-patch");
808 // Alright now that we've done everything related to the ThinLTO
809 // analysis it's time to run some optimizations! Here we use the same
810 // `run_pass_manager` as the "fat" LTO above except that we tell it to
811 // populate a thin-specific pass manager, which presumably LLVM treats a
812 // little differently.
814 let _timer = cgcx.prof.generic_activity("LLVM_thin_lto_optimize");
815 info!("running thin lto passes over {}", module.name);
816 let config = cgcx.config(module.kind);
817 run_pass_manager(cgcx, &module, config, true);
818 save_temp_bitcode(cgcx, &module, "thin-lto-after-pm");
824 #[derive(Debug, Default)]
825 pub struct ThinLTOImports {
826 // key = llvm name of importing module, value = list of modules it imports from
827 imports: FxHashMap<String, Vec<String>>,
830 impl ThinLTOImports {
831 fn modules_imported_by(&self, llvm_module_name: &str) -> &[String] {
832 self.imports.get(llvm_module_name).map(|v| &v[..]).unwrap_or(&[])
835 /// Loads the ThinLTO import map from ThinLTOData.
836 unsafe fn from_thin_lto_data(data: *const llvm::ThinLTOData) -> ThinLTOImports {
837 unsafe extern "C" fn imported_module_callback(payload: *mut libc::c_void,
838 importing_module_name: *const libc::c_char,
839 imported_module_name: *const libc::c_char) {
840 let map = &mut* (payload as *mut ThinLTOImports);
841 let importing_module_name = CStr::from_ptr(importing_module_name);
842 let importing_module_name = module_name_to_str(&importing_module_name);
843 let imported_module_name = CStr::from_ptr(imported_module_name);
844 let imported_module_name = module_name_to_str(&imported_module_name);
846 if !map.imports.contains_key(importing_module_name) {
847 map.imports.insert(importing_module_name.to_owned(), vec![]);
851 .get_mut(importing_module_name)
853 .push(imported_module_name.to_owned());
855 let mut map = ThinLTOImports::default();
856 llvm::LLVMRustGetThinLTOModuleImports(data,
857 imported_module_callback,
858 &mut map as *mut _ as *mut libc::c_void);
863 fn module_name_to_str(c_str: &CStr) -> &str {
864 c_str.to_str().unwrap_or_else(|e|
865 bug!("Encountered non-utf8 LLVM module name `{}`: {}", c_str.to_string_lossy(), e))
868 pub fn parse_module<'a>(
869 cx: &'a llvm::Context,
872 diag_handler: &Handler,
873 ) -> Result<&'a llvm::Module, FatalError> {
875 llvm::LLVMRustParseBitcodeForLTO(
881 let msg = "failed to parse bitcode for LTO module";
882 write::llvm_err(&diag_handler, msg)