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