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.
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.
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
18 use hir::CodegenFnAttrs;
19 use hir::map as hir_map;
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;
27 use util::nodemap::{NodeSet, FxHashSet};
29 use rustc_target::spec::abi::Abi;
33 use hir::def_id::LOCAL_CRATE;
34 use hir::intravisit::{Visitor, NestedVisitorMap};
35 use hir::itemlikevisit::ItemLikeVisitor;
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 {
43 GenericParamDefKind::Lifetime { .. } => {}
44 GenericParamDefKind::Type { .. } => return true,
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>,
55 attrs: CodegenFnAttrs) -> bool {
56 if attrs.requests_inline() {
63 let generics = tcx.generics_of(tcx.hir.local_def_id(item.id));
64 generics_require_inlining(generics)
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) {
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),
83 span_bug!(impl_item.span, "impl did is not an item")
86 span_bug!(impl_item.span, "found a foreign impl as a parent of a local method")
90 // Information needed while computing reachability.
91 struct ReachableContext<'a, 'tcx: 'a> {
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
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
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;
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))
122 hir::ExprMethodCall(..) => {
123 Some(self.tables.type_dependent_defs()[expr.hir_id])
129 Some(Def::Local(node_id)) | Some(Def::Upvar(node_id, ..)) => {
130 self.reachable_symbols.insert(node_id);
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);
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);
146 // If this wasn't a static, then the destination is
149 self.reachable_symbols.insert(node_id);
158 intravisit::walk_expr(self, expr)
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; }
171 match self.tcx.hir.find(node_id) {
172 Some(hir_map::NodeItem(item)) => {
175 item_might_be_inlined(self.tcx, &item, self.tcx.codegen_fn_attrs(def_id)),
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,
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() {
197 let impl_did = self.tcx
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
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)
213 hir::ImplItemKind::Type(_) => false,
217 None => false // This will happen for default methods.
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) {
229 if let Some(ref item) = self.tcx.hir.find(search_item) {
230 self.propagate_node(item, search_item);
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
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);
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);
261 hir_map::NodeItem(item) => {
263 hir::ItemFn(.., body) => {
264 let def_id = self.tcx.hir.local_def_id(item.id);
265 if item_might_be_inlined(self.tcx,
267 self.tcx.codegen_fn_attrs(def_id)) {
268 self.visit_nested_body(body);
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);
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(..) => {}
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
297 hir::TraitItemKind::Const(_, Some(body_id)) |
298 hir::TraitItemKind::Method(_, hir::TraitMethod::Provided(body_id)) => {
299 self.visit_nested_body(body_id);
301 hir::TraitItemKind::Type(..) => {}
304 hir_map::NodeImplItem(impl_item) => {
305 match impl_item.node {
306 hir::ImplItemKind::Const(_, body) => {
307 self.visit_nested_body(body);
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)
315 hir::ImplItemKind::Type(_) => {}
318 hir_map::NodeExpr(&hir::Expr { node: hir::ExprClosure(.., body, _, _), .. }) => {
319 self.visit_nested_body(body);
321 // Nothing to recurse on for these
322 hir_map::NodeForeignItem(_) |
323 hir_map::NodeVariant(_) |
324 hir_map::NodeStructCtor(_) |
325 hir_map::NodeField(_) |
327 hir_map::NodeMacroDef(_) => {}
329 bug!("found unexpected thingy in worklist: {}",
330 self.tcx.hir.node_to_string(search_item))
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>,
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);
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);
365 let trait_def_id = match trait_ref.path.def {
366 Def::Trait(def_id) => def_id,
370 if !trait_def_id.is_local() {
374 for default_method in self.tcx.provided_trait_methods(trait_def_id) {
375 let node_id = self.tcx
377 .as_local_node_id(default_method.def_id)
379 self.worklist.push(node_id);
385 fn visit_trait_item(&mut self, _trait_item: &hir::TraitItem) {}
387 fn visit_impl_item(&mut self, _impl_item: &hir::ImplItem) {
388 // processed in visit_item above
392 // We introduce a new-type here, so we can have a specialized HashStable
393 // implementation for it.
395 pub struct ReachableSet(pub Lrc<NodeSet>);
398 fn reachable_set<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, crate_num: CrateNum) -> ReachableSet {
399 debug_assert!(crate_num == LOCAL_CRATE);
401 let access_levels = &tcx.privacy_access_levels(LOCAL_CRATE);
403 let any_library = tcx.sess.crate_types.borrow().iter().any(|ty| {
404 *ty == config::CrateTypeRlib || *ty == config::CrateTypeDylib ||
405 *ty == config::CrateTypeProcMacro
407 let mut reachable_context = ReachableContext {
409 tables: &ty::TypeckTables::empty(None),
410 reachable_symbols: NodeSet(),
411 worklist: Vec::new(),
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
420 for (id, _) in &access_levels.map {
421 reachable_context.worklist.push(*id);
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);
431 let mut collect_private_impl_items = CollectPrivateImplItemsVisitor {
434 worklist: &mut reachable_context.worklist,
436 tcx.hir.krate().visit_all_item_likes(&mut collect_private_impl_items);
439 // Step 2: Mark all symbols that the symbols on the worklist touch.
440 reachable_context.propagate();
442 // Return the set of reachable symbols.
443 ReachableSet(Lrc::new(reachable_context.reachable_symbols))
446 pub fn provide(providers: &mut Providers) {
447 *providers = Providers {