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