]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_passes/src/dead.rs
Rollup merge of #98870 - TaKO8Ki:add-regression-test-for-86784, r=compiler-errors
[rust.git] / compiler / rustc_passes / src / dead.rs
1 // This implements the dead-code warning pass. It follows middle::reachable
2 // closely. The idea is that all reachable symbols are live, codes called
3 // from live codes are live, and everything else is dead.
4
5 use itertools::Itertools;
6 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
7 use rustc_errors::{pluralize, MultiSpan};
8 use rustc_hir as hir;
9 use rustc_hir::def::{CtorOf, DefKind, Res};
10 use rustc_hir::def_id::{DefId, LocalDefId};
11 use rustc_hir::intravisit::{self, Visitor};
12 use rustc_hir::{Node, PatKind, TyKind};
13 use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags;
14 use rustc_middle::middle::privacy;
15 use rustc_middle::ty::query::Providers;
16 use rustc_middle::ty::{self, DefIdTree, TyCtxt};
17 use rustc_session::lint;
18 use rustc_span::symbol::{sym, Symbol};
19 use std::mem;
20
21 // Any local node that may call something in its body block should be
22 // explored. For example, if it's a live Node::Item that is a
23 // function, then we should explore its block to check for codes that
24 // may need to be marked as live.
25 fn should_explore(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool {
26     matches!(
27         tcx.hir().find_by_def_id(def_id),
28         Some(
29             Node::Item(..)
30                 | Node::ImplItem(..)
31                 | Node::ForeignItem(..)
32                 | Node::TraitItem(..)
33                 | Node::Variant(..)
34                 | Node::AnonConst(..)
35         )
36     )
37 }
38
39 struct MarkSymbolVisitor<'tcx> {
40     worklist: Vec<LocalDefId>,
41     tcx: TyCtxt<'tcx>,
42     maybe_typeck_results: Option<&'tcx ty::TypeckResults<'tcx>>,
43     live_symbols: FxHashSet<LocalDefId>,
44     repr_has_repr_c: bool,
45     in_pat: bool,
46     ignore_variant_stack: Vec<DefId>,
47     // maps from tuple struct constructors to tuple struct items
48     struct_constructors: FxHashMap<LocalDefId, LocalDefId>,
49     // maps from ADTs to ignored derived traits (e.g. Debug and Clone)
50     // and the span of their respective impl (i.e., part of the derive
51     // macro)
52     ignored_derived_traits: FxHashMap<LocalDefId, Vec<(DefId, DefId)>>,
53 }
54
55 impl<'tcx> MarkSymbolVisitor<'tcx> {
56     /// Gets the type-checking results for the current body.
57     /// As this will ICE if called outside bodies, only call when working with
58     /// `Expr` or `Pat` nodes (they are guaranteed to be found only in bodies).
59     #[track_caller]
60     fn typeck_results(&self) -> &'tcx ty::TypeckResults<'tcx> {
61         self.maybe_typeck_results
62             .expect("`MarkSymbolVisitor::typeck_results` called outside of body")
63     }
64
65     fn check_def_id(&mut self, def_id: DefId) {
66         if let Some(def_id) = def_id.as_local() {
67             if should_explore(self.tcx, def_id) || self.struct_constructors.contains_key(&def_id) {
68                 self.worklist.push(def_id);
69             }
70             self.live_symbols.insert(def_id);
71         }
72     }
73
74     fn insert_def_id(&mut self, def_id: DefId) {
75         if let Some(def_id) = def_id.as_local() {
76             debug_assert!(!should_explore(self.tcx, def_id));
77             self.live_symbols.insert(def_id);
78         }
79     }
80
81     fn handle_res(&mut self, res: Res) {
82         match res {
83             Res::Def(DefKind::Const | DefKind::AssocConst | DefKind::TyAlias, def_id) => {
84                 self.check_def_id(def_id);
85             }
86             _ if self.in_pat => {}
87             Res::PrimTy(..) | Res::SelfCtor(..) | Res::Local(..) => {}
88             Res::Def(DefKind::Ctor(CtorOf::Variant, ..), ctor_def_id) => {
89                 let variant_id = self.tcx.parent(ctor_def_id);
90                 let enum_id = self.tcx.parent(variant_id);
91                 self.check_def_id(enum_id);
92                 if !self.ignore_variant_stack.contains(&ctor_def_id) {
93                     self.check_def_id(variant_id);
94                 }
95             }
96             Res::Def(DefKind::Variant, variant_id) => {
97                 let enum_id = self.tcx.parent(variant_id);
98                 self.check_def_id(enum_id);
99                 if !self.ignore_variant_stack.contains(&variant_id) {
100                     self.check_def_id(variant_id);
101                 }
102             }
103             Res::Def(_, def_id) => self.check_def_id(def_id),
104             Res::SelfTy { trait_: t, alias_to: i } => {
105                 if let Some(t) = t {
106                     self.check_def_id(t);
107                 }
108                 if let Some((i, _)) = i {
109                     self.check_def_id(i);
110                 }
111             }
112             Res::ToolMod | Res::NonMacroAttr(..) | Res::Err => {}
113         }
114     }
115
116     fn lookup_and_handle_method(&mut self, id: hir::HirId) {
117         if let Some(def_id) = self.typeck_results().type_dependent_def_id(id) {
118             self.check_def_id(def_id);
119         } else {
120             bug!("no type-dependent def for method");
121         }
122     }
123
124     fn handle_field_access(&mut self, lhs: &hir::Expr<'_>, hir_id: hir::HirId) {
125         match self.typeck_results().expr_ty_adjusted(lhs).kind() {
126             ty::Adt(def, _) => {
127                 let index = self.tcx.field_index(hir_id, self.typeck_results());
128                 self.insert_def_id(def.non_enum_variant().fields[index].did);
129             }
130             ty::Tuple(..) => {}
131             _ => span_bug!(lhs.span, "named field access on non-ADT"),
132         }
133     }
134
135     #[allow(dead_code)] // FIXME(81658): should be used + lint reinstated after #83171 relands.
136     fn handle_assign(&mut self, expr: &'tcx hir::Expr<'tcx>) {
137         if self
138             .typeck_results()
139             .expr_adjustments(expr)
140             .iter()
141             .any(|adj| matches!(adj.kind, ty::adjustment::Adjust::Deref(_)))
142         {
143             self.visit_expr(expr);
144         } else if let hir::ExprKind::Field(base, ..) = expr.kind {
145             // Ignore write to field
146             self.handle_assign(base);
147         } else {
148             self.visit_expr(expr);
149         }
150     }
151
152     #[allow(dead_code)] // FIXME(81658): should be used + lint reinstated after #83171 relands.
153     fn check_for_self_assign(&mut self, assign: &'tcx hir::Expr<'tcx>) {
154         fn check_for_self_assign_helper<'tcx>(
155             typeck_results: &'tcx ty::TypeckResults<'tcx>,
156             lhs: &'tcx hir::Expr<'tcx>,
157             rhs: &'tcx hir::Expr<'tcx>,
158         ) -> bool {
159             match (&lhs.kind, &rhs.kind) {
160                 (hir::ExprKind::Path(ref qpath_l), hir::ExprKind::Path(ref qpath_r)) => {
161                     if let (Res::Local(id_l), Res::Local(id_r)) = (
162                         typeck_results.qpath_res(qpath_l, lhs.hir_id),
163                         typeck_results.qpath_res(qpath_r, rhs.hir_id),
164                     ) {
165                         if id_l == id_r {
166                             return true;
167                         }
168                     }
169                     return false;
170                 }
171                 (hir::ExprKind::Field(lhs_l, ident_l), hir::ExprKind::Field(lhs_r, ident_r)) => {
172                     if ident_l == ident_r {
173                         return check_for_self_assign_helper(typeck_results, lhs_l, lhs_r);
174                     }
175                     return false;
176                 }
177                 _ => {
178                     return false;
179                 }
180             }
181         }
182
183         if let hir::ExprKind::Assign(lhs, rhs, _) = assign.kind
184             && check_for_self_assign_helper(self.typeck_results(), lhs, rhs)
185                 && !assign.span.from_expansion()
186         {
187                 let is_field_assign = matches!(lhs.kind, hir::ExprKind::Field(..));
188                 self.tcx.struct_span_lint_hir(
189                     lint::builtin::DEAD_CODE,
190                     assign.hir_id,
191                     assign.span,
192                     |lint| {
193                         lint.build(&format!(
194                             "useless assignment of {} of type `{}` to itself",
195                             if is_field_assign { "field" } else { "variable" },
196                             self.typeck_results().expr_ty(lhs),
197                         ))
198                         .emit();
199                     },
200                 )
201         }
202     }
203
204     fn handle_field_pattern_match(
205         &mut self,
206         lhs: &hir::Pat<'_>,
207         res: Res,
208         pats: &[hir::PatField<'_>],
209     ) {
210         let variant = match self.typeck_results().node_type(lhs.hir_id).kind() {
211             ty::Adt(adt, _) => adt.variant_of_res(res),
212             _ => span_bug!(lhs.span, "non-ADT in struct pattern"),
213         };
214         for pat in pats {
215             if let PatKind::Wild = pat.pat.kind {
216                 continue;
217             }
218             let index = self.tcx.field_index(pat.hir_id, self.typeck_results());
219             self.insert_def_id(variant.fields[index].did);
220         }
221     }
222
223     fn mark_live_symbols(&mut self) {
224         let mut scanned = FxHashSet::default();
225         while let Some(id) = self.worklist.pop() {
226             if !scanned.insert(id) {
227                 continue;
228             }
229
230             // in the case of tuple struct constructors we want to check the item, not the generated
231             // tuple struct constructor function
232             let id = self.struct_constructors.get(&id).copied().unwrap_or(id);
233
234             if let Some(node) = self.tcx.hir().find_by_def_id(id) {
235                 self.live_symbols.insert(id);
236                 self.visit_node(node);
237             }
238         }
239     }
240
241     /// Automatically generated items marked with `rustc_trivial_field_reads`
242     /// will be ignored for the purposes of dead code analysis (see PR #85200
243     /// for discussion).
244     fn should_ignore_item(&mut self, def_id: DefId) -> bool {
245         if let Some(impl_of) = self.tcx.impl_of_method(def_id) {
246             if !self.tcx.has_attr(impl_of, sym::automatically_derived) {
247                 return false;
248             }
249
250             if let Some(trait_of) = self.tcx.trait_id_of_impl(impl_of)
251                 && self.tcx.has_attr(trait_of, sym::rustc_trivial_field_reads)
252             {
253                 let trait_ref = self.tcx.impl_trait_ref(impl_of).unwrap();
254                 if let ty::Adt(adt_def, _) = trait_ref.self_ty().kind()
255                     && let Some(adt_def_id) = adt_def.did().as_local()
256                 {
257                     self.ignored_derived_traits
258                         .entry(adt_def_id)
259                         .or_default()
260                         .push((trait_of, impl_of));
261                 }
262                 return true;
263             }
264         }
265
266         return false;
267     }
268
269     fn visit_node(&mut self, node: Node<'tcx>) {
270         if let Node::ImplItem(hir::ImplItem { def_id, .. }) = node
271             && self.should_ignore_item(def_id.to_def_id())
272         {
273             return;
274         }
275
276         let had_repr_c = self.repr_has_repr_c;
277         self.repr_has_repr_c = false;
278         match node {
279             Node::Item(item) => match item.kind {
280                 hir::ItemKind::Struct(..) | hir::ItemKind::Union(..) => {
281                     let def = self.tcx.adt_def(item.def_id);
282                     self.repr_has_repr_c = def.repr().c();
283
284                     intravisit::walk_item(self, &item)
285                 }
286                 hir::ItemKind::ForeignMod { .. } => {}
287                 _ => intravisit::walk_item(self, &item),
288             },
289             Node::TraitItem(trait_item) => {
290                 intravisit::walk_trait_item(self, trait_item);
291             }
292             Node::ImplItem(impl_item) => {
293                 let item = self.tcx.local_parent(impl_item.def_id);
294                 if self.tcx.impl_trait_ref(item).is_none() {
295                     //// If it's a type whose items are live, then it's live, too.
296                     //// This is done to handle the case where, for example, the static
297                     //// method of a private type is used, but the type itself is never
298                     //// called directly.
299                     let self_ty = self.tcx.type_of(item);
300                     match *self_ty.kind() {
301                         ty::Adt(def, _) => self.check_def_id(def.did()),
302                         ty::Foreign(did) => self.check_def_id(did),
303                         ty::Dynamic(data, ..) => {
304                             if let Some(def_id) = data.principal_def_id() {
305                                 self.check_def_id(def_id)
306                             }
307                         }
308                         _ => {}
309                     }
310                 }
311                 intravisit::walk_impl_item(self, impl_item);
312             }
313             Node::ForeignItem(foreign_item) => {
314                 intravisit::walk_foreign_item(self, &foreign_item);
315             }
316             _ => {}
317         }
318         self.repr_has_repr_c = had_repr_c;
319     }
320
321     fn mark_as_used_if_union(&mut self, adt: ty::AdtDef<'tcx>, fields: &[hir::ExprField<'_>]) {
322         if adt.is_union() && adt.non_enum_variant().fields.len() > 1 && adt.did().is_local() {
323             for field in fields {
324                 let index = self.tcx.field_index(field.hir_id, self.typeck_results());
325                 self.insert_def_id(adt.non_enum_variant().fields[index].did);
326             }
327         }
328     }
329 }
330
331 impl<'tcx> Visitor<'tcx> for MarkSymbolVisitor<'tcx> {
332     fn visit_nested_body(&mut self, body: hir::BodyId) {
333         let old_maybe_typeck_results =
334             self.maybe_typeck_results.replace(self.tcx.typeck_body(body));
335         let body = self.tcx.hir().body(body);
336         self.visit_body(body);
337         self.maybe_typeck_results = old_maybe_typeck_results;
338     }
339
340     fn visit_variant_data(
341         &mut self,
342         def: &'tcx hir::VariantData<'tcx>,
343         _: Symbol,
344         _: &hir::Generics<'_>,
345         _: hir::HirId,
346         _: rustc_span::Span,
347     ) {
348         let tcx = self.tcx;
349         let has_repr_c = self.repr_has_repr_c;
350         let live_fields = def.fields().iter().filter_map(|f| {
351             let def_id = tcx.hir().local_def_id(f.hir_id);
352             if has_repr_c {
353                 return Some(def_id);
354             }
355             if !tcx.visibility(f.hir_id.owner).is_public() {
356                 return None;
357             }
358             if tcx.visibility(def_id).is_public() { Some(def_id) } else { None }
359         });
360         self.live_symbols.extend(live_fields);
361
362         intravisit::walk_struct_def(self, def);
363     }
364
365     fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
366         match expr.kind {
367             hir::ExprKind::Path(ref qpath @ hir::QPath::TypeRelative(..)) => {
368                 let res = self.typeck_results().qpath_res(qpath, expr.hir_id);
369                 self.handle_res(res);
370             }
371             hir::ExprKind::MethodCall(..) => {
372                 self.lookup_and_handle_method(expr.hir_id);
373             }
374             hir::ExprKind::Field(ref lhs, ..) => {
375                 self.handle_field_access(&lhs, expr.hir_id);
376             }
377             hir::ExprKind::Struct(ref qpath, ref fields, _) => {
378                 let res = self.typeck_results().qpath_res(qpath, expr.hir_id);
379                 self.handle_res(res);
380                 if let ty::Adt(adt, _) = self.typeck_results().expr_ty(expr).kind() {
381                     self.mark_as_used_if_union(*adt, fields);
382                 }
383             }
384             _ => (),
385         }
386
387         intravisit::walk_expr(self, expr);
388     }
389
390     fn visit_arm(&mut self, arm: &'tcx hir::Arm<'tcx>) {
391         // Inside the body, ignore constructions of variants
392         // necessary for the pattern to match. Those construction sites
393         // can't be reached unless the variant is constructed elsewhere.
394         let len = self.ignore_variant_stack.len();
395         self.ignore_variant_stack.extend(arm.pat.necessary_variants());
396         intravisit::walk_arm(self, arm);
397         self.ignore_variant_stack.truncate(len);
398     }
399
400     fn visit_pat(&mut self, pat: &'tcx hir::Pat<'tcx>) {
401         self.in_pat = true;
402         match pat.kind {
403             PatKind::Struct(ref path, ref fields, _) => {
404                 let res = self.typeck_results().qpath_res(path, pat.hir_id);
405                 self.handle_field_pattern_match(pat, res, fields);
406             }
407             PatKind::Path(ref qpath) => {
408                 let res = self.typeck_results().qpath_res(qpath, pat.hir_id);
409                 self.handle_res(res);
410             }
411             _ => (),
412         }
413
414         intravisit::walk_pat(self, pat);
415         self.in_pat = false;
416     }
417
418     fn visit_path(&mut self, path: &'tcx hir::Path<'tcx>, _: hir::HirId) {
419         self.handle_res(path.res);
420         intravisit::walk_path(self, path);
421     }
422
423     fn visit_ty(&mut self, ty: &'tcx hir::Ty<'tcx>) {
424         if let TyKind::OpaqueDef(item_id, _) = ty.kind {
425             let item = self.tcx.hir().item(item_id);
426             intravisit::walk_item(self, item);
427         }
428         intravisit::walk_ty(self, ty);
429     }
430
431     fn visit_anon_const(&mut self, c: &'tcx hir::AnonConst) {
432         // When inline const blocks are used in pattern position, paths
433         // referenced by it should be considered as used.
434         let in_pat = mem::replace(&mut self.in_pat, false);
435
436         self.live_symbols.insert(self.tcx.hir().local_def_id(c.hir_id));
437         intravisit::walk_anon_const(self, c);
438
439         self.in_pat = in_pat;
440     }
441 }
442
443 fn has_allow_dead_code_or_lang_attr(tcx: TyCtxt<'_>, id: hir::HirId) -> bool {
444     let attrs = tcx.hir().attrs(id);
445     if tcx.sess.contains_name(attrs, sym::lang) {
446         return true;
447     }
448
449     // Stable attribute for #[lang = "panic_impl"]
450     if tcx.sess.contains_name(attrs, sym::panic_handler) {
451         return true;
452     }
453
454     // (To be) stable attribute for #[lang = "oom"]
455     if tcx.sess.contains_name(attrs, sym::alloc_error_handler) {
456         return true;
457     }
458
459     let def_id = tcx.hir().local_def_id(id);
460     if tcx.def_kind(def_id).has_codegen_attrs() {
461         let cg_attrs = tcx.codegen_fn_attrs(def_id);
462
463         // #[used], #[no_mangle], #[export_name], etc also keeps the item alive
464         // forcefully, e.g., for placing it in a specific section.
465         if cg_attrs.contains_extern_indicator()
466             || cg_attrs.flags.contains(CodegenFnAttrFlags::USED)
467             || cg_attrs.flags.contains(CodegenFnAttrFlags::USED_LINKER)
468         {
469             return true;
470         }
471     }
472
473     tcx.lint_level_at_node(lint::builtin::DEAD_CODE, id).0 == lint::Allow
474 }
475
476 // These check_* functions seeds items that
477 //   1) We want to explicitly consider as live:
478 //     * Item annotated with #[allow(dead_code)]
479 //         - This is done so that if we want to suppress warnings for a
480 //           group of dead functions, we only have to annotate the "root".
481 //           For example, if both `f` and `g` are dead and `f` calls `g`,
482 //           then annotating `f` with `#[allow(dead_code)]` will suppress
483 //           warning for both `f` and `g`.
484 //     * Item annotated with #[lang=".."]
485 //         - This is because lang items are always callable from elsewhere.
486 //   or
487 //   2) We are not sure to be live or not
488 //     * Implementations of traits and trait methods
489 fn check_item<'tcx>(
490     tcx: TyCtxt<'tcx>,
491     worklist: &mut Vec<LocalDefId>,
492     struct_constructors: &mut FxHashMap<LocalDefId, LocalDefId>,
493     id: hir::ItemId,
494 ) {
495     let allow_dead_code = has_allow_dead_code_or_lang_attr(tcx, id.hir_id());
496     if allow_dead_code {
497         worklist.push(id.def_id);
498     }
499
500     match tcx.def_kind(id.def_id) {
501         DefKind::Enum => {
502             let item = tcx.hir().item(id);
503             if let hir::ItemKind::Enum(ref enum_def, _) = item.kind {
504                 let hir = tcx.hir();
505                 if allow_dead_code {
506                     worklist.extend(
507                         enum_def.variants.iter().map(|variant| hir.local_def_id(variant.id)),
508                     );
509                 }
510
511                 for variant in enum_def.variants {
512                     if let Some(ctor_hir_id) = variant.data.ctor_hir_id() {
513                         struct_constructors
514                             .insert(hir.local_def_id(ctor_hir_id), hir.local_def_id(variant.id));
515                     }
516                 }
517             }
518         }
519         DefKind::Impl => {
520             let of_trait = tcx.impl_trait_ref(id.def_id);
521
522             if of_trait.is_some() {
523                 worklist.push(id.def_id);
524             }
525
526             // get DefIds from another query
527             let local_def_ids = tcx
528                 .associated_item_def_ids(id.def_id)
529                 .iter()
530                 .filter_map(|def_id| def_id.as_local());
531
532             // And we access the Map here to get HirId from LocalDefId
533             for id in local_def_ids {
534                 if of_trait.is_some()
535                     || has_allow_dead_code_or_lang_attr(tcx, tcx.hir().local_def_id_to_hir_id(id))
536                 {
537                     worklist.push(id);
538                 }
539             }
540         }
541         DefKind::Struct => {
542             let item = tcx.hir().item(id);
543             if let hir::ItemKind::Struct(ref variant_data, _) = item.kind
544                 && let Some(ctor_hir_id) = variant_data.ctor_hir_id()
545             {
546                 struct_constructors.insert(tcx.hir().local_def_id(ctor_hir_id), item.def_id);
547             }
548         }
549         DefKind::GlobalAsm => {
550             // global_asm! is always live.
551             worklist.push(id.def_id);
552         }
553         _ => {}
554     }
555 }
556
557 fn check_trait_item<'tcx>(tcx: TyCtxt<'tcx>, worklist: &mut Vec<LocalDefId>, id: hir::TraitItemId) {
558     use hir::TraitItemKind::{Const, Fn};
559     if matches!(tcx.def_kind(id.def_id), DefKind::AssocConst | DefKind::AssocFn) {
560         let trait_item = tcx.hir().trait_item(id);
561         if matches!(trait_item.kind, Const(_, Some(_)) | Fn(_, hir::TraitFn::Provided(_)))
562             && has_allow_dead_code_or_lang_attr(tcx, trait_item.hir_id())
563         {
564             worklist.push(trait_item.def_id);
565         }
566     }
567 }
568
569 fn check_foreign_item<'tcx>(
570     tcx: TyCtxt<'tcx>,
571     worklist: &mut Vec<LocalDefId>,
572     id: hir::ForeignItemId,
573 ) {
574     if matches!(tcx.def_kind(id.def_id), DefKind::Static(_) | DefKind::Fn)
575         && has_allow_dead_code_or_lang_attr(tcx, id.hir_id())
576     {
577         worklist.push(id.def_id);
578     }
579 }
580
581 fn create_and_seed_worklist<'tcx>(
582     tcx: TyCtxt<'tcx>,
583 ) -> (Vec<LocalDefId>, FxHashMap<LocalDefId, LocalDefId>) {
584     let access_levels = &tcx.privacy_access_levels(());
585     // see `MarkSymbolVisitor::struct_constructors`
586     let mut struct_constructors = Default::default();
587     let mut worklist = access_levels
588         .map
589         .iter()
590         .filter_map(
591             |(&id, &level)| {
592                 if level >= privacy::AccessLevel::Reachable { Some(id) } else { None }
593             },
594         )
595         // Seed entry point
596         .chain(tcx.entry_fn(()).and_then(|(def_id, _)| def_id.as_local()))
597         .collect::<Vec<_>>();
598
599     let crate_items = tcx.hir_crate_items(());
600     for id in crate_items.items() {
601         check_item(tcx, &mut worklist, &mut struct_constructors, id);
602     }
603
604     for id in crate_items.trait_items() {
605         check_trait_item(tcx, &mut worklist, id);
606     }
607
608     for id in crate_items.foreign_items() {
609         check_foreign_item(tcx, &mut worklist, id);
610     }
611
612     (worklist, struct_constructors)
613 }
614
615 fn live_symbols_and_ignored_derived_traits<'tcx>(
616     tcx: TyCtxt<'tcx>,
617     (): (),
618 ) -> (FxHashSet<LocalDefId>, FxHashMap<LocalDefId, Vec<(DefId, DefId)>>) {
619     let (worklist, struct_constructors) = create_and_seed_worklist(tcx);
620     let mut symbol_visitor = MarkSymbolVisitor {
621         worklist,
622         tcx,
623         maybe_typeck_results: None,
624         live_symbols: Default::default(),
625         repr_has_repr_c: false,
626         in_pat: false,
627         ignore_variant_stack: vec![],
628         struct_constructors,
629         ignored_derived_traits: FxHashMap::default(),
630     };
631     symbol_visitor.mark_live_symbols();
632     (symbol_visitor.live_symbols, symbol_visitor.ignored_derived_traits)
633 }
634
635 struct DeadVariant {
636     def_id: LocalDefId,
637     name: Symbol,
638     level: lint::Level,
639 }
640
641 struct DeadVisitor<'tcx> {
642     tcx: TyCtxt<'tcx>,
643     live_symbols: &'tcx FxHashSet<LocalDefId>,
644     ignored_derived_traits: &'tcx FxHashMap<LocalDefId, Vec<(DefId, DefId)>>,
645 }
646
647 impl<'tcx> DeadVisitor<'tcx> {
648     fn should_warn_about_field(&mut self, field: &ty::FieldDef) -> bool {
649         if self.live_symbols.contains(&field.did.expect_local()) {
650             return false;
651         }
652         let is_positional = field.name.as_str().starts_with(|c: char| c.is_ascii_digit());
653         if is_positional {
654             return false;
655         }
656         let field_type = self.tcx.type_of(field.did);
657         !field_type.is_phantom_data()
658     }
659
660     fn warn_multiple_dead_codes(
661         &self,
662         dead_codes: &[LocalDefId],
663         participle: &str,
664         parent_item: Option<LocalDefId>,
665     ) {
666         if let Some(&first_id) = dead_codes.first() {
667             let tcx = self.tcx;
668             let names: Vec<_> = dead_codes
669                 .iter()
670                 .map(|&def_id| tcx.item_name(def_id.to_def_id()).to_string())
671                 .collect();
672             let spans = dead_codes
673                 .iter()
674                 .map(|&def_id| match tcx.def_ident_span(def_id) {
675                     Some(s) => s.with_ctxt(tcx.def_span(def_id).ctxt()),
676                     None => tcx.def_span(def_id),
677                 })
678                 .collect();
679
680             tcx.struct_span_lint_hir(
681                 lint::builtin::DEAD_CODE,
682                 tcx.hir().local_def_id_to_hir_id(first_id),
683                 MultiSpan::from_spans(spans),
684                 |lint| {
685                     let descr = tcx.def_kind(first_id).descr(first_id.to_def_id());
686                     let span_len = dead_codes.len();
687                     let names = match &names[..] {
688                         _ if span_len > 6 => String::new(),
689                         [name] => format!("`{name}` "),
690                         [names @ .., last] => {
691                             format!(
692                                 "{} and `{last}` ",
693                                 names.iter().map(|name| format!("`{name}`")).join(", ")
694                             )
695                         }
696                         [] => unreachable!(),
697                     };
698                     let mut err = lint.build(&format!(
699                         "{these}{descr}{s} {names}{are} never {participle}",
700                         these = if span_len > 6 { "multiple " } else { "" },
701                         s = pluralize!(span_len),
702                         are = pluralize!("is", span_len),
703                     ));
704
705                     if let Some(parent_item) = parent_item {
706                         let parent_descr = tcx.def_kind(parent_item).descr(parent_item.to_def_id());
707                         err.span_label(
708                             tcx.def_ident_span(parent_item).unwrap(),
709                             format!("{descr}{s} in this {parent_descr}", s = pluralize!(span_len)),
710                         );
711                     }
712
713                     let encl_def_id = parent_item.unwrap_or(first_id);
714                     if let Some(ign_traits) = self.ignored_derived_traits.get(&encl_def_id) {
715                         let traits_str = ign_traits
716                             .iter()
717                             .map(|(trait_id, _)| format!("`{}`", self.tcx.item_name(*trait_id)))
718                             .collect::<Vec<_>>()
719                             .join(" and ");
720                         let plural_s = pluralize!(ign_traits.len());
721                         let article = if ign_traits.len() > 1 { "" } else { "a " };
722                         let is_are = if ign_traits.len() > 1 { "these are" } else { "this is" };
723                         let msg = format!(
724                             "`{}` has {}derived impl{} for the trait{} {}, but {} \
725                             intentionally ignored during dead code analysis",
726                             self.tcx.item_name(encl_def_id.to_def_id()),
727                             article,
728                             plural_s,
729                             plural_s,
730                             traits_str,
731                             is_are
732                         );
733                         err.note(&msg);
734                     }
735                     err.emit();
736                 },
737             );
738         }
739     }
740
741     fn warn_dead_fields_and_variants(
742         &self,
743         def_id: LocalDefId,
744         participle: &str,
745         dead_codes: Vec<DeadVariant>,
746     ) {
747         let mut dead_codes = dead_codes
748             .iter()
749             .filter(|v| !v.name.as_str().starts_with('_'))
750             .map(|v| v)
751             .collect::<Vec<&DeadVariant>>();
752         if dead_codes.is_empty() {
753             return;
754         }
755         dead_codes.sort_by_key(|v| v.level);
756         for (_, group) in &dead_codes.into_iter().group_by(|v| v.level) {
757             self.warn_multiple_dead_codes(
758                 &group.map(|v| v.def_id).collect::<Vec<_>>(),
759                 participle,
760                 Some(def_id),
761             );
762         }
763     }
764
765     fn warn_dead_code(&mut self, id: LocalDefId, participle: &str) {
766         self.warn_multiple_dead_codes(&[id], participle, None);
767     }
768
769     fn check_definition(&mut self, def_id: LocalDefId) {
770         if self.live_symbols.contains(&def_id) {
771             return;
772         }
773         let hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id);
774         if has_allow_dead_code_or_lang_attr(self.tcx, hir_id) {
775             return;
776         }
777         let Some(name) = self.tcx.opt_item_name(def_id.to_def_id()) else {
778             return
779         };
780         if name.as_str().starts_with('_') {
781             return;
782         }
783         match self.tcx.def_kind(def_id) {
784             DefKind::AssocConst
785             | DefKind::AssocFn
786             | DefKind::Fn
787             | DefKind::Static(_)
788             | DefKind::Const
789             | DefKind::TyAlias
790             | DefKind::Enum
791             | DefKind::Union
792             | DefKind::ForeignTy => self.warn_dead_code(def_id, "used"),
793             DefKind::Struct => self.warn_dead_code(def_id, "constructed"),
794             DefKind::Variant | DefKind::Field => bug!("should be handled specially"),
795             _ => {}
796         }
797     }
798 }
799
800 fn check_mod_deathness(tcx: TyCtxt<'_>, module: LocalDefId) {
801     let (live_symbols, ignored_derived_traits) = tcx.live_symbols_and_ignored_derived_traits(());
802     let mut visitor = DeadVisitor { tcx, live_symbols, ignored_derived_traits };
803
804     let module_items = tcx.hir_module_items(module);
805
806     for item in module_items.items() {
807         if !live_symbols.contains(&item.def_id) {
808             let parent = tcx.local_parent(item.def_id);
809             if parent != module && !live_symbols.contains(&parent) {
810                 // We already have diagnosed something.
811                 continue;
812             }
813             visitor.check_definition(item.def_id);
814             continue;
815         }
816
817         let def_kind = tcx.def_kind(item.def_id);
818         if let DefKind::Struct | DefKind::Union | DefKind::Enum = def_kind {
819             let adt = tcx.adt_def(item.def_id);
820             let mut dead_variants = Vec::new();
821
822             for variant in adt.variants() {
823                 let def_id = variant.def_id.expect_local();
824                 if !live_symbols.contains(&def_id) {
825                     // Record to group diagnostics.
826                     let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
827                     let level = tcx.lint_level_at_node(lint::builtin::DEAD_CODE, hir_id).0;
828                     dead_variants.push(DeadVariant { def_id, name: variant.name, level });
829                     continue;
830                 }
831
832                 let dead_fields = variant
833                     .fields
834                     .iter()
835                     .filter_map(|field| {
836                         let def_id = field.did.expect_local();
837                         let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
838                         if visitor.should_warn_about_field(&field) {
839                             let level = tcx.lint_level_at_node(lint::builtin::DEAD_CODE, hir_id).0;
840                             Some(DeadVariant { def_id, name: field.name, level })
841                         } else {
842                             None
843                         }
844                     })
845                     .collect();
846                 visitor.warn_dead_fields_and_variants(def_id, "read", dead_fields)
847             }
848
849             visitor.warn_dead_fields_and_variants(item.def_id, "constructed", dead_variants);
850         }
851     }
852
853     for impl_item in module_items.impl_items() {
854         visitor.check_definition(impl_item.def_id);
855     }
856
857     for foreign_item in module_items.foreign_items() {
858         visitor.check_definition(foreign_item.def_id);
859     }
860
861     // We do not warn trait items.
862 }
863
864 pub(crate) fn provide(providers: &mut Providers) {
865     *providers =
866         Providers { live_symbols_and_ignored_derived_traits, check_mod_deathness, ..*providers };
867 }