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