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