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