]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_codegen_llvm/src/back/lto.rs
Auto merge of #105701 - RedDocMD:bug-105634, r=cjgillot
[rust.git] / compiler / rustc_codegen_llvm / src / back / lto.rs
1 use crate::back::write::{self, save_temp_bitcode, DiagnosticHandlers};
2 use crate::errors::DynamicLinkingWithLTO;
3 use crate::llvm::{self, build_string};
4 use crate::{LlvmCodegenBackend, ModuleLlvm};
5 use object::read::archive::ArchiveFile;
6 use rustc_codegen_ssa::back::lto::{LtoModuleCodegen, SerializedModule, ThinModule, ThinShared};
7 use rustc_codegen_ssa::back::symbol_export;
8 use rustc_codegen_ssa::back::write::{CodegenContext, FatLTOInput, TargetMachineFactoryConfig};
9 use rustc_codegen_ssa::traits::*;
10 use rustc_codegen_ssa::{looks_like_rust_object_file, ModuleCodegen, ModuleKind};
11 use rustc_data_structures::fx::FxHashMap;
12 use rustc_data_structures::memmap::Mmap;
13 use rustc_errors::{FatalError, Handler};
14 use rustc_hir::def_id::LOCAL_CRATE;
15 use rustc_middle::bug;
16 use rustc_middle::dep_graph::WorkProduct;
17 use rustc_middle::middle::exported_symbols::{SymbolExportInfo, SymbolExportLevel};
18 use rustc_session::cgu_reuse_tracker::CguReuse;
19 use rustc_session::config::{self, CrateType, Lto};
20
21 use std::ffi::{CStr, CString};
22 use std::fs::File;
23 use std::io;
24 use std::iter;
25 use std::path::Path;
26 use std::ptr;
27 use std::slice;
28 use std::sync::Arc;
29
30 /// We keep track of the computed LTO cache keys from the previous
31 /// session to determine which CGUs we can reuse.
32 pub const THIN_LTO_KEYS_INCR_COMP_FILE_NAME: &str = "thin-lto-past-keys.bin";
33
34 pub fn crate_type_allows_lto(crate_type: CrateType) -> bool {
35     match crate_type {
36         CrateType::Executable | CrateType::Dylib | CrateType::Staticlib | CrateType::Cdylib => true,
37         CrateType::Rlib | CrateType::ProcMacro => false,
38     }
39 }
40
41 fn prepare_lto(
42     cgcx: &CodegenContext<LlvmCodegenBackend>,
43     diag_handler: &Handler,
44 ) -> Result<(Vec<CString>, Vec<(SerializedModule<ModuleBuffer>, CString)>), FatalError> {
45     let export_threshold = match cgcx.lto {
46         // We're just doing LTO for our one crate
47         Lto::ThinLocal => SymbolExportLevel::Rust,
48
49         // We're doing LTO for the entire crate graph
50         Lto::Fat | Lto::Thin => symbol_export::crates_export_threshold(&cgcx.crate_types),
51
52         Lto::No => panic!("didn't request LTO but we're doing LTO"),
53     };
54
55     let symbol_filter = &|&(ref name, info): &(String, SymbolExportInfo)| {
56         if info.level.is_below_threshold(export_threshold) || info.used {
57             Some(CString::new(name.as_str()).unwrap())
58         } else {
59             None
60         }
61     };
62     let exported_symbols = cgcx.exported_symbols.as_ref().expect("needs exported symbols for LTO");
63     let mut symbols_below_threshold = {
64         let _timer = cgcx.prof.generic_activity("LLVM_lto_generate_symbols_below_threshold");
65         exported_symbols[&LOCAL_CRATE].iter().filter_map(symbol_filter).collect::<Vec<CString>>()
66     };
67     info!("{} symbols to preserve in this crate", symbols_below_threshold.len());
68
69     // If we're performing LTO for the entire crate graph, then for each of our
70     // upstream dependencies, find the corresponding rlib and load the bitcode
71     // from the archive.
72     //
73     // We save off all the bytecode and LLVM module ids for later processing
74     // with either fat or thin LTO
75     let mut upstream_modules = Vec::new();
76     if cgcx.lto != Lto::ThinLocal {
77         // Make sure we actually can run LTO
78         for crate_type in cgcx.crate_types.iter() {
79             if !crate_type_allows_lto(*crate_type) {
80                 let e = diag_handler.fatal(
81                     "lto can only be run for executables, cdylibs and \
82                                             static library outputs",
83                 );
84                 return Err(e);
85             } else if *crate_type == CrateType::Dylib {
86                 if !cgcx.opts.unstable_opts.dylib_lto {
87                     return Err(diag_handler
88                         .fatal("lto cannot be used for `dylib` crate type without `-Zdylib-lto`"));
89                 }
90             }
91         }
92
93         if cgcx.opts.cg.prefer_dynamic && !cgcx.opts.unstable_opts.dylib_lto {
94             diag_handler.emit_err(DynamicLinkingWithLTO);
95             return Err(FatalError);
96         }
97
98         for &(cnum, ref path) in cgcx.each_linked_rlib_for_lto.iter() {
99             let exported_symbols =
100                 cgcx.exported_symbols.as_ref().expect("needs exported symbols for LTO");
101             {
102                 let _timer =
103                     cgcx.prof.generic_activity("LLVM_lto_generate_symbols_below_threshold");
104                 symbols_below_threshold
105                     .extend(exported_symbols[&cnum].iter().filter_map(symbol_filter));
106             }
107
108             let archive_data = unsafe {
109                 Mmap::map(std::fs::File::open(&path).expect("couldn't open rlib"))
110                     .expect("couldn't map rlib")
111             };
112             let archive = ArchiveFile::parse(&*archive_data).expect("wanted an rlib");
113             let obj_files = archive
114                 .members()
115                 .filter_map(|child| {
116                     child.ok().and_then(|c| {
117                         std::str::from_utf8(c.name()).ok().map(|name| (name.trim(), c))
118                     })
119                 })
120                 .filter(|&(name, _)| looks_like_rust_object_file(name));
121             for (name, child) in obj_files {
122                 info!("adding bitcode from {}", name);
123                 match get_bitcode_slice_from_object_data(
124                     child.data(&*archive_data).expect("corrupt rlib"),
125                 ) {
126                     Ok(data) => {
127                         let module = SerializedModule::FromRlib(data.to_vec());
128                         upstream_modules.push((module, CString::new(name).unwrap()));
129                     }
130                     Err(msg) => return Err(diag_handler.fatal(&msg)),
131                 }
132             }
133         }
134     }
135
136     // __llvm_profile_counter_bias is pulled in at link time by an undefined reference to
137     // __llvm_profile_runtime, therefore we won't know until link time if this symbol
138     // should have default visibility.
139     symbols_below_threshold.push(CString::new("__llvm_profile_counter_bias").unwrap());
140     Ok((symbols_below_threshold, upstream_modules))
141 }
142
143 fn get_bitcode_slice_from_object_data(obj: &[u8]) -> Result<&[u8], String> {
144     let mut len = 0;
145     let data =
146         unsafe { llvm::LLVMRustGetBitcodeSliceFromObjectData(obj.as_ptr(), obj.len(), &mut len) };
147     if !data.is_null() {
148         assert!(len != 0);
149         let bc = unsafe { slice::from_raw_parts(data, len) };
150
151         // `bc` must be a sub-slice of `obj`.
152         assert!(obj.as_ptr() <= bc.as_ptr());
153         assert!(bc[bc.len()..bc.len()].as_ptr() <= obj[obj.len()..obj.len()].as_ptr());
154
155         Ok(bc)
156     } else {
157         assert!(len == 0);
158         let msg = llvm::last_error().unwrap_or_else(|| "unknown LLVM error".to_string());
159         Err(format!("failed to get bitcode from object file for LTO ({})", msg))
160     }
161 }
162
163 /// Performs fat LTO by merging all modules into a single one and returning it
164 /// for further optimization.
165 pub(crate) fn run_fat(
166     cgcx: &CodegenContext<LlvmCodegenBackend>,
167     modules: Vec<FatLTOInput<LlvmCodegenBackend>>,
168     cached_modules: Vec<(SerializedModule<ModuleBuffer>, WorkProduct)>,
169 ) -> Result<LtoModuleCodegen<LlvmCodegenBackend>, FatalError> {
170     let diag_handler = cgcx.create_diag_handler();
171     let (symbols_below_threshold, upstream_modules) = prepare_lto(cgcx, &diag_handler)?;
172     let symbols_below_threshold =
173         symbols_below_threshold.iter().map(|c| c.as_ptr()).collect::<Vec<_>>();
174     fat_lto(
175         cgcx,
176         &diag_handler,
177         modules,
178         cached_modules,
179         upstream_modules,
180         &symbols_below_threshold,
181     )
182 }
183
184 /// Performs thin LTO by performing necessary global analysis and returning two
185 /// lists, one of the modules that need optimization and another for modules that
186 /// can simply be copied over from the incr. comp. cache.
187 pub(crate) fn run_thin(
188     cgcx: &CodegenContext<LlvmCodegenBackend>,
189     modules: Vec<(String, ThinBuffer)>,
190     cached_modules: Vec<(SerializedModule<ModuleBuffer>, WorkProduct)>,
191 ) -> Result<(Vec<LtoModuleCodegen<LlvmCodegenBackend>>, Vec<WorkProduct>), FatalError> {
192     let diag_handler = cgcx.create_diag_handler();
193     let (symbols_below_threshold, upstream_modules) = prepare_lto(cgcx, &diag_handler)?;
194     let symbols_below_threshold =
195         symbols_below_threshold.iter().map(|c| c.as_ptr()).collect::<Vec<_>>();
196     if cgcx.opts.cg.linker_plugin_lto.enabled() {
197         unreachable!(
198             "We should never reach this case if the LTO step \
199                       is deferred to the linker"
200         );
201     }
202     thin_lto(
203         cgcx,
204         &diag_handler,
205         modules,
206         upstream_modules,
207         cached_modules,
208         &symbols_below_threshold,
209     )
210 }
211
212 pub(crate) fn prepare_thin(module: ModuleCodegen<ModuleLlvm>) -> (String, ThinBuffer) {
213     let name = module.name;
214     let buffer = ThinBuffer::new(module.module_llvm.llmod(), true);
215     (name, buffer)
216 }
217
218 fn fat_lto(
219     cgcx: &CodegenContext<LlvmCodegenBackend>,
220     diag_handler: &Handler,
221     modules: Vec<FatLTOInput<LlvmCodegenBackend>>,
222     cached_modules: Vec<(SerializedModule<ModuleBuffer>, WorkProduct)>,
223     mut serialized_modules: Vec<(SerializedModule<ModuleBuffer>, CString)>,
224     symbols_below_threshold: &[*const libc::c_char],
225 ) -> Result<LtoModuleCodegen<LlvmCodegenBackend>, FatalError> {
226     let _timer = cgcx.prof.generic_activity("LLVM_fat_lto_build_monolithic_module");
227     info!("going for a fat lto");
228
229     // Sort out all our lists of incoming modules into two lists.
230     //
231     // * `serialized_modules` (also and argument to this function) contains all
232     //   modules that are serialized in-memory.
233     // * `in_memory` contains modules which are already parsed and in-memory,
234     //   such as from multi-CGU builds.
235     //
236     // All of `cached_modules` (cached from previous incremental builds) can
237     // immediately go onto the `serialized_modules` modules list and then we can
238     // split the `modules` array into these two lists.
239     let mut in_memory = Vec::new();
240     serialized_modules.extend(cached_modules.into_iter().map(|(buffer, wp)| {
241         info!("pushing cached module {:?}", wp.cgu_name);
242         (buffer, CString::new(wp.cgu_name).unwrap())
243     }));
244     for module in modules {
245         match module {
246             FatLTOInput::InMemory(m) => in_memory.push(m),
247             FatLTOInput::Serialized { name, buffer } => {
248                 info!("pushing serialized module {:?}", name);
249                 let buffer = SerializedModule::Local(buffer);
250                 serialized_modules.push((buffer, CString::new(name).unwrap()));
251             }
252         }
253     }
254
255     // Find the "costliest" module and merge everything into that codegen unit.
256     // All the other modules will be serialized and reparsed into the new
257     // context, so this hopefully avoids serializing and parsing the largest
258     // codegen unit.
259     //
260     // Additionally use a regular module as the base here to ensure that various
261     // file copy operations in the backend work correctly. The only other kind
262     // of module here should be an allocator one, and if your crate is smaller
263     // than the allocator module then the size doesn't really matter anyway.
264     let costliest_module = in_memory
265         .iter()
266         .enumerate()
267         .filter(|&(_, module)| module.kind == ModuleKind::Regular)
268         .map(|(i, module)| {
269             let cost = unsafe { llvm::LLVMRustModuleCost(module.module_llvm.llmod()) };
270             (cost, i)
271         })
272         .max();
273
274     // If we found a costliest module, we're good to go. Otherwise all our
275     // inputs were serialized which could happen in the case, for example, that
276     // all our inputs were incrementally reread from the cache and we're just
277     // re-executing the LTO passes. If that's the case deserialize the first
278     // module and create a linker with it.
279     let module: ModuleCodegen<ModuleLlvm> = match costliest_module {
280         Some((_cost, i)) => in_memory.remove(i),
281         None => {
282             assert!(!serialized_modules.is_empty(), "must have at least one serialized module");
283             let (buffer, name) = serialized_modules.remove(0);
284             info!("no in-memory regular modules to choose from, parsing {:?}", name);
285             ModuleCodegen {
286                 module_llvm: ModuleLlvm::parse(cgcx, &name, buffer.data(), diag_handler)?,
287                 name: name.into_string().unwrap(),
288                 kind: ModuleKind::Regular,
289             }
290         }
291     };
292     let mut serialized_bitcode = Vec::new();
293     {
294         let (llcx, llmod) = {
295             let llvm = &module.module_llvm;
296             (&llvm.llcx, llvm.llmod())
297         };
298         info!("using {:?} as a base module", module.name);
299
300         // The linking steps below may produce errors and diagnostics within LLVM
301         // which we'd like to handle and print, so set up our diagnostic handlers
302         // (which get unregistered when they go out of scope below).
303         let _handler = DiagnosticHandlers::new(cgcx, diag_handler, llcx);
304
305         // For all other modules we codegened we'll need to link them into our own
306         // bitcode. All modules were codegened in their own LLVM context, however,
307         // and we want to move everything to the same LLVM context. Currently the
308         // way we know of to do that is to serialize them to a string and them parse
309         // them later. Not great but hey, that's why it's "fat" LTO, right?
310         for module in in_memory {
311             let buffer = ModuleBuffer::new(module.module_llvm.llmod());
312             let llmod_id = CString::new(&module.name[..]).unwrap();
313             serialized_modules.push((SerializedModule::Local(buffer), llmod_id));
314         }
315         // Sort the modules to ensure we produce deterministic results.
316         serialized_modules.sort_by(|module1, module2| module1.1.cmp(&module2.1));
317
318         // For all serialized bitcode files we parse them and link them in as we did
319         // above, this is all mostly handled in C++. Like above, though, we don't
320         // know much about the memory management here so we err on the side of being
321         // save and persist everything with the original module.
322         let mut linker = Linker::new(llmod);
323         for (bc_decoded, name) in serialized_modules {
324             let _timer = cgcx
325                 .prof
326                 .generic_activity_with_arg_recorder("LLVM_fat_lto_link_module", |recorder| {
327                     recorder.record_arg(format!("{:?}", name))
328                 });
329             info!("linking {:?}", name);
330             let data = bc_decoded.data();
331             linker.add(data).map_err(|()| {
332                 let msg = format!("failed to load bitcode of module {:?}", name);
333                 write::llvm_err(diag_handler, &msg)
334             })?;
335             serialized_bitcode.push(bc_decoded);
336         }
337         drop(linker);
338         save_temp_bitcode(cgcx, &module, "lto.input");
339
340         // Internalize everything below threshold to help strip out more modules and such.
341         unsafe {
342             let ptr = symbols_below_threshold.as_ptr();
343             llvm::LLVMRustRunRestrictionPass(
344                 llmod,
345                 ptr as *const *const libc::c_char,
346                 symbols_below_threshold.len() as libc::size_t,
347             );
348             save_temp_bitcode(cgcx, &module, "lto.after-restriction");
349         }
350     }
351
352     Ok(LtoModuleCodegen::Fat { module, _serialized_bitcode: serialized_bitcode })
353 }
354
355 pub(crate) struct Linker<'a>(&'a mut llvm::Linker<'a>);
356
357 impl<'a> Linker<'a> {
358     pub(crate) fn new(llmod: &'a llvm::Module) -> Self {
359         unsafe { Linker(llvm::LLVMRustLinkerNew(llmod)) }
360     }
361
362     pub(crate) fn add(&mut self, bytecode: &[u8]) -> Result<(), ()> {
363         unsafe {
364             if llvm::LLVMRustLinkerAdd(
365                 self.0,
366                 bytecode.as_ptr() as *const libc::c_char,
367                 bytecode.len(),
368             ) {
369                 Ok(())
370             } else {
371                 Err(())
372             }
373         }
374     }
375 }
376
377 impl Drop for Linker<'_> {
378     fn drop(&mut self) {
379         unsafe {
380             llvm::LLVMRustLinkerFree(&mut *(self.0 as *mut _));
381         }
382     }
383 }
384
385 /// Prepare "thin" LTO to get run on these modules.
386 ///
387 /// The general structure of ThinLTO is quite different from the structure of
388 /// "fat" LTO above. With "fat" LTO all LLVM modules in question are merged into
389 /// one giant LLVM module, and then we run more optimization passes over this
390 /// big module after internalizing most symbols. Thin LTO, on the other hand,
391 /// avoid this large bottleneck through more targeted optimization.
392 ///
393 /// At a high level Thin LTO looks like:
394 ///
395 ///    1. Prepare a "summary" of each LLVM module in question which describes
396 ///       the values inside, cost of the values, etc.
397 ///    2. Merge the summaries of all modules in question into one "index"
398 ///    3. Perform some global analysis on this index
399 ///    4. For each module, use the index and analysis calculated previously to
400 ///       perform local transformations on the module, for example inlining
401 ///       small functions from other modules.
402 ///    5. Run thin-specific optimization passes over each module, and then code
403 ///       generate everything at the end.
404 ///
405 /// The summary for each module is intended to be quite cheap, and the global
406 /// index is relatively quite cheap to create as well. As a result, the goal of
407 /// ThinLTO is to reduce the bottleneck on LTO and enable LTO to be used in more
408 /// situations. For example one cheap optimization is that we can parallelize
409 /// all codegen modules, easily making use of all the cores on a machine.
410 ///
411 /// With all that in mind, the function here is designed at specifically just
412 /// calculating the *index* for ThinLTO. This index will then be shared amongst
413 /// all of the `LtoModuleCodegen` units returned below and destroyed once
414 /// they all go out of scope.
415 fn thin_lto(
416     cgcx: &CodegenContext<LlvmCodegenBackend>,
417     diag_handler: &Handler,
418     modules: Vec<(String, ThinBuffer)>,
419     serialized_modules: Vec<(SerializedModule<ModuleBuffer>, CString)>,
420     cached_modules: Vec<(SerializedModule<ModuleBuffer>, WorkProduct)>,
421     symbols_below_threshold: &[*const libc::c_char],
422 ) -> Result<(Vec<LtoModuleCodegen<LlvmCodegenBackend>>, Vec<WorkProduct>), FatalError> {
423     let _timer = cgcx.prof.generic_activity("LLVM_thin_lto_global_analysis");
424     unsafe {
425         info!("going for that thin, thin LTO");
426
427         let green_modules: FxHashMap<_, _> =
428             cached_modules.iter().map(|(_, wp)| (wp.cgu_name.clone(), wp.clone())).collect();
429
430         let full_scope_len = modules.len() + serialized_modules.len() + cached_modules.len();
431         let mut thin_buffers = Vec::with_capacity(modules.len());
432         let mut module_names = Vec::with_capacity(full_scope_len);
433         let mut thin_modules = Vec::with_capacity(full_scope_len);
434
435         for (i, (name, buffer)) in modules.into_iter().enumerate() {
436             info!("local module: {} - {}", i, name);
437             let cname = CString::new(name.clone()).unwrap();
438             thin_modules.push(llvm::ThinLTOModule {
439                 identifier: cname.as_ptr(),
440                 data: buffer.data().as_ptr(),
441                 len: buffer.data().len(),
442             });
443             thin_buffers.push(buffer);
444             module_names.push(cname);
445         }
446
447         // FIXME: All upstream crates are deserialized internally in the
448         //        function below to extract their summary and modules. Note that
449         //        unlike the loop above we *must* decode and/or read something
450         //        here as these are all just serialized files on disk. An
451         //        improvement, however, to make here would be to store the
452         //        module summary separately from the actual module itself. Right
453         //        now this is store in one large bitcode file, and the entire
454         //        file is deflate-compressed. We could try to bypass some of the
455         //        decompression by storing the index uncompressed and only
456         //        lazily decompressing the bytecode if necessary.
457         //
458         //        Note that truly taking advantage of this optimization will
459         //        likely be further down the road. We'd have to implement
460         //        incremental ThinLTO first where we could actually avoid
461         //        looking at upstream modules entirely sometimes (the contents,
462         //        we must always unconditionally look at the index).
463         let mut serialized = Vec::with_capacity(serialized_modules.len() + cached_modules.len());
464
465         let cached_modules =
466             cached_modules.into_iter().map(|(sm, wp)| (sm, CString::new(wp.cgu_name).unwrap()));
467
468         for (module, name) in serialized_modules.into_iter().chain(cached_modules) {
469             info!("upstream or cached module {:?}", name);
470             thin_modules.push(llvm::ThinLTOModule {
471                 identifier: name.as_ptr(),
472                 data: module.data().as_ptr(),
473                 len: module.data().len(),
474             });
475             serialized.push(module);
476             module_names.push(name);
477         }
478
479         // Sanity check
480         assert_eq!(thin_modules.len(), module_names.len());
481
482         // Delegate to the C++ bindings to create some data here. Once this is a
483         // tried-and-true interface we may wish to try to upstream some of this
484         // to LLVM itself, right now we reimplement a lot of what they do
485         // upstream...
486         let data = llvm::LLVMRustCreateThinLTOData(
487             thin_modules.as_ptr(),
488             thin_modules.len() as u32,
489             symbols_below_threshold.as_ptr(),
490             symbols_below_threshold.len() as u32,
491         )
492         .ok_or_else(|| write::llvm_err(diag_handler, "failed to prepare thin LTO context"))?;
493
494         let data = ThinData(data);
495
496         info!("thin LTO data created");
497
498         let (key_map_path, prev_key_map, curr_key_map) = if let Some(ref incr_comp_session_dir) =
499             cgcx.incr_comp_session_dir
500         {
501             let path = incr_comp_session_dir.join(THIN_LTO_KEYS_INCR_COMP_FILE_NAME);
502             // If the previous file was deleted, or we get an IO error
503             // reading the file, then we'll just use `None` as the
504             // prev_key_map, which will force the code to be recompiled.
505             let prev =
506                 if path.exists() { ThinLTOKeysMap::load_from_file(&path).ok() } else { None };
507             let curr = ThinLTOKeysMap::from_thin_lto_modules(&data, &thin_modules, &module_names);
508             (Some(path), prev, curr)
509         } else {
510             // If we don't compile incrementally, we don't need to load the
511             // import data from LLVM.
512             assert!(green_modules.is_empty());
513             let curr = ThinLTOKeysMap::default();
514             (None, None, curr)
515         };
516         info!("thin LTO cache key map loaded");
517         info!("prev_key_map: {:#?}", prev_key_map);
518         info!("curr_key_map: {:#?}", curr_key_map);
519
520         // Throw our data in an `Arc` as we'll be sharing it across threads. We
521         // also put all memory referenced by the C++ data (buffers, ids, etc)
522         // into the arc as well. After this we'll create a thin module
523         // codegen per module in this data.
524         let shared = Arc::new(ThinShared {
525             data,
526             thin_buffers,
527             serialized_modules: serialized,
528             module_names,
529         });
530
531         let mut copy_jobs = vec![];
532         let mut opt_jobs = vec![];
533
534         info!("checking which modules can be-reused and which have to be re-optimized.");
535         for (module_index, module_name) in shared.module_names.iter().enumerate() {
536             let module_name = module_name_to_str(module_name);
537             if let (Some(prev_key_map), true) =
538                 (prev_key_map.as_ref(), green_modules.contains_key(module_name))
539             {
540                 assert!(cgcx.incr_comp_session_dir.is_some());
541
542                 // If a module exists in both the current and the previous session,
543                 // and has the same LTO cache key in both sessions, then we can re-use it
544                 if prev_key_map.keys.get(module_name) == curr_key_map.keys.get(module_name) {
545                     let work_product = green_modules[module_name].clone();
546                     copy_jobs.push(work_product);
547                     info!(" - {}: re-used", module_name);
548                     assert!(cgcx.incr_comp_session_dir.is_some());
549                     cgcx.cgu_reuse_tracker.set_actual_reuse(module_name, CguReuse::PostLto);
550                     continue;
551                 }
552             }
553
554             info!(" - {}: re-compiled", module_name);
555             opt_jobs.push(LtoModuleCodegen::Thin(ThinModule {
556                 shared: shared.clone(),
557                 idx: module_index,
558             }));
559         }
560
561         // Save the current ThinLTO import information for the next compilation
562         // session, overwriting the previous serialized data (if any).
563         if let Some(path) = key_map_path {
564             if let Err(err) = curr_key_map.save_to_file(&path) {
565                 let msg = format!("Error while writing ThinLTO key data: {}", err);
566                 return Err(write::llvm_err(diag_handler, &msg));
567             }
568         }
569
570         Ok((opt_jobs, copy_jobs))
571     }
572 }
573
574 pub(crate) fn run_pass_manager(
575     cgcx: &CodegenContext<LlvmCodegenBackend>,
576     diag_handler: &Handler,
577     module: &mut ModuleCodegen<ModuleLlvm>,
578     thin: bool,
579 ) -> Result<(), FatalError> {
580     let _timer = cgcx.prof.verbose_generic_activity_with_arg("LLVM_lto_optimize", &*module.name);
581     let config = cgcx.config(module.kind);
582
583     // Now we have one massive module inside of llmod. Time to run the
584     // LTO-specific optimization passes that LLVM provides.
585     //
586     // This code is based off the code found in llvm's LTO code generator:
587     //      llvm/lib/LTO/LTOCodeGenerator.cpp
588     debug!("running the pass manager");
589     unsafe {
590         if !llvm::LLVMRustHasModuleFlag(
591             module.module_llvm.llmod(),
592             "LTOPostLink".as_ptr().cast(),
593             11,
594         ) {
595             llvm::LLVMRustAddModuleFlag(
596                 module.module_llvm.llmod(),
597                 llvm::LLVMModFlagBehavior::Error,
598                 "LTOPostLink\0".as_ptr().cast(),
599                 1,
600             );
601         }
602         let opt_stage = if thin { llvm::OptStage::ThinLTO } else { llvm::OptStage::FatLTO };
603         let opt_level = config.opt_level.unwrap_or(config::OptLevel::No);
604         write::llvm_optimize(cgcx, diag_handler, module, config, opt_level, opt_stage)?;
605     }
606     debug!("lto done");
607     Ok(())
608 }
609
610 pub struct ModuleBuffer(&'static mut llvm::ModuleBuffer);
611
612 unsafe impl Send for ModuleBuffer {}
613 unsafe impl Sync for ModuleBuffer {}
614
615 impl ModuleBuffer {
616     pub fn new(m: &llvm::Module) -> ModuleBuffer {
617         ModuleBuffer(unsafe { llvm::LLVMRustModuleBufferCreate(m) })
618     }
619 }
620
621 impl ModuleBufferMethods for ModuleBuffer {
622     fn data(&self) -> &[u8] {
623         unsafe {
624             let ptr = llvm::LLVMRustModuleBufferPtr(self.0);
625             let len = llvm::LLVMRustModuleBufferLen(self.0);
626             slice::from_raw_parts(ptr, len)
627         }
628     }
629 }
630
631 impl Drop for ModuleBuffer {
632     fn drop(&mut self) {
633         unsafe {
634             llvm::LLVMRustModuleBufferFree(&mut *(self.0 as *mut _));
635         }
636     }
637 }
638
639 pub struct ThinData(&'static mut llvm::ThinLTOData);
640
641 unsafe impl Send for ThinData {}
642 unsafe impl Sync for ThinData {}
643
644 impl Drop for ThinData {
645     fn drop(&mut self) {
646         unsafe {
647             llvm::LLVMRustFreeThinLTOData(&mut *(self.0 as *mut _));
648         }
649     }
650 }
651
652 pub struct ThinBuffer(&'static mut llvm::ThinLTOBuffer);
653
654 unsafe impl Send for ThinBuffer {}
655 unsafe impl Sync for ThinBuffer {}
656
657 impl ThinBuffer {
658     pub fn new(m: &llvm::Module, is_thin: bool) -> ThinBuffer {
659         unsafe {
660             let buffer = llvm::LLVMRustThinLTOBufferCreate(m, is_thin);
661             ThinBuffer(buffer)
662         }
663     }
664 }
665
666 impl ThinBufferMethods for ThinBuffer {
667     fn data(&self) -> &[u8] {
668         unsafe {
669             let ptr = llvm::LLVMRustThinLTOBufferPtr(self.0) as *const _;
670             let len = llvm::LLVMRustThinLTOBufferLen(self.0);
671             slice::from_raw_parts(ptr, len)
672         }
673     }
674 }
675
676 impl Drop for ThinBuffer {
677     fn drop(&mut self) {
678         unsafe {
679             llvm::LLVMRustThinLTOBufferFree(&mut *(self.0 as *mut _));
680         }
681     }
682 }
683
684 pub unsafe fn optimize_thin_module(
685     thin_module: ThinModule<LlvmCodegenBackend>,
686     cgcx: &CodegenContext<LlvmCodegenBackend>,
687 ) -> Result<ModuleCodegen<ModuleLlvm>, FatalError> {
688     let diag_handler = cgcx.create_diag_handler();
689
690     let module_name = &thin_module.shared.module_names[thin_module.idx];
691     let tm_factory_config = TargetMachineFactoryConfig::new(cgcx, module_name.to_str().unwrap());
692     let tm =
693         (cgcx.tm_factory)(tm_factory_config).map_err(|e| write::llvm_err(&diag_handler, &e))?;
694
695     // Right now the implementation we've got only works over serialized
696     // modules, so we create a fresh new LLVM context and parse the module
697     // into that context. One day, however, we may do this for upstream
698     // crates but for locally codegened modules we may be able to reuse
699     // that LLVM Context and Module.
700     let llcx = llvm::LLVMRustContextCreate(cgcx.fewer_names);
701     let llmod_raw = parse_module(llcx, module_name, thin_module.data(), &diag_handler)? as *const _;
702     let mut module = ModuleCodegen {
703         module_llvm: ModuleLlvm { llmod_raw, llcx, tm },
704         name: thin_module.name().to_string(),
705         kind: ModuleKind::Regular,
706     };
707     {
708         let target = &*module.module_llvm.tm;
709         let llmod = module.module_llvm.llmod();
710         save_temp_bitcode(cgcx, &module, "thin-lto-input");
711
712         // Before we do much else find the "main" `DICompileUnit` that we'll be
713         // using below. If we find more than one though then rustc has changed
714         // in a way we're not ready for, so generate an ICE by returning
715         // an error.
716         let mut cu1 = ptr::null_mut();
717         let mut cu2 = ptr::null_mut();
718         llvm::LLVMRustThinLTOGetDICompileUnit(llmod, &mut cu1, &mut cu2);
719         if !cu2.is_null() {
720             let msg = "multiple source DICompileUnits found";
721             return Err(write::llvm_err(&diag_handler, msg));
722         }
723
724         // Up next comes the per-module local analyses that we do for Thin LTO.
725         // Each of these functions is basically copied from the LLVM
726         // implementation and then tailored to suit this implementation. Ideally
727         // each of these would be supported by upstream LLVM but that's perhaps
728         // a patch for another day!
729         //
730         // You can find some more comments about these functions in the LLVM
731         // bindings we've got (currently `PassWrapper.cpp`)
732         {
733             let _timer =
734                 cgcx.prof.generic_activity_with_arg("LLVM_thin_lto_rename", thin_module.name());
735             if !llvm::LLVMRustPrepareThinLTORename(thin_module.shared.data.0, llmod, target) {
736                 let msg = "failed to prepare thin LTO module";
737                 return Err(write::llvm_err(&diag_handler, msg));
738             }
739             save_temp_bitcode(cgcx, &module, "thin-lto-after-rename");
740         }
741
742         {
743             let _timer = cgcx
744                 .prof
745                 .generic_activity_with_arg("LLVM_thin_lto_resolve_weak", thin_module.name());
746             if !llvm::LLVMRustPrepareThinLTOResolveWeak(thin_module.shared.data.0, llmod) {
747                 let msg = "failed to prepare thin LTO module";
748                 return Err(write::llvm_err(&diag_handler, msg));
749             }
750             save_temp_bitcode(cgcx, &module, "thin-lto-after-resolve");
751         }
752
753         {
754             let _timer = cgcx
755                 .prof
756                 .generic_activity_with_arg("LLVM_thin_lto_internalize", thin_module.name());
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));
760             }
761             save_temp_bitcode(cgcx, &module, "thin-lto-after-internalize");
762         }
763
764         {
765             let _timer =
766                 cgcx.prof.generic_activity_with_arg("LLVM_thin_lto_import", thin_module.name());
767             if !llvm::LLVMRustPrepareThinLTOImport(thin_module.shared.data.0, llmod, target) {
768                 let msg = "failed to prepare thin LTO module";
769                 return Err(write::llvm_err(&diag_handler, msg));
770             }
771             save_temp_bitcode(cgcx, &module, "thin-lto-after-import");
772         }
773
774         // Ok now this is a bit unfortunate. This is also something you won't
775         // find upstream in LLVM's ThinLTO passes! This is a hack for now to
776         // work around bugs in LLVM.
777         //
778         // First discovered in #45511 it was found that as part of ThinLTO
779         // importing passes LLVM will import `DICompileUnit` metadata
780         // information across modules. This means that we'll be working with one
781         // LLVM module that has multiple `DICompileUnit` instances in it (a
782         // bunch of `llvm.dbg.cu` members). Unfortunately there's a number of
783         // bugs in LLVM's backend which generates invalid DWARF in a situation
784         // like this:
785         //
786         //  https://bugs.llvm.org/show_bug.cgi?id=35212
787         //  https://bugs.llvm.org/show_bug.cgi?id=35562
788         //
789         // While the first bug there is fixed the second ended up causing #46346
790         // which was basically a resurgence of #45511 after LLVM's bug 35212 was
791         // fixed.
792         //
793         // This function below is a huge hack around this problem. The function
794         // below is defined in `PassWrapper.cpp` and will basically "merge"
795         // all `DICompileUnit` instances in a module. Basically it'll take all
796         // the objects, rewrite all pointers of `DISubprogram` to point to the
797         // first `DICompileUnit`, and then delete all the other units.
798         //
799         // This is probably mangling to the debug info slightly (but hopefully
800         // not too much) but for now at least gets LLVM to emit valid DWARF (or
801         // so it appears). Hopefully we can remove this once upstream bugs are
802         // fixed in LLVM.
803         {
804             let _timer = cgcx
805                 .prof
806                 .generic_activity_with_arg("LLVM_thin_lto_patch_debuginfo", thin_module.name());
807             llvm::LLVMRustThinLTOPatchDICompileUnit(llmod, cu1);
808             save_temp_bitcode(cgcx, &module, "thin-lto-after-patch");
809         }
810
811         // Alright now that we've done everything related to the ThinLTO
812         // analysis it's time to run some optimizations! Here we use the same
813         // `run_pass_manager` as the "fat" LTO above except that we tell it to
814         // populate a thin-specific pass manager, which presumably LLVM treats a
815         // little differently.
816         {
817             info!("running thin lto passes over {}", module.name);
818             run_pass_manager(cgcx, &diag_handler, &mut module, true)?;
819             save_temp_bitcode(cgcx, &module, "thin-lto-after-pm");
820         }
821     }
822     Ok(module)
823 }
824
825 /// Maps LLVM module identifiers to their corresponding LLVM LTO cache keys
826 #[derive(Debug, Default)]
827 pub struct ThinLTOKeysMap {
828     // key = llvm name of importing module, value = LLVM cache key
829     keys: FxHashMap<String, String>,
830 }
831
832 impl ThinLTOKeysMap {
833     fn save_to_file(&self, path: &Path) -> io::Result<()> {
834         use std::io::Write;
835         let file = File::create(path)?;
836         let mut writer = io::BufWriter::new(file);
837         for (module, key) in &self.keys {
838             writeln!(writer, "{} {}", module, key)?;
839         }
840         Ok(())
841     }
842
843     fn load_from_file(path: &Path) -> io::Result<Self> {
844         use std::io::BufRead;
845         let mut keys = FxHashMap::default();
846         let file = File::open(path)?;
847         for line in io::BufReader::new(file).lines() {
848             let line = line?;
849             let mut split = line.split(' ');
850             let module = split.next().unwrap();
851             let key = split.next().unwrap();
852             assert_eq!(split.next(), None, "Expected two space-separated values, found {:?}", line);
853             keys.insert(module.to_string(), key.to_string());
854         }
855         Ok(Self { keys })
856     }
857
858     fn from_thin_lto_modules(
859         data: &ThinData,
860         modules: &[llvm::ThinLTOModule],
861         names: &[CString],
862     ) -> Self {
863         let keys = iter::zip(modules, names)
864             .map(|(module, name)| {
865                 let key = build_string(|rust_str| unsafe {
866                     llvm::LLVMRustComputeLTOCacheKey(rust_str, module.identifier, data.0);
867                 })
868                 .expect("Invalid ThinLTO module key");
869                 (name.clone().into_string().unwrap(), key)
870             })
871             .collect();
872         Self { keys }
873     }
874 }
875
876 fn module_name_to_str(c_str: &CStr) -> &str {
877     c_str.to_str().unwrap_or_else(|e| {
878         bug!("Encountered non-utf8 LLVM module name `{}`: {}", c_str.to_string_lossy(), e)
879     })
880 }
881
882 pub fn parse_module<'a>(
883     cx: &'a llvm::Context,
884     name: &CStr,
885     data: &[u8],
886     diag_handler: &Handler,
887 ) -> Result<&'a llvm::Module, FatalError> {
888     unsafe {
889         llvm::LLVMRustParseBitcodeForLTO(cx, data.as_ptr(), data.len(), name.as_ptr()).ok_or_else(
890             || {
891                 let msg = "failed to parse bitcode for LTO module";
892                 write::llvm_err(diag_handler, msg)
893             },
894         )
895     }
896 }