]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_ssa/back/symbol_export.rs
Auto merge of #68474 - tmandry:rollup-6gmbet6, r=tmandry
[rust.git] / src / librustc_codegen_ssa / back / symbol_export.rs
1 use std::collections::hash_map::Entry::*;
2 use std::sync::Arc;
3
4 use rustc::middle::codegen_fn_attrs::CodegenFnAttrFlags;
5 use rustc::middle::exported_symbols::{metadata_symbol_name, ExportedSymbol, SymbolExportLevel};
6 use rustc::session::config::{self, Sanitizer};
7 use rustc::ty::query::Providers;
8 use rustc::ty::subst::SubstsRef;
9 use rustc::ty::Instance;
10 use rustc::ty::{SymbolName, TyCtxt};
11 use rustc_codegen_utils::symbol_names;
12 use rustc_data_structures::fingerprint::Fingerprint;
13 use rustc_data_structures::fx::FxHashMap;
14 use rustc_hir as hir;
15 use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, CRATE_DEF_INDEX, LOCAL_CRATE};
16 use rustc_hir::Node;
17 use rustc_index::vec::IndexVec;
18 use syntax::expand::allocator::ALLOCATOR_METHODS;
19
20 pub type ExportedSymbols = FxHashMap<CrateNum, Arc<Vec<(String, SymbolExportLevel)>>>;
21
22 pub fn threshold(tcx: TyCtxt<'_>) -> SymbolExportLevel {
23     crates_export_threshold(&tcx.sess.crate_types.borrow())
24 }
25
26 fn crate_export_threshold(crate_type: config::CrateType) -> SymbolExportLevel {
27     match crate_type {
28         config::CrateType::Executable
29         | config::CrateType::Staticlib
30         | config::CrateType::ProcMacro
31         | config::CrateType::Cdylib => SymbolExportLevel::C,
32         config::CrateType::Rlib | config::CrateType::Dylib => SymbolExportLevel::Rust,
33     }
34 }
35
36 pub fn crates_export_threshold(crate_types: &[config::CrateType]) -> SymbolExportLevel {
37     if crate_types
38         .iter()
39         .any(|&crate_type| crate_export_threshold(crate_type) == SymbolExportLevel::Rust)
40     {
41         SymbolExportLevel::Rust
42     } else {
43         SymbolExportLevel::C
44     }
45 }
46
47 fn reachable_non_generics_provider(
48     tcx: TyCtxt<'_>,
49     cnum: CrateNum,
50 ) -> &DefIdMap<SymbolExportLevel> {
51     assert_eq!(cnum, LOCAL_CRATE);
52
53     if !tcx.sess.opts.output_types.should_codegen() {
54         return tcx.arena.alloc(Default::default());
55     }
56
57     // Check to see if this crate is a "special runtime crate". These
58     // crates, implementation details of the standard library, typically
59     // have a bunch of `pub extern` and `#[no_mangle]` functions as the
60     // ABI between them. We don't want their symbols to have a `C`
61     // export level, however, as they're just implementation details.
62     // Down below we'll hardwire all of the symbols to the `Rust` export
63     // level instead.
64     let special_runtime_crate =
65         tcx.is_panic_runtime(LOCAL_CRATE) || tcx.is_compiler_builtins(LOCAL_CRATE);
66
67     let mut reachable_non_generics: DefIdMap<_> = tcx
68         .reachable_set(LOCAL_CRATE)
69         .iter()
70         .filter_map(|&hir_id| {
71             // We want to ignore some FFI functions that are not exposed from
72             // this crate. Reachable FFI functions can be lumped into two
73             // categories:
74             //
75             // 1. Those that are included statically via a static library
76             // 2. Those included otherwise (e.g., dynamically or via a framework)
77             //
78             // Although our LLVM module is not literally emitting code for the
79             // statically included symbols, it's an export of our library which
80             // needs to be passed on to the linker and encoded in the metadata.
81             //
82             // As a result, if this id is an FFI item (foreign item) then we only
83             // let it through if it's included statically.
84             match tcx.hir().get(hir_id) {
85                 Node::ForeignItem(..) => {
86                     let def_id = tcx.hir().local_def_id(hir_id);
87                     tcx.is_statically_included_foreign_item(def_id).then_some(def_id)
88                 }
89
90                 // Only consider nodes that actually have exported symbols.
91                 Node::Item(&hir::Item { kind: hir::ItemKind::Static(..), .. })
92                 | Node::Item(&hir::Item { kind: hir::ItemKind::Fn(..), .. })
93                 | Node::ImplItem(&hir::ImplItem { kind: hir::ImplItemKind::Method(..), .. }) => {
94                     let def_id = tcx.hir().local_def_id(hir_id);
95                     let generics = tcx.generics_of(def_id);
96                     if !generics.requires_monomorphization(tcx) &&
97                         // Functions marked with #[inline] are only ever codegened
98                         // with "internal" linkage and are never exported.
99                         !Instance::mono(tcx, def_id).def.requires_local(tcx)
100                     {
101                         Some(def_id)
102                     } else {
103                         None
104                     }
105                 }
106
107                 _ => None,
108             }
109         })
110         .map(|def_id| {
111             let export_level = if special_runtime_crate {
112                 let name = tcx.symbol_name(Instance::mono(tcx, def_id)).name.as_str();
113                 // We can probably do better here by just ensuring that
114                 // it has hidden visibility rather than public
115                 // visibility, as this is primarily here to ensure it's
116                 // not stripped during LTO.
117                 //
118                 // In general though we won't link right if these
119                 // symbols are stripped, and LTO currently strips them.
120                 if name == "rust_eh_personality"
121                     || name == "rust_eh_register_frames"
122                     || name == "rust_eh_unregister_frames"
123                 {
124                     SymbolExportLevel::C
125                 } else {
126                     SymbolExportLevel::Rust
127                 }
128             } else {
129                 symbol_export_level(tcx, def_id)
130             };
131             debug!(
132                 "EXPORTED SYMBOL (local): {} ({:?})",
133                 tcx.symbol_name(Instance::mono(tcx, def_id)),
134                 export_level
135             );
136             (def_id, export_level)
137         })
138         .collect();
139
140     if let Some(id) = tcx.proc_macro_decls_static(LOCAL_CRATE) {
141         reachable_non_generics.insert(id, SymbolExportLevel::C);
142     }
143
144     if let Some(id) = tcx.plugin_registrar_fn(LOCAL_CRATE) {
145         reachable_non_generics.insert(id, SymbolExportLevel::C);
146     }
147
148     tcx.arena.alloc(reachable_non_generics)
149 }
150
151 fn is_reachable_non_generic_provider_local(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
152     let export_threshold = threshold(tcx);
153
154     if let Some(&level) = tcx.reachable_non_generics(def_id.krate).get(&def_id) {
155         level.is_below_threshold(export_threshold)
156     } else {
157         false
158     }
159 }
160
161 fn is_reachable_non_generic_provider_extern(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
162     tcx.reachable_non_generics(def_id.krate).contains_key(&def_id)
163 }
164
165 fn exported_symbols_provider_local(
166     tcx: TyCtxt<'_>,
167     cnum: CrateNum,
168 ) -> Arc<Vec<(ExportedSymbol<'_>, SymbolExportLevel)>> {
169     assert_eq!(cnum, LOCAL_CRATE);
170
171     if !tcx.sess.opts.output_types.should_codegen() {
172         return Arc::new(vec![]);
173     }
174
175     let mut symbols: Vec<_> = tcx
176         .reachable_non_generics(LOCAL_CRATE)
177         .iter()
178         .map(|(&def_id, &level)| (ExportedSymbol::NonGeneric(def_id), level))
179         .collect();
180
181     if tcx.entry_fn(LOCAL_CRATE).is_some() {
182         let exported_symbol = ExportedSymbol::NoDefId(SymbolName::new("main"));
183
184         symbols.push((exported_symbol, SymbolExportLevel::C));
185     }
186
187     if tcx.allocator_kind().is_some() {
188         for method in ALLOCATOR_METHODS {
189             let symbol_name = format!("__rust_{}", method.name);
190             let exported_symbol = ExportedSymbol::NoDefId(SymbolName::new(&symbol_name));
191
192             symbols.push((exported_symbol, SymbolExportLevel::Rust));
193         }
194     }
195
196     if tcx.sess.opts.cg.profile_generate.enabled() {
197         // These are weak symbols that point to the profile version and the
198         // profile name, which need to be treated as exported so LTO doesn't nix
199         // them.
200         const PROFILER_WEAK_SYMBOLS: [&str; 2] =
201             ["__llvm_profile_raw_version", "__llvm_profile_filename"];
202
203         symbols.extend(PROFILER_WEAK_SYMBOLS.iter().map(|sym| {
204             let exported_symbol = ExportedSymbol::NoDefId(SymbolName::new(sym));
205             (exported_symbol, SymbolExportLevel::C)
206         }));
207     }
208
209     if let Some(Sanitizer::Memory) = tcx.sess.opts.debugging_opts.sanitizer {
210         // Similar to profiling, preserve weak msan symbol during LTO.
211         const MSAN_WEAK_SYMBOLS: [&str; 2] = ["__msan_track_origins", "__msan_keep_going"];
212
213         symbols.extend(MSAN_WEAK_SYMBOLS.iter().map(|sym| {
214             let exported_symbol = ExportedSymbol::NoDefId(SymbolName::new(sym));
215             (exported_symbol, SymbolExportLevel::C)
216         }));
217     }
218
219     if tcx.sess.crate_types.borrow().contains(&config::CrateType::Dylib) {
220         let symbol_name = metadata_symbol_name(tcx);
221         let exported_symbol = ExportedSymbol::NoDefId(SymbolName::new(&symbol_name));
222
223         symbols.push((exported_symbol, SymbolExportLevel::Rust));
224     }
225
226     if tcx.sess.opts.share_generics() && tcx.local_crate_exports_generics() {
227         use rustc::mir::mono::{Linkage, MonoItem, Visibility};
228         use rustc::ty::InstanceDef;
229
230         // Normally, we require that shared monomorphizations are not hidden,
231         // because if we want to re-use a monomorphization from a Rust dylib, it
232         // needs to be exported.
233         // However, on platforms that don't allow for Rust dylibs, having
234         // external linkage is enough for monomorphization to be linked to.
235         let need_visibility = tcx.sess.target.target.options.dynamic_linking
236             && !tcx.sess.target.target.options.only_cdylib;
237
238         let (_, cgus) = tcx.collect_and_partition_mono_items(LOCAL_CRATE);
239
240         for (mono_item, &(linkage, visibility)) in cgus.iter().flat_map(|cgu| cgu.items().iter()) {
241             if linkage != Linkage::External {
242                 // We can only re-use things with external linkage, otherwise
243                 // we'll get a linker error
244                 continue;
245             }
246
247             if need_visibility && visibility == Visibility::Hidden {
248                 // If we potentially share things from Rust dylibs, they must
249                 // not be hidden
250                 continue;
251             }
252
253             if let &MonoItem::Fn(Instance { def: InstanceDef::Item(def_id), substs }) = mono_item {
254                 if substs.non_erasable_generics().next().is_some() {
255                     symbols
256                         .push((ExportedSymbol::Generic(def_id, substs), SymbolExportLevel::Rust));
257                 }
258             }
259         }
260     }
261
262     // Sort so we get a stable incr. comp. hash.
263     symbols.sort_unstable_by(|&(ref symbol1, ..), &(ref symbol2, ..)| {
264         symbol1.compare_stable(tcx, symbol2)
265     });
266
267     Arc::new(symbols)
268 }
269
270 fn upstream_monomorphizations_provider(
271     tcx: TyCtxt<'_>,
272     cnum: CrateNum,
273 ) -> &DefIdMap<FxHashMap<SubstsRef<'_>, CrateNum>> {
274     debug_assert!(cnum == LOCAL_CRATE);
275
276     let cnums = tcx.all_crate_nums(LOCAL_CRATE);
277
278     let mut instances: DefIdMap<FxHashMap<_, _>> = Default::default();
279
280     let cnum_stable_ids: IndexVec<CrateNum, Fingerprint> = {
281         let mut cnum_stable_ids = IndexVec::from_elem_n(Fingerprint::ZERO, cnums.len() + 1);
282
283         for &cnum in cnums.iter() {
284             cnum_stable_ids[cnum] =
285                 tcx.def_path_hash(DefId { krate: cnum, index: CRATE_DEF_INDEX }).0;
286         }
287
288         cnum_stable_ids
289     };
290
291     for &cnum in cnums.iter() {
292         for (exported_symbol, _) in tcx.exported_symbols(cnum).iter() {
293             if let &ExportedSymbol::Generic(def_id, substs) = exported_symbol {
294                 let substs_map = instances.entry(def_id).or_default();
295
296                 match substs_map.entry(substs) {
297                     Occupied(mut e) => {
298                         // If there are multiple monomorphizations available,
299                         // we select one deterministically.
300                         let other_cnum = *e.get();
301                         if cnum_stable_ids[other_cnum] > cnum_stable_ids[cnum] {
302                             e.insert(cnum);
303                         }
304                     }
305                     Vacant(e) => {
306                         e.insert(cnum);
307                     }
308                 }
309             }
310         }
311     }
312
313     tcx.arena.alloc(instances)
314 }
315
316 fn upstream_monomorphizations_for_provider(
317     tcx: TyCtxt<'_>,
318     def_id: DefId,
319 ) -> Option<&FxHashMap<SubstsRef<'_>, CrateNum>> {
320     debug_assert!(!def_id.is_local());
321     tcx.upstream_monomorphizations(LOCAL_CRATE).get(&def_id)
322 }
323
324 fn is_unreachable_local_definition_provider(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
325     if let Some(hir_id) = tcx.hir().as_local_hir_id(def_id) {
326         !tcx.reachable_set(LOCAL_CRATE).contains(&hir_id)
327     } else {
328         bug!("is_unreachable_local_definition called with non-local DefId: {:?}", def_id)
329     }
330 }
331
332 pub fn provide(providers: &mut Providers<'_>) {
333     providers.reachable_non_generics = reachable_non_generics_provider;
334     providers.is_reachable_non_generic = is_reachable_non_generic_provider_local;
335     providers.exported_symbols = exported_symbols_provider_local;
336     providers.upstream_monomorphizations = upstream_monomorphizations_provider;
337     providers.is_unreachable_local_definition = is_unreachable_local_definition_provider;
338 }
339
340 pub fn provide_extern(providers: &mut Providers<'_>) {
341     providers.is_reachable_non_generic = is_reachable_non_generic_provider_extern;
342     providers.upstream_monomorphizations_for = upstream_monomorphizations_for_provider;
343 }
344
345 fn symbol_export_level(tcx: TyCtxt<'_>, sym_def_id: DefId) -> SymbolExportLevel {
346     // We export anything that's not mangled at the "C" layer as it probably has
347     // to do with ABI concerns. We do not, however, apply such treatment to
348     // special symbols in the standard library for various plumbing between
349     // core/std/allocators/etc. For example symbols used to hook up allocation
350     // are not considered for export
351     let codegen_fn_attrs = tcx.codegen_fn_attrs(sym_def_id);
352     let is_extern = codegen_fn_attrs.contains_extern_indicator();
353     let std_internal =
354         codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL);
355
356     if is_extern && !std_internal {
357         let target = &tcx.sess.target.target.llvm_target;
358         // WebAssembly cannot export data symbols, so reduce their export level
359         if target.contains("emscripten") {
360             if let Some(Node::Item(&hir::Item { kind: hir::ItemKind::Static(..), .. })) =
361                 tcx.hir().get_if_local(sym_def_id)
362             {
363                 return SymbolExportLevel::Rust;
364             }
365         }
366
367         SymbolExportLevel::C
368     } else {
369         SymbolExportLevel::Rust
370     }
371 }
372
373 /// This is the symbol name of the given instance instantiated in a specific crate.
374 pub fn symbol_name_for_instance_in_crate<'tcx>(
375     tcx: TyCtxt<'tcx>,
376     symbol: ExportedSymbol<'tcx>,
377     instantiating_crate: CrateNum,
378 ) -> String {
379     // If this is something instantiated in the local crate then we might
380     // already have cached the name as a query result.
381     if instantiating_crate == LOCAL_CRATE {
382         return symbol.symbol_name_for_local_instance(tcx).to_string();
383     }
384
385     // This is something instantiated in an upstream crate, so we have to use
386     // the slower (because uncached) version of computing the symbol name.
387     match symbol {
388         ExportedSymbol::NonGeneric(def_id) => symbol_names::symbol_name_for_instance_in_crate(
389             tcx,
390             Instance::mono(tcx, def_id),
391             instantiating_crate,
392         ),
393         ExportedSymbol::Generic(def_id, substs) => symbol_names::symbol_name_for_instance_in_crate(
394             tcx,
395             Instance::new(def_id, substs),
396             instantiating_crate,
397         ),
398         ExportedSymbol::NoDefId(symbol_name) => symbol_name.to_string(),
399     }
400 }