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