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