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, CodegenFnAttrFlags};
21 use hir::def_id::{DefId, CrateNum};
22 use rustc_data_structures::sync::Lrc;
23 use ty::{self, TyCtxt};
24 use ty::query::Providers;
27 use util::nodemap::{NodeSet, FxHashSet};
29 use rustc_target::spec::abi::Abi;
32 use hir::def_id::LOCAL_CRATE;
33 use hir::intravisit::{Visitor, NestedVisitorMap};
34 use hir::itemlikevisit::ItemLikeVisitor;
37 // Returns true if the given item must be inlined because it may be
38 // monomorphized or it was marked with `#[inline]`. This will only return
39 // true for functions.
40 fn item_might_be_inlined(tcx: TyCtxt<'a, 'tcx, 'tcx>,
42 attrs: CodegenFnAttrs) -> bool {
43 if attrs.requests_inline() {
48 hir::ItemKind::Impl(..) |
49 hir::ItemKind::Fn(..) => {
50 let generics = tcx.generics_of(tcx.hir.local_def_id(item.id));
51 generics.requires_monomorphization(tcx)
57 fn method_might_be_inlined<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
58 impl_item: &hir::ImplItem,
59 impl_src: DefId) -> bool {
60 let codegen_fn_attrs = tcx.codegen_fn_attrs(impl_item.hir_id.owner_def_id());
61 let generics = tcx.generics_of(tcx.hir.local_def_id(impl_item.id));
62 if codegen_fn_attrs.requests_inline() || generics.requires_monomorphization(tcx) {
65 if let Some(impl_node_id) = tcx.hir.as_local_node_id(impl_src) {
66 match tcx.hir.find(impl_node_id) {
67 Some(Node::Item(item)) =>
68 item_might_be_inlined(tcx, &item, codegen_fn_attrs),
70 span_bug!(impl_item.span, "impl did is not an item")
73 span_bug!(impl_item.span, "found a foreign impl as a parent of a local method")
77 // Information needed while computing reachability.
78 struct ReachableContext<'a, 'tcx: 'a> {
80 tcx: TyCtxt<'a, 'tcx, 'tcx>,
81 tables: &'a ty::TypeckTables<'tcx>,
82 // The set of items which must be exported in the linkage sense.
83 reachable_symbols: NodeSet,
84 // A worklist of item IDs. Each item ID in this worklist will be inlined
85 // and will be scanned for further references.
86 worklist: Vec<ast::NodeId>,
87 // Whether any output of this compilation is a library
91 impl<'a, 'tcx> Visitor<'tcx> for ReachableContext<'a, 'tcx> {
92 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
93 NestedVisitorMap::None
96 fn visit_nested_body(&mut self, body: hir::BodyId) {
97 let old_tables = self.tables;
98 self.tables = self.tcx.body_tables(body);
99 let body = self.tcx.hir.body(body);
100 self.visit_body(body);
101 self.tables = old_tables;
104 fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
105 let def = match expr.node {
106 hir::ExprKind::Path(ref qpath) => {
107 Some(self.tables.qpath_def(qpath, expr.hir_id))
109 hir::ExprKind::MethodCall(..) => {
110 self.tables.type_dependent_defs().get(expr.hir_id).cloned()
116 Some(Def::Local(node_id)) | Some(Def::Upvar(node_id, ..)) => {
117 self.reachable_symbols.insert(node_id);
120 let def_id = def.def_id();
121 if let Some(node_id) = self.tcx.hir.as_local_node_id(def_id) {
122 if self.def_id_represents_local_inlined_item(def_id) {
123 self.worklist.push(node_id);
126 // If this path leads to a constant, then we need to
127 // recurse into the constant to continue finding
128 // items that are reachable.
129 Def::Const(..) | Def::AssociatedConst(..) => {
130 self.worklist.push(node_id);
133 // If this wasn't a static, then the destination is
136 self.reachable_symbols.insert(node_id);
145 intravisit::walk_expr(self, expr)
149 impl<'a, 'tcx> ReachableContext<'a, 'tcx> {
150 // Returns true if the given def ID represents a local item that is
151 // eligible for inlining and false otherwise.
152 fn def_id_represents_local_inlined_item(&self, def_id: DefId) -> bool {
153 let node_id = match self.tcx.hir.as_local_node_id(def_id) {
154 Some(node_id) => node_id,
155 None => { return false; }
158 match self.tcx.hir.find(node_id) {
159 Some(Node::Item(item)) => {
161 hir::ItemKind::Fn(..) =>
162 item_might_be_inlined(self.tcx, &item, self.tcx.codegen_fn_attrs(def_id)),
166 Some(Node::TraitItem(trait_method)) => {
167 match trait_method.node {
168 hir::TraitItemKind::Const(_, ref default) => default.is_some(),
169 hir::TraitItemKind::Method(_, hir::TraitMethod::Provided(_)) => true,
170 hir::TraitItemKind::Method(_, hir::TraitMethod::Required(_)) |
171 hir::TraitItemKind::Type(..) => false,
174 Some(Node::ImplItem(impl_item)) => {
175 match impl_item.node {
176 hir::ImplItemKind::Const(..) => true,
177 hir::ImplItemKind::Method(..) => {
178 let attrs = self.tcx.codegen_fn_attrs(def_id);
179 let generics = self.tcx.generics_of(def_id);
180 if generics.requires_monomorphization(self.tcx) || attrs.requests_inline() {
183 let impl_did = self.tcx
185 .get_parent_did(node_id);
186 // Check the impl. If the generics on the self
187 // type of the impl require inlining, this method
189 let impl_node_id = self.tcx.hir.as_local_node_id(impl_did).unwrap();
190 match self.tcx.hir.expect_item(impl_node_id).node {
191 hir::ItemKind::Impl(..) => {
192 let generics = self.tcx.generics_of(impl_did);
193 generics.requires_monomorphization(self.tcx)
199 hir::ImplItemKind::Existential(..) |
200 hir::ImplItemKind::Type(_) => false,
204 None => false // This will happen for default methods.
208 // Step 2: Mark all symbols that the symbols on the worklist touch.
209 fn propagate(&mut self) {
210 let mut scanned = FxHashSet();
211 while let Some(search_item) = self.worklist.pop() {
212 if !scanned.insert(search_item) {
216 if let Some(ref item) = self.tcx.hir.find(search_item) {
217 self.propagate_node(item, search_item);
222 fn propagate_node(&mut self, node: &Node<'tcx>,
223 search_item: ast::NodeId) {
224 if !self.any_library {
225 // If we are building an executable, only explicitly extern
226 // types need to be exported.
227 if let Node::Item(item) = *node {
228 let reachable = if let hir::ItemKind::Fn(_, header, ..) = item.node {
229 header.abi != Abi::Rust
233 let def_id = self.tcx.hir.local_def_id(item.id);
234 let codegen_attrs = self.tcx.codegen_fn_attrs(def_id);
235 let is_extern = codegen_attrs.contains_extern_indicator();
236 let std_internal = codegen_attrs.flags.contains(
237 CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL);
238 if reachable || is_extern || std_internal {
239 self.reachable_symbols.insert(search_item);
243 // If we are building a library, then reachable symbols will
244 // continue to participate in linkage after this product is
245 // produced. In this case, we traverse the ast node, recursing on
246 // all reachable nodes from this one.
247 self.reachable_symbols.insert(search_item);
251 Node::Item(item) => {
253 hir::ItemKind::Fn(.., body) => {
254 let def_id = self.tcx.hir.local_def_id(item.id);
255 if item_might_be_inlined(self.tcx,
257 self.tcx.codegen_fn_attrs(def_id)) {
258 self.visit_nested_body(body);
262 // Reachable constants will be inlined into other crates
263 // unconditionally, so we need to make sure that their
264 // contents are also reachable.
265 hir::ItemKind::Const(_, init) => {
266 self.visit_nested_body(init);
269 // These are normal, nothing reachable about these
270 // inherently and their children are already in the
271 // worklist, as determined by the privacy pass
272 hir::ItemKind::ExternCrate(_) |
273 hir::ItemKind::Use(..) |
274 hir::ItemKind::Existential(..) |
275 hir::ItemKind::Ty(..) |
276 hir::ItemKind::Static(..) |
277 hir::ItemKind::Mod(..) |
278 hir::ItemKind::ForeignMod(..) |
279 hir::ItemKind::Impl(..) |
280 hir::ItemKind::Trait(..) |
281 hir::ItemKind::TraitAlias(..) |
282 hir::ItemKind::Struct(..) |
283 hir::ItemKind::Enum(..) |
284 hir::ItemKind::Union(..) |
285 hir::ItemKind::GlobalAsm(..) => {}
288 Node::TraitItem(trait_method) => {
289 match trait_method.node {
290 hir::TraitItemKind::Const(_, None) |
291 hir::TraitItemKind::Method(_, hir::TraitMethod::Required(_)) => {
292 // Keep going, nothing to get exported
294 hir::TraitItemKind::Const(_, Some(body_id)) |
295 hir::TraitItemKind::Method(_, hir::TraitMethod::Provided(body_id)) => {
296 self.visit_nested_body(body_id);
298 hir::TraitItemKind::Type(..) => {}
301 Node::ImplItem(impl_item) => {
302 match impl_item.node {
303 hir::ImplItemKind::Const(_, body) => {
304 self.visit_nested_body(body);
306 hir::ImplItemKind::Method(_, body) => {
307 let did = self.tcx.hir.get_parent_did(search_item);
308 if method_might_be_inlined(self.tcx, impl_item, did) {
309 self.visit_nested_body(body)
312 hir::ImplItemKind::Existential(..) |
313 hir::ImplItemKind::Type(_) => {}
316 Node::Expr(&hir::Expr { node: hir::ExprKind::Closure(.., body, _, _), .. }) => {
317 self.visit_nested_body(body);
319 // Nothing to recurse on for these
320 Node::ForeignItem(_) |
322 Node::StructCtor(_) |
325 Node::MacroDef(_) => {}
327 bug!("found unexpected thingy in worklist: {}",
328 self.tcx.hir.node_to_string(search_item))
334 // Some methods from non-exported (completely private) trait impls still have to be
335 // reachable if they are called from inlinable code. Generally, it's not known until
336 // monomorphization if a specific trait impl item can be reachable or not. So, we
337 // conservatively mark all of them as reachable.
338 // FIXME: One possible strategy for pruning the reachable set is to avoid marking impl
339 // items of non-exported traits (or maybe all local traits?) unless their respective
340 // trait items are used from inlinable code through method call syntax or UFCS, or their
341 // trait is a lang item.
342 struct CollectPrivateImplItemsVisitor<'a, 'tcx: 'a> {
343 tcx: TyCtxt<'a, 'tcx, 'tcx>,
344 access_levels: &'a privacy::AccessLevels,
345 worklist: &'a mut Vec<ast::NodeId>,
348 impl<'a, 'tcx: 'a> ItemLikeVisitor<'tcx> for CollectPrivateImplItemsVisitor<'a, 'tcx> {
349 fn visit_item(&mut self, item: &hir::Item) {
350 // Anything which has custom linkage gets thrown on the worklist no
351 // matter where it is in the crate, along with "special std symbols"
352 // which are currently akin to allocator symbols.
353 let def_id = self.tcx.hir.local_def_id(item.id);
354 let codegen_attrs = self.tcx.codegen_fn_attrs(def_id);
355 if codegen_attrs.linkage.is_some() ||
356 codegen_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL) {
357 self.worklist.push(item.id);
360 // We need only trait impls here, not inherent impls, and only non-exported ones
361 if let hir::ItemKind::Impl(.., Some(ref trait_ref), _, ref impl_item_refs) = item.node {
362 if !self.access_levels.is_reachable(item.id) {
363 self.worklist.extend(impl_item_refs.iter().map(|r| r.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::CrateType::Rlib || *ty == config::CrateType::Dylib ||
405 *ty == config::CrateType::ProcMacro
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 reachable_context.worklist.extend(access_levels.map.iter().map(|(id, _)| *id));
421 for item in tcx.lang_items().items().iter() {
422 if let Some(did) = *item {
423 if let Some(node_id) = tcx.hir.as_local_node_id(did) {
424 reachable_context.worklist.push(node_id);
429 let mut collect_private_impl_items = CollectPrivateImplItemsVisitor {
432 worklist: &mut reachable_context.worklist,
434 tcx.hir.krate().visit_all_item_likes(&mut collect_private_impl_items);
437 // Step 2: Mark all symbols that the symbols on the worklist touch.
438 reachable_context.propagate();
440 debug!("Inline reachability shows: {:?}", reachable_context.reachable_symbols);
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 {