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