]> git.lizzy.rs Git - rust.git/blob - src/librustc_passes/reachable.rs
Rollup merge of #67719 - jumbatm:add-self-to-mailmap, r=Mark-Simulacrum
[rust.git] / src / librustc_passes / reachable.rs
1 // Finds items that are externally reachable, to determine which items
2 // need to have their metadata (and possibly their AST) serialized.
3 // All items that can be referred to through an exported name are
4 // reachable, and when a reachable thing is inline or generic, it
5 // makes all other generics or inline functions that it references
6 // reachable as well.
7
8 use rustc::hir::def::{DefKind, Res};
9 use rustc::hir::def_id::{CrateNum, DefId};
10 use rustc::hir::Node;
11 use rustc::hir::{CodegenFnAttrFlags, CodegenFnAttrs};
12 use rustc::middle::privacy;
13 use rustc::session::config;
14 use rustc::ty::query::Providers;
15 use rustc::ty::{self, TyCtxt};
16 use rustc::util::nodemap::{FxHashSet, HirIdSet};
17 use rustc_data_structures::sync::Lrc;
18
19 use rustc::hir;
20 use rustc::hir::def_id::LOCAL_CRATE;
21 use rustc::hir::intravisit;
22 use rustc::hir::intravisit::{NestedVisitorMap, Visitor};
23 use rustc::hir::itemlikevisit::ItemLikeVisitor;
24 use rustc_target::spec::abi::Abi;
25
26 // Returns true if the given item must be inlined because it may be
27 // monomorphized or it was marked with `#[inline]`. This will only return
28 // true for functions.
29 fn item_might_be_inlined(tcx: TyCtxt<'tcx>, item: &hir::Item<'_>, attrs: CodegenFnAttrs) -> bool {
30     if attrs.requests_inline() {
31         return true;
32     }
33
34     match item.kind {
35         hir::ItemKind::Fn(ref sig, ..) if sig.header.is_const() => {
36             return true;
37         }
38         hir::ItemKind::Impl(..) | hir::ItemKind::Fn(..) => {
39             let generics = tcx.generics_of(tcx.hir().local_def_id(item.hir_id));
40             generics.requires_monomorphization(tcx)
41         }
42         _ => false,
43     }
44 }
45
46 fn method_might_be_inlined(
47     tcx: TyCtxt<'_>,
48     impl_item: &hir::ImplItem<'_>,
49     impl_src: DefId,
50 ) -> bool {
51     let codegen_fn_attrs = tcx.codegen_fn_attrs(impl_item.hir_id.owner_def_id());
52     let generics = tcx.generics_of(tcx.hir().local_def_id(impl_item.hir_id));
53     if codegen_fn_attrs.requests_inline() || generics.requires_monomorphization(tcx) {
54         return true;
55     }
56     if let hir::ImplItemKind::Method(method_sig, _) = &impl_item.kind {
57         if method_sig.header.is_const() {
58             return true;
59         }
60     }
61     if let Some(impl_hir_id) = tcx.hir().as_local_hir_id(impl_src) {
62         match tcx.hir().find(impl_hir_id) {
63             Some(Node::Item(item)) => item_might_be_inlined(tcx, &item, codegen_fn_attrs),
64             Some(..) | None => span_bug!(impl_item.span, "impl did is not an item"),
65         }
66     } else {
67         span_bug!(impl_item.span, "found a foreign impl as a parent of a local method")
68     }
69 }
70
71 // Information needed while computing reachability.
72 struct ReachableContext<'a, 'tcx> {
73     // The type context.
74     tcx: TyCtxt<'tcx>,
75     tables: &'a ty::TypeckTables<'tcx>,
76     // The set of items which must be exported in the linkage sense.
77     reachable_symbols: HirIdSet,
78     // A worklist of item IDs. Each item ID in this worklist will be inlined
79     // and will be scanned for further references.
80     worklist: Vec<hir::HirId>,
81     // Whether any output of this compilation is a library
82     any_library: bool,
83 }
84
85 impl<'a, 'tcx> Visitor<'tcx> for ReachableContext<'a, 'tcx> {
86     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
87         NestedVisitorMap::None
88     }
89
90     fn visit_nested_body(&mut self, body: hir::BodyId) {
91         let old_tables = self.tables;
92         self.tables = self.tcx.body_tables(body);
93         let body = self.tcx.hir().body(body);
94         self.visit_body(body);
95         self.tables = old_tables;
96     }
97
98     fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
99         let res = match expr.kind {
100             hir::ExprKind::Path(ref qpath) => Some(self.tables.qpath_res(qpath, expr.hir_id)),
101             hir::ExprKind::MethodCall(..) => self
102                 .tables
103                 .type_dependent_def(expr.hir_id)
104                 .map(|(kind, def_id)| Res::Def(kind, def_id)),
105             _ => None,
106         };
107
108         match res {
109             Some(Res::Local(hir_id)) => {
110                 self.reachable_symbols.insert(hir_id);
111             }
112             Some(res) => {
113                 if let Some((hir_id, def_id)) = res.opt_def_id().and_then(|def_id| {
114                     self.tcx.hir().as_local_hir_id(def_id).map(|hir_id| (hir_id, def_id))
115                 }) {
116                     if self.def_id_represents_local_inlined_item(def_id) {
117                         self.worklist.push(hir_id);
118                     } else {
119                         match res {
120                             // If this path leads to a constant, then we need to
121                             // recurse into the constant to continue finding
122                             // items that are reachable.
123                             Res::Def(DefKind::Const, _) | Res::Def(DefKind::AssocConst, _) => {
124                                 self.worklist.push(hir_id);
125                             }
126
127                             // If this wasn't a static, then the destination is
128                             // surely reachable.
129                             _ => {
130                                 self.reachable_symbols.insert(hir_id);
131                             }
132                         }
133                     }
134                 }
135             }
136             _ => {}
137         }
138
139         intravisit::walk_expr(self, expr)
140     }
141 }
142
143 impl<'a, 'tcx> ReachableContext<'a, 'tcx> {
144     // Returns true if the given def ID represents a local item that is
145     // eligible for inlining and false otherwise.
146     fn def_id_represents_local_inlined_item(&self, def_id: DefId) -> bool {
147         let hir_id = match self.tcx.hir().as_local_hir_id(def_id) {
148             Some(hir_id) => hir_id,
149             None => {
150                 return false;
151             }
152         };
153
154         match self.tcx.hir().find(hir_id) {
155             Some(Node::Item(item)) => match item.kind {
156                 hir::ItemKind::Fn(..) => {
157                     item_might_be_inlined(self.tcx, &item, self.tcx.codegen_fn_attrs(def_id))
158                 }
159                 _ => false,
160             },
161             Some(Node::TraitItem(trait_method)) => match trait_method.kind {
162                 hir::TraitItemKind::Const(_, ref default) => default.is_some(),
163                 hir::TraitItemKind::Method(_, hir::TraitMethod::Provided(_)) => true,
164                 hir::TraitItemKind::Method(_, hir::TraitMethod::Required(_))
165                 | hir::TraitItemKind::Type(..) => false,
166             },
167             Some(Node::ImplItem(impl_item)) => {
168                 match impl_item.kind {
169                     hir::ImplItemKind::Const(..) => true,
170                     hir::ImplItemKind::Method(..) => {
171                         let attrs = self.tcx.codegen_fn_attrs(def_id);
172                         let generics = self.tcx.generics_of(def_id);
173                         if generics.requires_monomorphization(self.tcx) || attrs.requests_inline() {
174                             true
175                         } else {
176                             let impl_did = self.tcx.hir().get_parent_did(hir_id);
177                             // Check the impl. If the generics on the self
178                             // type of the impl require inlining, this method
179                             // does too.
180                             let impl_hir_id = self.tcx.hir().as_local_hir_id(impl_did).unwrap();
181                             match self.tcx.hir().expect_item(impl_hir_id).kind {
182                                 hir::ItemKind::Impl(..) => {
183                                     let generics = self.tcx.generics_of(impl_did);
184                                     generics.requires_monomorphization(self.tcx)
185                                 }
186                                 _ => false,
187                             }
188                         }
189                     }
190                     hir::ImplItemKind::OpaqueTy(..) | hir::ImplItemKind::TyAlias(_) => false,
191                 }
192             }
193             Some(_) => false,
194             None => false, // This will happen for default methods.
195         }
196     }
197
198     // Step 2: Mark all symbols that the symbols on the worklist touch.
199     fn propagate(&mut self) {
200         let mut scanned = FxHashSet::default();
201         while let Some(search_item) = self.worklist.pop() {
202             if !scanned.insert(search_item) {
203                 continue;
204             }
205
206             if let Some(ref item) = self.tcx.hir().find(search_item) {
207                 self.propagate_node(item, search_item);
208             }
209         }
210     }
211
212     fn propagate_node(&mut self, node: &Node<'tcx>, search_item: hir::HirId) {
213         if !self.any_library {
214             // If we are building an executable, only explicitly extern
215             // types need to be exported.
216             if let Node::Item(item) = *node {
217                 let reachable = if let hir::ItemKind::Fn(ref sig, ..) = item.kind {
218                     sig.header.abi != Abi::Rust
219                 } else {
220                     false
221                 };
222                 let def_id = self.tcx.hir().local_def_id(item.hir_id);
223                 let codegen_attrs = self.tcx.codegen_fn_attrs(def_id);
224                 let is_extern = codegen_attrs.contains_extern_indicator();
225                 let std_internal =
226                     codegen_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL);
227                 if reachable || is_extern || std_internal {
228                     self.reachable_symbols.insert(search_item);
229                 }
230             }
231         } else {
232             // If we are building a library, then reachable symbols will
233             // continue to participate in linkage after this product is
234             // produced. In this case, we traverse the ast node, recursing on
235             // all reachable nodes from this one.
236             self.reachable_symbols.insert(search_item);
237         }
238
239         match *node {
240             Node::Item(item) => {
241                 match item.kind {
242                     hir::ItemKind::Fn(.., body) => {
243                         let def_id = self.tcx.hir().local_def_id(item.hir_id);
244                         if item_might_be_inlined(self.tcx, &item, self.tcx.codegen_fn_attrs(def_id))
245                         {
246                             self.visit_nested_body(body);
247                         }
248                     }
249
250                     // Reachable constants will be inlined into other crates
251                     // unconditionally, so we need to make sure that their
252                     // contents are also reachable.
253                     hir::ItemKind::Const(_, init) => {
254                         self.visit_nested_body(init);
255                     }
256
257                     // These are normal, nothing reachable about these
258                     // inherently and their children are already in the
259                     // worklist, as determined by the privacy pass
260                     hir::ItemKind::ExternCrate(_)
261                     | hir::ItemKind::Use(..)
262                     | hir::ItemKind::OpaqueTy(..)
263                     | hir::ItemKind::TyAlias(..)
264                     | hir::ItemKind::Static(..)
265                     | hir::ItemKind::Mod(..)
266                     | hir::ItemKind::ForeignMod(..)
267                     | hir::ItemKind::Impl(..)
268                     | hir::ItemKind::Trait(..)
269                     | hir::ItemKind::TraitAlias(..)
270                     | hir::ItemKind::Struct(..)
271                     | hir::ItemKind::Enum(..)
272                     | hir::ItemKind::Union(..)
273                     | hir::ItemKind::GlobalAsm(..) => {}
274                 }
275             }
276             Node::TraitItem(trait_method) => {
277                 match trait_method.kind {
278                     hir::TraitItemKind::Const(_, None)
279                     | hir::TraitItemKind::Method(_, hir::TraitMethod::Required(_)) => {
280                         // Keep going, nothing to get exported
281                     }
282                     hir::TraitItemKind::Const(_, Some(body_id))
283                     | hir::TraitItemKind::Method(_, hir::TraitMethod::Provided(body_id)) => {
284                         self.visit_nested_body(body_id);
285                     }
286                     hir::TraitItemKind::Type(..) => {}
287                 }
288             }
289             Node::ImplItem(impl_item) => match impl_item.kind {
290                 hir::ImplItemKind::Const(_, body) => {
291                     self.visit_nested_body(body);
292                 }
293                 hir::ImplItemKind::Method(_, body) => {
294                     let did = self.tcx.hir().get_parent_did(search_item);
295                     if method_might_be_inlined(self.tcx, impl_item, did) {
296                         self.visit_nested_body(body)
297                     }
298                 }
299                 hir::ImplItemKind::OpaqueTy(..) | hir::ImplItemKind::TyAlias(_) => {}
300             },
301             Node::Expr(&hir::Expr { kind: hir::ExprKind::Closure(.., body, _, _), .. }) => {
302                 self.visit_nested_body(body);
303             }
304             // Nothing to recurse on for these
305             Node::ForeignItem(_)
306             | Node::Variant(_)
307             | Node::Ctor(..)
308             | Node::Field(_)
309             | Node::Ty(_)
310             | Node::MacroDef(_) => {}
311             _ => {
312                 bug!(
313                     "found unexpected node kind in worklist: {} ({:?})",
314                     self.tcx.hir().node_to_string(search_item),
315                     node,
316                 );
317             }
318         }
319     }
320 }
321
322 // Some methods from non-exported (completely private) trait impls still have to be
323 // reachable if they are called from inlinable code. Generally, it's not known until
324 // monomorphization if a specific trait impl item can be reachable or not. So, we
325 // conservatively mark all of them as reachable.
326 // FIXME: One possible strategy for pruning the reachable set is to avoid marking impl
327 // items of non-exported traits (or maybe all local traits?) unless their respective
328 // trait items are used from inlinable code through method call syntax or UFCS, or their
329 // trait is a lang item.
330 struct CollectPrivateImplItemsVisitor<'a, 'tcx> {
331     tcx: TyCtxt<'tcx>,
332     access_levels: &'a privacy::AccessLevels,
333     worklist: &'a mut Vec<hir::HirId>,
334 }
335
336 impl<'a, 'tcx> ItemLikeVisitor<'tcx> for CollectPrivateImplItemsVisitor<'a, 'tcx> {
337     fn visit_item(&mut self, item: &hir::Item<'_>) {
338         // Anything which has custom linkage gets thrown on the worklist no
339         // matter where it is in the crate, along with "special std symbols"
340         // which are currently akin to allocator symbols.
341         let def_id = self.tcx.hir().local_def_id(item.hir_id);
342         let codegen_attrs = self.tcx.codegen_fn_attrs(def_id);
343         if codegen_attrs.contains_extern_indicator()
344             || codegen_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL)
345         {
346             self.worklist.push(item.hir_id);
347         }
348
349         // We need only trait impls here, not inherent impls, and only non-exported ones
350         if let hir::ItemKind::Impl(.., Some(ref trait_ref), _, ref impl_item_refs) = item.kind {
351             if !self.access_levels.is_reachable(item.hir_id) {
352                 self.worklist.extend(impl_item_refs.iter().map(|ii_ref| ii_ref.id.hir_id));
353
354                 let trait_def_id = match trait_ref.path.res {
355                     Res::Def(DefKind::Trait, def_id) => def_id,
356                     _ => unreachable!(),
357                 };
358
359                 if !trait_def_id.is_local() {
360                     return;
361                 }
362
363                 let provided_trait_methods = self.tcx.provided_trait_methods(trait_def_id);
364                 self.worklist.reserve(provided_trait_methods.len());
365                 for default_method in provided_trait_methods {
366                     let hir_id = self.tcx.hir().as_local_hir_id(default_method.def_id).unwrap();
367                     self.worklist.push(hir_id);
368                 }
369             }
370         }
371     }
372
373     fn visit_trait_item(&mut self, _trait_item: &hir::TraitItem<'_>) {}
374
375     fn visit_impl_item(&mut self, _impl_item: &hir::ImplItem<'_>) {
376         // processed in visit_item above
377     }
378 }
379
380 fn reachable_set(tcx: TyCtxt<'_>, crate_num: CrateNum) -> Lrc<HirIdSet> {
381     debug_assert!(crate_num == LOCAL_CRATE);
382
383     let access_levels = &tcx.privacy_access_levels(LOCAL_CRATE);
384
385     let any_library = tcx.sess.crate_types.borrow().iter().any(|ty| {
386         *ty == config::CrateType::Rlib
387             || *ty == config::CrateType::Dylib
388             || *ty == config::CrateType::ProcMacro
389     });
390     let mut reachable_context = ReachableContext {
391         tcx,
392         tables: &ty::TypeckTables::empty(None),
393         reachable_symbols: Default::default(),
394         worklist: Vec::new(),
395         any_library,
396     };
397
398     // Step 1: Seed the worklist with all nodes which were found to be public as
399     //         a result of the privacy pass along with all local lang items and impl items.
400     //         If other crates link to us, they're going to expect to be able to
401     //         use the lang items, so we need to be sure to mark them as
402     //         exported.
403     reachable_context.worklist.extend(access_levels.map.iter().map(|(id, _)| *id));
404     for item in tcx.lang_items().items().iter() {
405         if let Some(did) = *item {
406             if let Some(hir_id) = tcx.hir().as_local_hir_id(did) {
407                 reachable_context.worklist.push(hir_id);
408             }
409         }
410     }
411     {
412         let mut collect_private_impl_items = CollectPrivateImplItemsVisitor {
413             tcx,
414             access_levels,
415             worklist: &mut reachable_context.worklist,
416         };
417         tcx.hir().krate().visit_all_item_likes(&mut collect_private_impl_items);
418     }
419
420     // Step 2: Mark all symbols that the symbols on the worklist touch.
421     reachable_context.propagate();
422
423     debug!("Inline reachability shows: {:?}", reachable_context.reachable_symbols);
424
425     // Return the set of reachable symbols.
426     Lrc::new(reachable_context.reachable_symbols)
427 }
428
429 pub fn provide(providers: &mut Providers<'_>) {
430     *providers = Providers { reachable_set, ..*providers };
431 }