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