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