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