1 use std::collections::hash_map::Entry::*;
4 use rustc::ty::Instance;
7 use rustc::hir::CodegenFnAttrFlags;
8 use rustc::hir::def_id::{CrateNum, DefId, LOCAL_CRATE, CRATE_DEF_INDEX};
9 use rustc_data_structures::fingerprint::Fingerprint;
10 use rustc::middle::exported_symbols::{SymbolExportLevel, ExportedSymbol, metadata_symbol_name};
11 use rustc::session::config;
12 use rustc::ty::{TyCtxt, SymbolName};
13 use rustc::ty::query::Providers;
14 use rustc::ty::subst::SubstsRef;
15 use rustc::util::nodemap::{FxHashMap, DefIdMap};
16 use rustc_data_structures::indexed_vec::IndexVec;
17 use syntax::ext::allocator::ALLOCATOR_METHODS;
19 pub type ExportedSymbols = FxHashMap<
21 Arc<Vec<(String, SymbolExportLevel)>>,
24 pub fn threshold(tcx: TyCtxt<'_>) -> SymbolExportLevel {
25 crates_export_threshold(&tcx.sess.crate_types.borrow())
28 fn crate_export_threshold(crate_type: config::CrateType) -> SymbolExportLevel {
30 config::CrateType::Executable |
31 config::CrateType::Staticlib |
32 config::CrateType::ProcMacro |
33 config::CrateType::Cdylib => SymbolExportLevel::C,
34 config::CrateType::Rlib |
35 config::CrateType::Dylib => SymbolExportLevel::Rust,
39 pub fn crates_export_threshold(crate_types: &[config::CrateType]) -> SymbolExportLevel {
40 if crate_types.iter().any(|&crate_type|
41 crate_export_threshold(crate_type) == SymbolExportLevel::Rust)
43 SymbolExportLevel::Rust
49 fn reachable_non_generics_provider(
52 ) -> &DefIdMap<SymbolExportLevel> {
53 assert_eq!(cnum, LOCAL_CRATE);
55 if !tcx.sess.opts.output_types.should_codegen() {
56 return tcx.arena.alloc(Default::default());
59 // Check to see if this crate is a "special runtime crate". These
60 // crates, implementation details of the standard library, typically
61 // have a bunch of `pub extern` and `#[no_mangle]` functions as the
62 // ABI between them. We don't want their symbols to have a `C`
63 // export level, however, as they're just implementation details.
64 // Down below we'll hardwire all of the symbols to the `Rust` export
66 let special_runtime_crate = tcx.is_panic_runtime(LOCAL_CRATE) ||
67 tcx.is_compiler_builtins(LOCAL_CRATE);
69 let mut reachable_non_generics: DefIdMap<_> = tcx.reachable_set(LOCAL_CRATE).0
71 .filter_map(|&hir_id| {
72 // We want to ignore some FFI functions that are not exposed from
73 // this crate. Reachable FFI functions can be lumped into two
76 // 1. Those that are included statically via a static library
77 // 2. Those included otherwise (e.g., dynamically or via a framework)
79 // Although our LLVM module is not literally emitting code for the
80 // statically included symbols, it's an export of our library which
81 // needs to be passed on to the linker and encoded in the metadata.
83 // As a result, if this id is an FFI item (foreign item) then we only
84 // let it through if it's included statically.
85 match tcx.hir().get(hir_id) {
86 Node::ForeignItem(..) => {
87 let def_id = tcx.hir().local_def_id(hir_id);
88 if tcx.is_statically_included_foreign_item(def_id) {
95 // Only consider nodes that actually have exported symbols.
96 Node::Item(&hir::Item {
97 node: hir::ItemKind::Static(..),
100 Node::Item(&hir::Item {
101 node: hir::ItemKind::Fn(..), ..
103 Node::ImplItem(&hir::ImplItem {
104 kind: hir::ImplItemKind::Method(..),
107 let def_id = tcx.hir().local_def_id(hir_id);
108 let generics = tcx.generics_of(def_id);
109 if !generics.requires_monomorphization(tcx) &&
110 // Functions marked with #[inline] are only ever codegened
111 // with "internal" linkage and are never exported.
112 !Instance::mono(tcx, def_id).def.requires_local(tcx) {
123 let export_level = if special_runtime_crate {
124 let name = tcx.symbol_name(Instance::mono(tcx, def_id)).name.as_str();
125 // We can probably do better here by just ensuring that
126 // it has hidden visibility rather than public
127 // visibility, as this is primarily here to ensure it's
128 // not stripped during LTO.
130 // In general though we won't link right if these
131 // symbols are stripped, and LTO currently strips them.
132 if &*name == "rust_eh_personality" ||
133 &*name == "rust_eh_register_frames" ||
134 &*name == "rust_eh_unregister_frames" {
137 SymbolExportLevel::Rust
140 symbol_export_level(tcx, def_id)
142 debug!("EXPORTED SYMBOL (local): {} ({:?})",
143 tcx.symbol_name(Instance::mono(tcx, def_id)),
145 (def_id, export_level)
149 if let Some(id) = tcx.proc_macro_decls_static(LOCAL_CRATE) {
150 reachable_non_generics.insert(id, SymbolExportLevel::C);
153 if let Some(id) = tcx.plugin_registrar_fn(LOCAL_CRATE) {
154 reachable_non_generics.insert(id, SymbolExportLevel::C);
157 tcx.arena.alloc(reachable_non_generics)
160 fn is_reachable_non_generic_provider_local(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
161 let export_threshold = threshold(tcx);
163 if let Some(&level) = tcx.reachable_non_generics(def_id.krate).get(&def_id) {
164 level.is_below_threshold(export_threshold)
170 fn is_reachable_non_generic_provider_extern(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
171 tcx.reachable_non_generics(def_id.krate).contains_key(&def_id)
174 fn exported_symbols_provider_local(
177 ) -> Arc<Vec<(ExportedSymbol<'_>, SymbolExportLevel)>> {
178 assert_eq!(cnum, LOCAL_CRATE);
180 if !tcx.sess.opts.output_types.should_codegen() {
181 return Arc::new(vec![])
184 let mut symbols: Vec<_> = tcx.reachable_non_generics(LOCAL_CRATE)
186 .map(|(&def_id, &level)| {
187 (ExportedSymbol::NonGeneric(def_id), level)
191 if tcx.entry_fn(LOCAL_CRATE).is_some() {
192 let exported_symbol = ExportedSymbol::NoDefId(SymbolName::new("main"));
194 symbols.push((exported_symbol, SymbolExportLevel::C));
197 if tcx.sess.allocator_kind.get().is_some() {
198 for method in ALLOCATOR_METHODS {
199 let symbol_name = format!("__rust_{}", method.name);
200 let exported_symbol = ExportedSymbol::NoDefId(SymbolName::new(&symbol_name));
202 symbols.push((exported_symbol, SymbolExportLevel::Rust));
206 if tcx.sess.opts.cg.profile_generate.enabled() {
207 // These are weak symbols that point to the profile version and the
208 // profile name, which need to be treated as exported so LTO doesn't nix
210 const PROFILER_WEAK_SYMBOLS: [&str; 2] = [
211 "__llvm_profile_raw_version",
212 "__llvm_profile_filename",
215 symbols.extend(PROFILER_WEAK_SYMBOLS.iter().map(|sym| {
216 let exported_symbol = ExportedSymbol::NoDefId(SymbolName::new(sym));
217 (exported_symbol, SymbolExportLevel::C)
221 if tcx.sess.crate_types.borrow().contains(&config::CrateType::Dylib) {
222 let symbol_name = metadata_symbol_name(tcx);
223 let exported_symbol = ExportedSymbol::NoDefId(SymbolName::new(&symbol_name));
225 symbols.push((exported_symbol, SymbolExportLevel::Rust));
228 if tcx.sess.opts.share_generics() && tcx.local_crate_exports_generics() {
229 use rustc::mir::mono::{Linkage, Visibility, MonoItem};
230 use rustc::ty::InstanceDef;
232 // Normally, we require that shared monomorphizations are not hidden,
233 // because if we want to re-use a monomorphization from a Rust dylib, it
234 // needs to be exported.
235 // However, on platforms that don't allow for Rust dylibs, having
236 // external linkage is enough for monomorphization to be linked to.
237 let need_visibility = tcx.sess.target.target.options.dynamic_linking &&
238 !tcx.sess.target.target.options.only_cdylib;
240 let (_, cgus) = tcx.collect_and_partition_mono_items(LOCAL_CRATE);
242 for (mono_item, &(linkage, visibility)) in cgus.iter()
243 .flat_map(|cgu| cgu.items().iter()) {
244 if linkage != Linkage::External {
245 // We can only re-use things with external linkage, otherwise
246 // we'll get a linker error
250 if need_visibility && visibility == Visibility::Hidden {
251 // If we potentially share things from Rust dylibs, they must
256 if let &MonoItem::Fn(Instance {
257 def: InstanceDef::Item(def_id),
260 if substs.non_erasable_generics().next().is_some() {
261 symbols.push((ExportedSymbol::Generic(def_id, substs),
262 SymbolExportLevel::Rust));
268 // Sort so we get a stable incr. comp. hash.
269 symbols.sort_unstable_by(|&(ref symbol1, ..), &(ref symbol2, ..)| {
270 symbol1.compare_stable(tcx, symbol2)
276 fn upstream_monomorphizations_provider(
279 ) -> &DefIdMap<FxHashMap<SubstsRef<'_>, CrateNum>> {
280 debug_assert!(cnum == LOCAL_CRATE);
282 let cnums = tcx.all_crate_nums(LOCAL_CRATE);
284 let mut instances: DefIdMap<FxHashMap<_, _>> = Default::default();
286 let cnum_stable_ids: IndexVec<CrateNum, Fingerprint> = {
287 let mut cnum_stable_ids = IndexVec::from_elem_n(Fingerprint::ZERO,
290 for &cnum in cnums.iter() {
291 cnum_stable_ids[cnum] = tcx.def_path_hash(DefId {
293 index: CRATE_DEF_INDEX,
300 for &cnum in cnums.iter() {
301 for (exported_symbol, _) in tcx.exported_symbols(cnum).iter() {
302 if let &ExportedSymbol::Generic(def_id, substs) = exported_symbol {
303 let substs_map = instances.entry(def_id).or_default();
305 match substs_map.entry(substs) {
307 // If there are multiple monomorphizations available,
308 // we select one deterministically.
309 let other_cnum = *e.get();
310 if cnum_stable_ids[other_cnum] > cnum_stable_ids[cnum] {
322 tcx.arena.alloc(instances)
325 fn upstream_monomorphizations_for_provider(
328 ) -> Option<&FxHashMap<SubstsRef<'_>, CrateNum>> {
329 debug_assert!(!def_id.is_local());
330 tcx.upstream_monomorphizations(LOCAL_CRATE).get(&def_id)
333 fn is_unreachable_local_definition_provider(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
334 if let Some(hir_id) = tcx.hir().as_local_hir_id(def_id) {
335 !tcx.reachable_set(LOCAL_CRATE).0.contains(&hir_id)
337 bug!("is_unreachable_local_definition called with non-local DefId: {:?}",
342 pub fn provide(providers: &mut Providers<'_>) {
343 providers.reachable_non_generics = reachable_non_generics_provider;
344 providers.is_reachable_non_generic = is_reachable_non_generic_provider_local;
345 providers.exported_symbols = exported_symbols_provider_local;
346 providers.upstream_monomorphizations = upstream_monomorphizations_provider;
347 providers.is_unreachable_local_definition = is_unreachable_local_definition_provider;
350 pub fn provide_extern(providers: &mut Providers<'_>) {
351 providers.is_reachable_non_generic = is_reachable_non_generic_provider_extern;
352 providers.upstream_monomorphizations_for = upstream_monomorphizations_for_provider;
355 fn symbol_export_level(tcx: TyCtxt<'_>, sym_def_id: DefId) -> SymbolExportLevel {
356 // We export anything that's not mangled at the "C" layer as it probably has
357 // to do with ABI concerns. We do not, however, apply such treatment to
358 // special symbols in the standard library for various plumbing between
359 // core/std/allocators/etc. For example symbols used to hook up allocation
360 // are not considered for export
361 let codegen_fn_attrs = tcx.codegen_fn_attrs(sym_def_id);
362 let is_extern = codegen_fn_attrs.contains_extern_indicator();
364 codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL);
366 if is_extern && !std_internal {
367 // Emscripten cannot export statics, so reduce their export level here
368 if tcx.sess.target.target.options.is_like_emscripten {
369 if let Some(Node::Item(&hir::Item {
370 node: hir::ItemKind::Static(..),
372 })) = tcx.hir().get_if_local(sym_def_id) {
373 return SymbolExportLevel::Rust;
379 SymbolExportLevel::Rust