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