Skip to main content

rustc_passes/
dead.rs

1// This implements the dead-code warning pass.
2// All reachable symbols are live, code called from live code is live, code with certain lint
3// expectations such as `#[expect(unused)]` and `#[expect(dead_code)]` is live, and everything else
4// is dead.
5
6use std::mem;
7use std::ops::ControlFlow;
8use std::sync::atomic::Ordering;
9
10use hir::def_id::{LocalDefIdMap, LocalDefIdSet};
11use rustc_abi::FieldIdx;
12use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexSet};
13use rustc_errors::{ErrorGuaranteed, MultiSpan};
14use rustc_hir::def::{CtorOf, DefKind, Res};
15use rustc_hir::def_id::{DefId, LocalDefId, LocalModId};
16use rustc_hir::intravisit::{self, Visitor};
17use rustc_hir::{self as hir, ForeignItemId, ItemId, Node, PatKind, QPath, find_attr};
18use rustc_lint_defs::builtin::{DEAD_CODE, DEAD_CODE_PUB_IN_BINARY};
19use rustc_lint_defs::{self as lint, Lint, StableLintExpectationId};
20use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags;
21use rustc_middle::middle::dead_code::{DeadCodeLivenessSnapshot, DeadCodeLivenessSummary};
22use rustc_middle::middle::privacy::Level;
23use rustc_middle::query::Providers;
24use rustc_middle::ty::{self, AssocTag, TyCtxt};
25use rustc_span::{Symbol, bug, kw, span_bug};
26use rustc_structures::CrateType;
27
28use crate::diagnostics::{
29    ChangeFields, DeadCodePubInBinaryNote, IgnoredDerivedImpls, MultipleDeadCodes, ParentInfo,
30    UselessAssignment,
31};
32
33/// Any local definition that may call something in its body block should be explored. For example,
34/// if it's a live function, then we should explore its block to check for codes that may need to
35/// be marked as live.
36fn should_explore(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool {
37    match tcx.def_kind(def_id) {
38        DefKind::Mod
39        | DefKind::Struct
40        | DefKind::Union
41        | DefKind::Enum
42        | DefKind::Variant
43        | DefKind::Trait
44        | DefKind::TyAlias
45        | DefKind::ForeignTy
46        | DefKind::TraitAlias
47        | DefKind::AssocTy
48        | DefKind::Fn
49        | DefKind::Const
50        | DefKind::Static { .. }
51        | DefKind::AssocFn
52        | DefKind::AssocConst
53        | DefKind::Macro(_)
54        | DefKind::GlobalAsm
55        | DefKind::Impl { .. }
56        | DefKind::OpaqueTy
57        | DefKind::AnonConst
58        | DefKind::ExternCrate
59        | DefKind::Use
60        | DefKind::Ctor(..)
61        | DefKind::ForeignMod => true,
62
63        DefKind::TyParam
64        | DefKind::ConstParam
65        | DefKind::Field
66        | DefKind::LifetimeParam
67        | DefKind::Closure
68        | DefKind::SyntheticCoroutineBody
69        | DefKind::TestBinderConstraints => false,
70    }
71}
72
73/// Determine if a work from the worklist is coming from a `#[allow]`
74/// or a `#[expect]` of `dead_code`
75#[derive(#[automatically_derived]
impl ::core::fmt::Debug for ComesFromAllowExpect {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                ComesFromAllowExpect::Yes => "Yes",
                ComesFromAllowExpect::No => "No",
            })
    }
}Debug, #[automatically_derived]
impl ::core::marker::Copy for ComesFromAllowExpect { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for ComesFromAllowExpect { }
#[automatically_derived]
impl ::core::clone::Clone for ComesFromAllowExpect {
    #[inline]
    fn clone(&self) -> ComesFromAllowExpect { *self }
}Clone, #[automatically_derived]
impl ::core::cmp::Eq for ComesFromAllowExpect { }Eq, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for ComesFromAllowExpect { }
#[automatically_derived]
impl ::core::cmp::PartialEq for ComesFromAllowExpect {
    #[inline]
    fn eq(&self, other: &ComesFromAllowExpect) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq, #[automatically_derived]
impl ::core::hash::Hash for ComesFromAllowExpect {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        ::core::hash::Hash::hash(&__self_discr, state)
    }
}Hash)]
76enum ComesFromAllowExpect {
77    Yes,
78    No,
79}
80
81/// Carries both the propagated `allow/expect` context and the current item's
82/// own `allow/expect` status.
83///
84/// For example:
85///
86/// ```rust
87/// #[expect(dead_code)]
88/// fn root() { middle() }
89///
90/// fn middle() { leaf() }
91///
92/// #[expect(dead_code)]
93/// fn leaf() {}
94/// ```
95///
96/// The seed for `root` starts as `propagated = Yes, own = Yes`.
97///
98/// When `root` reaches `middle`, the propagated context stays `Yes`, but
99/// `middle` itself does not have `#[allow(dead_code)]` or `#[expect(dead_code)]`,
100/// so its work item becomes `propagated = Yes, own = No`.
101///
102/// When `middle` reaches `leaf`, that same propagated `Yes` context is preserved,
103/// and since `leaf` itself has `#[expect(dead_code)]`, its work item becomes
104/// `propagated = Yes, own = Yes`.
105///
106/// In general, `propagated` controls whether descendants are still explored
107/// under an `allow/expect` context, while `own` controls whether the current
108/// item itself should be excluded from `live_symbols`.
109#[derive(#[automatically_derived]
impl ::core::fmt::Debug for WorkItem {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field3_finish(f, "WorkItem",
            "id", &self.id, "propagated", &self.propagated, "own", &&self.own)
    }
}Debug, #[automatically_derived]
impl ::core::marker::Copy for WorkItem { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for WorkItem { }
#[automatically_derived]
impl ::core::clone::Clone for WorkItem {
    #[inline]
    fn clone(&self) -> WorkItem {
        let _: ::core::clone::AssertParamIsClone<LocalDefId>;
        let _: ::core::clone::AssertParamIsClone<ComesFromAllowExpect>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::cmp::Eq for WorkItem {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<LocalDefId>;
        let _: ::core::cmp::AssertParamIsEq<ComesFromAllowExpect>;
    }
}Eq, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for WorkItem { }
#[automatically_derived]
impl ::core::cmp::PartialEq for WorkItem {
    #[inline]
    fn eq(&self, other: &WorkItem) -> bool {
        self.id == other.id && self.propagated == other.propagated &&
            self.own == other.own
    }
}PartialEq, #[automatically_derived]
impl ::core::hash::Hash for WorkItem {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&self.id, state);
        ::core::hash::Hash::hash(&self.propagated, state);
        ::core::hash::Hash::hash(&self.own, state)
    }
}Hash)]
110struct WorkItem {
111    id: LocalDefId,
112    propagated: ComesFromAllowExpect,
113    own: ComesFromAllowExpect,
114}
115
116enum ImplItemCheckResult {
117    Live(ComesFromAllowExpect),
118    Dead { require: LocalDefId },
119}
120
121struct MarkSymbolVisitor<'tcx> {
122    worklist: Vec<WorkItem>,
123    tcx: TyCtxt<'tcx>,
124    maybe_typeck_results: Option<&'tcx ty::TypeckResults<'tcx>>,
125    scanned: FxHashSet<(LocalDefId, ComesFromAllowExpect)>,
126    live_symbols: LocalDefIdSet,
127    repr_unconditionally_treats_fields_as_live: bool,
128    repr_has_repr_simd_or_scalable: bool,
129    in_pat: bool,
130    ignore_variant_stack: Vec<DefId>,
131    // maps from ADTs to ignored derived traits (e.g. Debug and Clone)
132    // and the span of their respective impl (i.e., part of the derive
133    // macro)
134    ignored_derived_traits: LocalDefIdMap<FxIndexSet<DefId>>,
135    propagated_comes_from_allow_expect: ComesFromAllowExpect,
136    unsolved_items: Vec<LocalDefId>,
137}
138
139impl<'tcx> MarkSymbolVisitor<'tcx> {
140    /// Gets the type-checking results for the current body.
141    /// As this will ICE if called outside bodies, only call when working with
142    /// `Expr` or `Pat` nodes (they are guaranteed to be found only in bodies).
143    #[track_caller]
144    fn typeck_results(&self) -> &'tcx ty::TypeckResults<'tcx> {
145        self.maybe_typeck_results
146            .expect("`MarkSymbolVisitor::typeck_results` called outside of body")
147    }
148
149    /// Returns whether `def_id` itself should be treated as coming from
150    /// `#[allow(dead_code)]` or `#[expect(dead_code)]` in the current
151    /// propagated work-item context.
152    fn own_comes_from_allow_expect(&self, def_id: LocalDefId) -> ComesFromAllowExpect {
153        if self.propagated_comes_from_allow_expect == ComesFromAllowExpect::Yes
154            && let Some(ComesFromAllowExpect::Yes) =
155                has_allow_dead_code_or_lang_attr(self.tcx, def_id)
156        {
157            ComesFromAllowExpect::Yes
158        } else {
159            ComesFromAllowExpect::No
160        }
161    }
162
163    fn check_def_id(&mut self, def_id: DefId) {
164        if let Some(def_id) = def_id.as_local() {
165            let own_comes_from_allow_expect = self.own_comes_from_allow_expect(def_id);
166
167            if should_explore(self.tcx, def_id) {
168                self.worklist.push(WorkItem {
169                    id: def_id,
170                    propagated: self.propagated_comes_from_allow_expect,
171                    own: own_comes_from_allow_expect,
172                });
173            }
174
175            if own_comes_from_allow_expect == ComesFromAllowExpect::No {
176                self.live_symbols.insert(def_id);
177            }
178        }
179    }
180
181    fn insert_def_id(&mut self, def_id: DefId) {
182        if let Some(def_id) = def_id.as_local() {
183            if true {
    if !!should_explore(self.tcx, def_id) {
        ::core::panicking::panic("assertion failed: !should_explore(self.tcx, def_id)")
    };
};debug_assert!(!should_explore(self.tcx, def_id));
184
185            if self.own_comes_from_allow_expect(def_id) == ComesFromAllowExpect::No {
186                self.live_symbols.insert(def_id);
187            }
188        }
189    }
190
191    fn handle_res(&mut self, res: Res) {
192        match res {
193            Res::PrimTy(..) | Res::SelfCtor(..) | Res::Local(..) => {}
194            Res::Def(DefKind::Ctor(CtorOf::Variant, ..), ctor_def_id) => {
195                // Using a variant in patterns should not make the variant live,
196                // since we can just remove the match arm that matches the pattern
197                if self.in_pat {
198                    return;
199                }
200                let variant_id = self.tcx.parent(ctor_def_id);
201                let enum_id = self.tcx.parent(variant_id);
202                self.check_def_id(enum_id);
203                if !self.ignore_variant_stack.contains(&ctor_def_id) {
204                    self.check_def_id(variant_id);
205                }
206            }
207            Res::Def(DefKind::Variant, variant_id) => {
208                // Using a variant in patterns should not make the variant live,
209                // since we can just remove the match arm that matches the pattern
210                if self.in_pat {
211                    return;
212                }
213                let enum_id = self.tcx.parent(variant_id);
214                self.check_def_id(enum_id);
215                if !self.ignore_variant_stack.contains(&variant_id) {
216                    self.check_def_id(variant_id);
217                }
218            }
219            Res::Def(_, def_id) => self.check_def_id(def_id),
220            Res::SelfTyParam { trait_: t } => self.check_def_id(t),
221            Res::SelfTyAlias { alias_to: i, .. } => self.check_def_id(i),
222            Res::ToolMod | Res::NonMacroAttr(..) | Res::OpenMod(..) | Res::Err => {}
223        }
224    }
225
226    fn lookup_and_handle_method(&mut self, id: hir::HirId) {
227        if let Some(def_id) = self.typeck_results().type_dependent_def_id(id) {
228            self.check_def_id(def_id);
229        } else {
230            if !self.typeck_results().tainted_by_errors.is_some() {
    {
        ::core::panicking::panic_fmt(format_args!("no type-dependent def for method"));
    }
};assert!(
231                self.typeck_results().tainted_by_errors.is_some(),
232                "no type-dependent def for method"
233            );
234        }
235    }
236
237    fn handle_field_access(&mut self, lhs: &hir::Expr<'_>, hir_id: hir::HirId) {
238        match self.typeck_results().expr_ty_adjusted(lhs).kind() {
239            ty::Adt(def, _) => {
240                let index = self.typeck_results().field_index(hir_id);
241                self.insert_def_id(def.non_enum_variant().fields[index].did);
242            }
243            ty::Tuple(..) => {}
244            ty::Error(_) => {}
245            kind => bug_impl(Some(lhs.span),
    format_args!("named field access on non-ADT: {0:?}", kind),
    Location::caller())span_bug!(lhs.span, "named field access on non-ADT: {kind:?}"),
246        }
247    }
248
249    fn handle_assign(&mut self, expr: &'tcx hir::Expr<'tcx>) {
250        if self
251            .typeck_results()
252            .expr_adjustments(expr)
253            .iter()
254            .any(|adj| #[allow(non_exhaustive_omitted_patterns)] match adj.kind {
    ty::adjustment::Adjust::Deref(_) => true,
    _ => false,
}matches!(adj.kind, ty::adjustment::Adjust::Deref(_)))
255        {
256            let _ = self.visit_expr(expr);
257        } else if let hir::ExprKind::Field(base, ..) = expr.kind {
258            // Ignore write to field
259            self.handle_assign(base);
260        } else {
261            let _ = self.visit_expr(expr);
262        }
263    }
264
265    fn check_for_self_assign(&mut self, assign: &'tcx hir::Expr<'tcx>) {
266        fn check_for_self_assign_helper<'tcx>(
267            typeck_results: &'tcx ty::TypeckResults<'tcx>,
268            lhs: &'tcx hir::Expr<'tcx>,
269            rhs: &'tcx hir::Expr<'tcx>,
270        ) -> bool {
271            match (&lhs.kind, &rhs.kind) {
272                (hir::ExprKind::Path(qpath_l), hir::ExprKind::Path(qpath_r)) => {
273                    if let (Res::Local(id_l), Res::Local(id_r)) = (
274                        typeck_results.qpath_res(qpath_l, lhs.hir_id),
275                        typeck_results.qpath_res(qpath_r, rhs.hir_id),
276                    ) {
277                        if id_l == id_r {
278                            return true;
279                        }
280                    }
281                    return false;
282                }
283                (hir::ExprKind::Field(lhs_l, ident_l), hir::ExprKind::Field(lhs_r, ident_r)) => {
284                    if ident_l == ident_r {
285                        return check_for_self_assign_helper(typeck_results, lhs_l, lhs_r);
286                    }
287                    return false;
288                }
289                _ => {
290                    return false;
291                }
292            }
293        }
294
295        if let hir::ExprKind::Assign(lhs, rhs, _) = assign.kind
296            && check_for_self_assign_helper(self.typeck_results(), lhs, rhs)
297            && !assign.span.from_expansion()
298        {
299            let is_field_assign = #[allow(non_exhaustive_omitted_patterns)] match lhs.kind {
    hir::ExprKind::Field(..) => true,
    _ => false,
}matches!(lhs.kind, hir::ExprKind::Field(..));
300            self.tcx.emit_node_span_lint(
301                DEAD_CODE,
302                assign.hir_id,
303                assign.span,
304                UselessAssignment { is_field_assign, ty: self.typeck_results().expr_ty(lhs) },
305            )
306        }
307    }
308
309    fn handle_field_pattern_match(
310        &mut self,
311        lhs: &hir::Pat<'_>,
312        res: Res,
313        pats: &[hir::PatField<'_>],
314    ) {
315        let variant = match self.typeck_results().node_type(lhs.hir_id).kind() {
316            ty::Adt(adt, _) => {
317                // Marks the ADT live if its variant appears as the pattern,
318                // considering cases when we have `let T(x) = foo()` and `fn foo<T>() -> T;`,
319                // we will lose the liveness info of `T` cause we cannot mark it live when visiting `foo`.
320                // Related issue: https://github.com/rust-lang/rust/issues/120770
321                self.check_def_id(adt.did());
322                adt.variant_of_res(res)
323            }
324            _ => bug_impl(Some(lhs.span), format_args!("non-ADT in struct pattern"),
    Location::caller())span_bug!(lhs.span, "non-ADT in struct pattern"),
325        };
326        for pat in pats {
327            if let PatKind::Wild = pat.pat.kind {
328                continue;
329            }
330            let index = self.typeck_results().field_index(pat.hir_id);
331            self.insert_def_id(variant.fields[index].did);
332        }
333    }
334
335    fn handle_tuple_field_pattern_match(
336        &mut self,
337        lhs: &hir::Pat<'_>,
338        res: Res,
339        pats: &[hir::Pat<'_>],
340        dotdot: hir::DotDotPos,
341    ) {
342        let variant = match self.typeck_results().node_type(lhs.hir_id).kind() {
343            ty::Adt(adt, _) => {
344                // Marks the ADT live if its variant appears as the pattern
345                self.check_def_id(adt.did());
346                adt.variant_of_res(res)
347            }
348            _ => {
349                self.tcx.dcx().span_delayed_bug(lhs.span, "non-ADT in tuple struct pattern");
350                return;
351            }
352        };
353        let dotdot = dotdot.as_opt_usize().unwrap_or(pats.len());
354        let first_n = pats.iter().enumerate().take(dotdot);
355        let missing = variant.fields.len() - pats.len();
356        let last_n = pats.iter().enumerate().skip(dotdot).map(|(idx, pat)| (idx + missing, pat));
357        for (idx, pat) in first_n.chain(last_n) {
358            if let PatKind::Wild = pat.kind {
359                continue;
360            }
361            self.insert_def_id(variant.fields[FieldIdx::from_usize(idx)].did);
362        }
363    }
364
365    fn handle_offset_of(&mut self, expr: &'tcx hir::Expr<'tcx>) {
366        let indices = self
367            .typeck_results()
368            .offset_of_data()
369            .get(expr.hir_id)
370            .expect("no offset_of_data for offset_of");
371
372        for &(current_ty, variant, field) in indices {
373            match current_ty.kind() {
374                ty::Adt(def, _) => {
375                    let field = &def.variant(variant).fields[field];
376                    self.insert_def_id(field.did);
377                }
378                // we don't need to mark tuple fields as live,
379                // but we may need to mark subfields
380                ty::Tuple(_) => {}
381                _ => bug_impl(Some(expr.span), format_args!("named field access on non-ADT"),
    Location::caller())span_bug!(expr.span, "named field access on non-ADT"),
382            }
383        }
384    }
385
386    fn mark_live_symbols(&mut self) -> <MarkSymbolVisitor<'tcx> as Visitor<'tcx>>::Result {
387        while let Some(work) = self.worklist.pop() {
388            let WorkItem { mut id, propagated, own } = work;
389            self.propagated_comes_from_allow_expect = propagated;
390
391            // in the case of tuple struct constructors we want to check the item,
392            // not the generated tuple struct constructor function
393            if let DefKind::Ctor(..) = self.tcx.def_kind(id) {
394                id = self.tcx.local_parent(id);
395            }
396
397            // When using `#[allow]` or `#[expect]` of `dead_code`, we do a QOL improvement
398            // by declaring fn calls, statics, ... within said items as live, as well as
399            // the item itself, although technically this is not the case.
400            //
401            // This means that the lint for said items will never be fired.
402            //
403            // This doesn't make any difference for the item declared with `#[allow]`, as
404            // the lint firing will be a nop, as it will be silenced by the `#[allow]` of
405            // the item.
406            //
407            // However, for `#[expect]`, the presence or absence of the lint is relevant,
408            // so we don't add it to the list of live symbols when it comes from a
409            // `#[expect]`. This means that we will correctly report an item as live or not
410            // for the `#[expect]` case.
411            //
412            // Note that an item can and will be duplicated on the worklist with different
413            // `ComesFromAllowExpect`, particularly if it was added from the
414            // `effective_visibilities` query or from the `#[allow]`/`#[expect]` checks,
415            // this "duplication" is essential as otherwise a function with `#[expect]`
416            // called from a `pub fn` may be falsely reported as not live, falsely
417            // triggering the `unfulfilled_lint_expectations` lint.
418            match own {
419                ComesFromAllowExpect::Yes => {}
420                ComesFromAllowExpect::No => {
421                    self.live_symbols.insert(id);
422                }
423            }
424
425            if !self.scanned.insert((id, propagated)) {
426                continue;
427            } else if propagated == ComesFromAllowExpect::No {
428                // If the item is not coming from an `#[allow]` or `#[expect]`,
429                // we also mark it as scanned with `ComesFromAllowExpect::Yes`
430                // to avoid re-scanning it in the future.
431                self.scanned.insert((id, ComesFromAllowExpect::Yes));
432            }
433
434            // Avoid accessing the HIR for the synthesized associated type generated for RPITITs.
435            if self.tcx.is_impl_trait_in_trait(id.to_def_id()) {
436                self.live_symbols.insert(id);
437                continue;
438            }
439
440            self.visit_node(self.tcx.hir_node_by_def_id(id))?;
441        }
442
443        ControlFlow::Continue(())
444    }
445
446    /// Automatically generated items marked with `rustc_trivial_field_reads`
447    /// will be ignored for the purposes of dead code analysis (see PR #85200
448    /// for discussion).
449    fn should_ignore_impl_item(&mut self, impl_item: &hir::ImplItem<'_>) -> bool {
450        if let hir::ImplItemImplKind::Trait { .. } = impl_item.impl_kind
451            && let impl_of = self.tcx.local_parent(impl_item.owner_id.def_id)
452            && self.tcx.is_automatically_derived(impl_of.to_def_id())
453            && let trait_ref =
454                self.tcx.impl_trait_ref(impl_of).instantiate_identity().skip_norm_wip()
455            && {
        {
            'done:
                {
                for i in
                    ::rustc_attr_ir::HasAttrs::get_attrs(trait_ref.def_id,
                        &self.tcx) {
                    #[allow(unused_imports)]
                    use ::rustc_attr_ir::AttributeKind::*;
                    let i: &::rustc_attr_ir::Attribute = i;
                    match i {
                        ::rustc_attr_ir::Attribute::Parsed(RustcTrivialFieldReads)
                            => {
                            break 'done Some(());
                        }
                        ::rustc_attr_ir::Attribute::Unparsed(..) =>
                            {}
                            #[deny(unreachable_patterns)]
                            _ => {}
                    }
                }
                None
            }
        }
    }.is_some()find_attr!(self.tcx, trait_ref.def_id, RustcTrivialFieldReads)
456        {
457            if let ty::Adt(adt_def, _) = trait_ref.self_ty().kind()
458                && let Some(adt_def_id) = adt_def.did().as_local()
459            {
460                self.ignored_derived_traits.entry(adt_def_id).or_default().insert(trait_ref.def_id);
461            }
462            return true;
463        }
464
465        false
466    }
467
468    fn visit_node(
469        &mut self,
470        node: Node<'tcx>,
471    ) -> <MarkSymbolVisitor<'tcx> as Visitor<'tcx>>::Result {
472        if let Node::ImplItem(impl_item) = node
473            && self.should_ignore_impl_item(impl_item)
474        {
475            return ControlFlow::Continue(());
476        }
477
478        let unconditionally_treated_fields_as_live =
479            self.repr_unconditionally_treats_fields_as_live;
480        let had_repr_simd_or_scalable = self.repr_has_repr_simd_or_scalable;
481        self.repr_unconditionally_treats_fields_as_live = false;
482        self.repr_has_repr_simd_or_scalable = false;
483        let walk_result = match node {
484            Node::Item(item) => match item.kind {
485                hir::ItemKind::Struct(..) | hir::ItemKind::Union(..) => {
486                    let def = self.tcx.adt_def(item.owner_id);
487                    self.repr_unconditionally_treats_fields_as_live =
488                        def.repr().c() || def.repr().transparent();
489                    self.repr_has_repr_simd_or_scalable =
490                        def.repr().simd() || def.repr().scalable();
491
492                    intravisit::walk_item(self, item)
493                }
494                hir::ItemKind::ForeignMod { .. } => ControlFlow::Continue(()),
495                hir::ItemKind::Trait { items: trait_item_refs, .. } => {
496                    // mark assoc ty live if the trait is live
497                    for trait_item in trait_item_refs {
498                        if self.tcx.def_kind(trait_item.owner_id) == DefKind::AssocTy {
499                            self.check_def_id(trait_item.owner_id.to_def_id());
500                        }
501                    }
502                    intravisit::walk_item(self, item)
503                }
504                _ => intravisit::walk_item(self, item),
505            },
506            Node::TraitItem(trait_item) => {
507                // mark the trait live
508                let trait_item_id = trait_item.owner_id.to_def_id();
509                if let Some(trait_id) = self.tcx.trait_of_assoc(trait_item_id) {
510                    self.check_def_id(trait_id);
511                }
512                intravisit::walk_trait_item(self, trait_item)
513            }
514            Node::ImplItem(impl_item) => {
515                let item = self.tcx.local_parent(impl_item.owner_id.def_id);
516                if let hir::ImplItemImplKind::Inherent { .. } = impl_item.impl_kind {
517                    //// If it's a type whose items are live, then it's live, too.
518                    //// This is done to handle the case where, for example, the static
519                    //// method of a private type is used, but the type itself is never
520                    //// called directly.
521                    let self_ty = self.tcx.type_of(item).instantiate_identity().skip_norm_wip();
522                    match *self_ty.kind() {
523                        ty::Adt(def, _) => self.check_def_id(def.did()),
524                        ty::Foreign(did) => self.check_def_id(did),
525                        ty::Dynamic(data, ..) => {
526                            if let Some(def_id) = data.principal_def_id() {
527                                self.check_def_id(def_id)
528                            }
529                        }
530                        _ => {}
531                    }
532                }
533                intravisit::walk_impl_item(self, impl_item)
534            }
535            Node::ForeignItem(foreign_item) => intravisit::walk_foreign_item(self, foreign_item),
536            Node::OpaqueTy(opaq) => intravisit::walk_opaque_ty(self, opaq),
537            _ => ControlFlow::Continue(()),
538        };
539        self.repr_has_repr_simd_or_scalable = had_repr_simd_or_scalable;
540        self.repr_unconditionally_treats_fields_as_live = unconditionally_treated_fields_as_live;
541
542        walk_result
543    }
544
545    fn mark_as_used_if_union(&mut self, adt: ty::AdtDef<'tcx>, fields: &[hir::ExprField<'_>]) {
546        if adt.is_union() && adt.non_enum_variant().fields.len() > 1 && adt.did().is_local() {
547            for field in fields {
548                let index = self.typeck_results().field_index(field.hir_id);
549                self.insert_def_id(adt.non_enum_variant().fields[index].did);
550            }
551        }
552    }
553
554    /// Returns whether `local_def_id` is potentially alive or not.
555    /// `local_def_id` points to an impl or an impl item,
556    /// both impl and impl item that may be passed to this function are of a trait,
557    /// and added into the unsolved_items during `create_and_seed_worklist`
558    fn check_impl_or_impl_item_live(
559        &self,
560        local_def_id: LocalDefId,
561        defer_seeds_come_from_allow: bool,
562    ) -> ImplItemCheckResult {
563        let (impl_block_id, trait_def_id) = match self.tcx.def_kind(local_def_id) {
564            // assoc impl items of traits are live if the corresponding trait items are live
565            DefKind::AssocConst | DefKind::AssocTy | DefKind::AssocFn => {
566                let trait_def_id =
567                    self.tcx.trait_item_of(local_def_id).and_then(|def_id| def_id.as_local());
568                (self.tcx.local_parent(local_def_id), trait_def_id)
569            }
570            // impl items are live if the corresponding traits are live
571            DefKind::Impl { of_trait: true } => {
572                (local_def_id, self.tcx.impl_trait_id(local_def_id).as_local())
573            }
574            _ => bug_impl(None, format_args!("impossible case reached"), Location::caller())bug!(),
575        };
576
577        let mut trait_comes_from_allow = None;
578        if let Some(trait_def_id) = trait_def_id {
579            if defer_seeds_come_from_allow {
580                if !self.live_symbols.contains(&trait_def_id) {
581                    return ImplItemCheckResult::Dead { require: trait_def_id };
582                }
583            } else {
584                trait_comes_from_allow = has_allow_dead_code_or_lang_attr(self.tcx, trait_def_id);
585
586                if !self.live_symbols.contains(&trait_def_id) {
587                    return match trait_comes_from_allow {
588                        Some(comes_from_allow) => ImplItemCheckResult::Live(comes_from_allow),
589                        None => ImplItemCheckResult::Dead { require: trait_def_id },
590                    };
591                }
592            }
593        }
594
595        // The impl or impl item is used if the corresponding trait or trait item is used and the ty is used.
596        if let ty::Adt(adt, _) =
597            self.tcx.type_of(impl_block_id).instantiate_identity().skip_norm_wip().kind()
598            && let Some(adt_def_id) = adt.did().as_local()
599            && !self.live_symbols.contains(&adt_def_id)
600        {
601            if defer_seeds_come_from_allow {
602                return ImplItemCheckResult::Dead { require: adt_def_id };
603            }
604
605            return match trait_comes_from_allow {
606                Some(comes_from_allow) => ImplItemCheckResult::Live(comes_from_allow),
607                None => ImplItemCheckResult::Dead { require: adt_def_id },
608            };
609        }
610
611        ImplItemCheckResult::Live(ComesFromAllowExpect::No)
612    }
613
614    fn collect_live_items_from_unsolved_items(
615        &mut self,
616        defer_seeds_come_from_allow: bool,
617        unsolved_items: Vec<LocalDefId>,
618        unsolved_map: &mut FxHashMap<LocalDefId, Vec<LocalDefId>>,
619    ) -> Vec<(LocalDefId, ComesFromAllowExpect)> {
620        let mut items_to_check = ::alloc::vec::Vec::new()vec![];
621
622        for def_id in unsolved_items {
623            match self.check_impl_or_impl_item_live(def_id, defer_seeds_come_from_allow) {
624                ImplItemCheckResult::Live(comes_from_allow) => {
625                    items_to_check.push((def_id, comes_from_allow));
626                }
627                ImplItemCheckResult::Dead { require } => {
628                    unsolved_map.entry(require).or_default().push(def_id);
629                }
630            }
631        }
632        items_to_check
633    }
634
635    #[expect(
636        rustc::potential_query_instability,
637        reason = "The order of the unsolved items is not important, so we can just collect them into a vector."
638    )]
639    fn mark_live_symbols_and_ignored_derived_traits(
640        &mut self,
641        defer_seeds_come_from_allow: bool,
642    ) -> Result<(), ErrorGuaranteed> {
643        if let ControlFlow::Break(guar) = self.mark_live_symbols() {
644            return Err(guar);
645        }
646
647        // We have marked the primary seeds as live. We now need to process unsolved items from traits
648        // and trait impls: add them to the work list if the trait or the implemented type is live.
649        let unsolved_items = std::mem::take(&mut self.unsolved_items);
650        let mut unsolved_map = FxHashMap::default();
651        let mut items_to_check = self.collect_live_items_from_unsolved_items(
652            defer_seeds_come_from_allow,
653            unsolved_items,
654            &mut unsolved_map,
655        );
656
657        while !items_to_check.is_empty() {
658            self.worklist.extend(items_to_check.into_iter().map(|(id, comes_from_allow)| {
659                let own = if defer_seeds_come_from_allow {
660                    ComesFromAllowExpect::No
661                } else {
662                    has_allow_dead_code_or_lang_attr(self.tcx, id)
663                        .unwrap_or(ComesFromAllowExpect::No)
664                };
665
666                WorkItem { id, propagated: comes_from_allow, own }
667            }));
668            if let ControlFlow::Break(guar) = self.mark_live_symbols() {
669                return Err(guar);
670            }
671
672            let unsolved_items = unsolved_map
673                .extract_if(|require, _| self.live_symbols.contains(require))
674                .flat_map(|(_, items)| items)
675                .collect();
676
677            items_to_check = self.collect_live_items_from_unsolved_items(
678                defer_seeds_come_from_allow,
679                unsolved_items,
680                &mut unsolved_map,
681            );
682        }
683
684        self.unsolved_items = unsolved_map.into_values().flatten().collect();
685
686        Ok(())
687    }
688}
689
690impl<'tcx> Visitor<'tcx> for MarkSymbolVisitor<'tcx> {
691    type Result = ControlFlow<ErrorGuaranteed>;
692
693    fn visit_nested_body(&mut self, body: hir::BodyId) -> Self::Result {
694        let typeck_results = self.tcx.typeck_body(body);
695
696        // The result shouldn't be tainted, otherwise it will cause ICE.
697        if let Some(guar) = typeck_results.tainted_by_errors {
698            return ControlFlow::Break(guar);
699        }
700
701        let old_maybe_typeck_results = self.maybe_typeck_results.replace(typeck_results);
702        let body = self.tcx.hir_body(body);
703        let result = self.visit_body(body);
704        self.maybe_typeck_results = old_maybe_typeck_results;
705
706        result
707    }
708
709    fn visit_variant_data(&mut self, def: &'tcx hir::VariantData<'tcx>) -> Self::Result {
710        let tcx = self.tcx;
711        let unconditionally_treat_fields_as_live = self.repr_unconditionally_treats_fields_as_live;
712        let has_repr_simd_or_scalable = self.repr_has_repr_simd_or_scalable;
713        let effective_visibilities = &tcx.effective_visibilities(());
714        let live_fields = def.fields().iter().filter_map(|f| {
715            let def_id = f.def_id;
716            if unconditionally_treat_fields_as_live
717                || (f.is_positional() && has_repr_simd_or_scalable)
718            {
719                return Some(def_id);
720            }
721            if !effective_visibilities.is_reachable(f.hir_id.owner.def_id) {
722                return None;
723            }
724            if effective_visibilities.is_reachable(def_id) { Some(def_id) } else { None }
725        });
726        self.live_symbols.extend(live_fields);
727
728        intravisit::walk_struct_def(self, def)
729    }
730
731    fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) -> Self::Result {
732        match expr.kind {
733            hir::ExprKind::Path(ref qpath @ QPath::TypeRelative(..)) => {
734                let res = self.typeck_results().qpath_res(qpath, expr.hir_id);
735                self.handle_res(res);
736            }
737            hir::ExprKind::MethodCall(..) => {
738                self.lookup_and_handle_method(expr.hir_id);
739            }
740            hir::ExprKind::Field(ref lhs, ..) => {
741                if self.typeck_results().opt_field_index(expr.hir_id).is_some() {
742                    self.handle_field_access(lhs, expr.hir_id);
743                } else {
744                    self.tcx.dcx().span_delayed_bug(expr.span, "couldn't resolve index for field");
745                }
746            }
747            hir::ExprKind::Struct(qpath, fields, _) => {
748                let res = self.typeck_results().qpath_res(qpath, expr.hir_id);
749                self.handle_res(res);
750                if let ty::Adt(adt, _) = self.typeck_results().expr_ty(expr).kind() {
751                    self.mark_as_used_if_union(*adt, fields);
752                }
753            }
754            hir::ExprKind::Closure(cls) => {
755                self.insert_def_id(cls.def_id.to_def_id());
756            }
757            hir::ExprKind::OffsetOf(..) => {
758                self.handle_offset_of(expr);
759            }
760            hir::ExprKind::Assign(ref lhs, ..) => {
761                self.handle_assign(lhs);
762                self.check_for_self_assign(expr);
763            }
764            _ => (),
765        }
766
767        intravisit::walk_expr(self, expr)
768    }
769
770    fn visit_arm(&mut self, arm: &'tcx hir::Arm<'tcx>) -> Self::Result {
771        // Inside the body, ignore constructions of variants
772        // necessary for the pattern to match. Those construction sites
773        // can't be reached unless the variant is constructed elsewhere.
774        let len = self.ignore_variant_stack.len();
775        self.ignore_variant_stack.extend(arm.pat.necessary_variants());
776        let result = intravisit::walk_arm(self, arm);
777        self.ignore_variant_stack.truncate(len);
778
779        result
780    }
781
782    fn visit_pat(&mut self, pat: &'tcx hir::Pat<'tcx>) -> Self::Result {
783        self.in_pat = true;
784        match pat.kind {
785            PatKind::Struct(ref path, fields, _) => {
786                let res = self.typeck_results().qpath_res(path, pat.hir_id);
787                self.handle_field_pattern_match(pat, res, fields);
788            }
789            PatKind::TupleStruct(ref qpath, fields, dotdot) => {
790                let res = self.typeck_results().qpath_res(qpath, pat.hir_id);
791                self.handle_tuple_field_pattern_match(pat, res, fields, dotdot);
792            }
793            _ => (),
794        }
795
796        let result = intravisit::walk_pat(self, pat);
797        self.in_pat = false;
798
799        result
800    }
801
802    fn visit_pat_expr(&mut self, expr: &'tcx rustc_hir::PatExpr<'tcx>) -> Self::Result {
803        match &expr.kind {
804            rustc_hir::PatExprKind::Path(qpath) => {
805                // mark the type of variant live when meeting E::V in expr
806                if let ty::Adt(adt, _) = self.typeck_results().node_type(expr.hir_id).kind() {
807                    self.check_def_id(adt.did());
808                }
809
810                let res = self.typeck_results().qpath_res(qpath, expr.hir_id);
811                self.handle_res(res);
812            }
813            _ => {}
814        }
815        intravisit::walk_pat_expr(self, expr)
816    }
817
818    fn visit_path(&mut self, path: &hir::Path<'tcx>, _: hir::HirId) -> Self::Result {
819        self.handle_res(path.res);
820        intravisit::walk_path(self, path)
821    }
822
823    fn visit_anon_const(&mut self, c: &'tcx hir::AnonConst) -> Self::Result {
824        // When inline const blocks are used in pattern position, paths
825        // referenced by it should be considered as used.
826        let in_pat = mem::replace(&mut self.in_pat, false);
827
828        self.live_symbols.insert(c.def_id);
829        let result = intravisit::walk_anon_const(self, c);
830
831        self.in_pat = in_pat;
832
833        result
834    }
835
836    fn visit_inline_const(&mut self, c: &'tcx hir::ConstBlock) -> Self::Result {
837        // When inline const blocks are used in pattern position, paths
838        // referenced by it should be considered as used.
839        let in_pat = mem::replace(&mut self.in_pat, false);
840
841        self.live_symbols.insert(c.def_id);
842        let result = intravisit::walk_inline_const(self, c);
843
844        self.in_pat = in_pat;
845
846        result
847    }
848
849    fn visit_trait_ref(&mut self, t: &'tcx hir::TraitRef<'tcx>) -> Self::Result {
850        if let Some(trait_def_id) = t.path.res.opt_def_id()
851            && let Some(segment) = t.path.segments.last()
852            && let Some(args) = segment.args
853        {
854            for constraint in args.constraints {
855                if let Some(local_def_id) = self
856                    .tcx
857                    .associated_items(trait_def_id)
858                    .find_by_ident_and_kind(
859                        self.tcx,
860                        constraint.ident,
861                        AssocTag::Const,
862                        trait_def_id,
863                    )
864                    .and_then(|item| item.def_id.as_local())
865                {
866                    self.worklist.push(WorkItem {
867                        id: local_def_id,
868                        propagated: ComesFromAllowExpect::No,
869                        own: ComesFromAllowExpect::No,
870                    });
871                }
872            }
873        }
874
875        intravisit::walk_trait_ref(self, t)
876    }
877}
878
879fn has_allow_dead_code_or_lang_attr(
880    tcx: TyCtxt<'_>,
881    def_id: LocalDefId,
882) -> Option<ComesFromAllowExpect> {
883    fn has_allow_expect_dead_code(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool {
884        let hir_id = tcx.local_def_id_to_hir_id(def_id);
885        let lint_level = tcx.lint_level_spec_at_node(DEAD_CODE, hir_id).level();
886        #[allow(non_exhaustive_omitted_patterns)] match lint_level {
    lint::Allow | lint::Expect => true,
    _ => false,
}matches!(lint_level, lint::Allow | lint::Expect)
887    }
888
889    fn has_used_like_attr(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool {
890        tcx.def_kind(def_id).has_codegen_attrs() && {
891            let cg_attrs = tcx.codegen_fn_attrs(def_id);
892
893            // #[used], #[no_mangle], #[export_name], etc also keeps the item alive
894            // forcefully, e.g., for placing it in a specific section.
895            cg_attrs.contains_extern_indicator()
896                || cg_attrs.flags.contains(CodegenFnAttrFlags::USED_COMPILER)
897                || cg_attrs.flags.contains(CodegenFnAttrFlags::USED_LINKER)
898        }
899    }
900
901    if has_allow_expect_dead_code(tcx, def_id) {
902        Some(ComesFromAllowExpect::Yes)
903    } else if has_used_like_attr(tcx, def_id)
904        || {
        {
            'done:
                {
                for i in ::rustc_attr_ir::HasAttrs::get_attrs(def_id, &tcx) {
                    #[allow(unused_imports)]
                    use ::rustc_attr_ir::AttributeKind::*;
                    let i: &::rustc_attr_ir::Attribute = i;
                    match i {
                        ::rustc_attr_ir::Attribute::Parsed(Lang(..) |
                            RustcCanonicalSymbol) => {
                            break 'done Some(());
                        }
                        ::rustc_attr_ir::Attribute::Unparsed(..) =>
                            {}
                            #[deny(unreachable_patterns)]
                            _ => {}
                    }
                }
                None
            }
        }
    }.is_some()find_attr!(tcx, def_id, Lang(..) | RustcCanonicalSymbol)
905    {
906        Some(ComesFromAllowExpect::No)
907    } else {
908        None
909    }
910}
911
912/// Examine the given definition and record it in the worklist if it should be considered live.
913///
914/// We want to explicitly consider as live:
915/// * Item annotated with #[allow(dead_code)]
916///       This is done so that if we want to suppress warnings for a
917///       group of dead functions, we only have to annotate the "root".
918///       For example, if both `f` and `g` are dead and `f` calls `g`,
919///       then annotating `f` with `#[allow(dead_code)]` will suppress
920///       warning for both `f` and `g`.
921///
922/// * Item annotated with #[lang=".."]
923///       Lang items are always callable from elsewhere.
924///
925/// For trait methods and implementations of traits, we are not certain that the definitions are
926/// live at this stage. We record them in `unsolved_items` for later examination.
927fn maybe_record_as_seed<'tcx>(
928    tcx: TyCtxt<'tcx>,
929    owner_id: hir::OwnerId,
930    push_into_worklist: &mut impl FnMut(WorkItem),
931    unsolved_items: &mut Vec<LocalDefId>,
932) {
933    let allow_dead_code = has_allow_dead_code_or_lang_attr(tcx, owner_id.def_id);
934    if let Some(comes_from_allow) = allow_dead_code {
935        push_into_worklist(WorkItem {
936            id: owner_id.def_id,
937            propagated: comes_from_allow,
938            own: comes_from_allow,
939        });
940    }
941
942    match tcx.def_kind(owner_id) {
943        DefKind::Enum => {
944            if let Some(comes_from_allow) = allow_dead_code {
945                let adt = tcx.adt_def(owner_id);
946                for variant in adt.variants().iter() {
947                    push_into_worklist(WorkItem {
948                        id: variant.def_id.expect_local(),
949                        propagated: comes_from_allow,
950                        own: comes_from_allow,
951                    });
952                }
953            }
954        }
955        DefKind::AssocFn | DefKind::AssocConst | DefKind::AssocTy => {
956            if allow_dead_code.is_none() {
957                let parent = tcx.local_parent(owner_id.def_id);
958                match tcx.def_kind(parent) {
959                    DefKind::Impl { of_trait: false } | DefKind::Trait => {}
960                    DefKind::Impl { of_trait: true } => {
961                        // We only care about associated items of traits,
962                        // because they cannot be visited directly,
963                        // so we later mark them as live if their corresponding traits
964                        // or trait items and self types are both live,
965                        // but inherent associated items can be visited and marked directly.
966                        unsolved_items.push(owner_id.def_id);
967                    }
968                    _ => bug_impl(None, format_args!("impossible case reached"), Location::caller())bug!(),
969                }
970            }
971        }
972        DefKind::Impl { of_trait: true } if allow_dead_code.is_none() => {
973            unsolved_items.push(owner_id.def_id);
974        }
975        DefKind::GlobalAsm => {
976            // global_asm! is always live.
977            push_into_worklist(WorkItem {
978                id: owner_id.def_id,
979                propagated: ComesFromAllowExpect::No,
980                own: ComesFromAllowExpect::No,
981            });
982        }
983        DefKind::Const => {
984            if tcx.item_name(owner_id.def_id) == kw::Underscore {
985                // `const _` is always live, as that syntax only exists for the side effects
986                // of type checking and evaluating the constant expression, and marking them
987                // as dead code would defeat that purpose.
988                push_into_worklist(WorkItem {
989                    id: owner_id.def_id,
990                    propagated: ComesFromAllowExpect::No,
991                    own: ComesFromAllowExpect::No,
992                });
993            }
994        }
995        _ => {}
996    }
997}
998
999#[derive(#[automatically_derived]
impl ::core::default::Default for DeferredSeeds {
    #[inline]
    fn default() -> DeferredSeeds {
        DeferredSeeds {
            pub_reachables: ::core::default::Default::default(),
            come_from_allow: ::core::default::Default::default(),
        }
    }
}Default)]
1000struct DeferredSeeds {
1001    pub_reachables: Vec<WorkItem>,
1002    come_from_allow: Vec<WorkItem>,
1003}
1004
1005struct SeedWorklists {
1006    worklist: Vec<WorkItem>,
1007    deferred_seeds: DeferredSeeds,
1008    unsolved_items: Vec<LocalDefId>,
1009}
1010
1011fn create_and_seed_worklist(tcx: TyCtxt<'_>) -> SeedWorklists {
1012    let mut unsolved_items = Vec::new();
1013    let mut deferred_seeds = DeferredSeeds::default();
1014    let mut worklist = Vec::new();
1015
1016    if let Some((def_id, _)) = tcx.entry_fn(())
1017        && let Some(local_def_id) = def_id.as_local()
1018    {
1019        worklist.push(WorkItem {
1020            id: local_def_id,
1021            propagated: ComesFromAllowExpect::No,
1022            own: ComesFromAllowExpect::No,
1023        });
1024    }
1025
1026    // Under `--test`, what `main` resolves to is the would-be entry point of a normal build,
1027    // so keep it live, unless a stripped user `#[rustc_main]` would have been the entry instead.
1028    if tcx.sess.is_test_crate()
1029        && !tcx.sess.removed_rustc_main_attr.load(Ordering::Relaxed)
1030        && let Some(main_def) = tcx.resolutions(()).main_def
1031        && let Some(def_id) = main_def.opt_fn_def_id()
1032        && let Some(local_def_id) = def_id.as_local()
1033    {
1034        worklist.push(WorkItem {
1035            id: local_def_id,
1036            propagated: ComesFromAllowExpect::No,
1037            own: ComesFromAllowExpect::No,
1038        });
1039    }
1040
1041    for (id, effective_vis) in tcx.effective_visibilities(()).iter() {
1042        if effective_vis.is_public_at_level(Level::Reachable) {
1043            deferred_seeds.pub_reachables.push(WorkItem {
1044                id: *id,
1045                propagated: ComesFromAllowExpect::No,
1046                own: ComesFromAllowExpect::No,
1047            });
1048        }
1049    }
1050
1051    let mut push_into_worklist = |work_item: WorkItem| match work_item.own {
1052        ComesFromAllowExpect::Yes => deferred_seeds.come_from_allow.push(work_item),
1053        ComesFromAllowExpect::No => worklist.push(work_item),
1054    };
1055    let crate_items = tcx.hir_crate_items(());
1056    for id in crate_items.owners() {
1057        maybe_record_as_seed(tcx, id, &mut push_into_worklist, &mut unsolved_items);
1058    }
1059
1060    SeedWorklists { worklist, deferred_seeds, unsolved_items }
1061}
1062
1063fn live_symbols_and_ignored_derived_traits(
1064    tcx: TyCtxt<'_>,
1065    (): (),
1066) -> Result<DeadCodeLivenessSummary, ErrorGuaranteed> {
1067    let SeedWorklists { worklist, deferred_seeds, unsolved_items } = create_and_seed_worklist(tcx);
1068    let mut symbol_visitor = MarkSymbolVisitor {
1069        worklist,
1070        tcx,
1071        maybe_typeck_results: None,
1072        scanned: Default::default(),
1073        live_symbols: Default::default(),
1074        repr_unconditionally_treats_fields_as_live: false,
1075        repr_has_repr_simd_or_scalable: false,
1076        in_pat: false,
1077        ignore_variant_stack: ::alloc::vec::Vec::new()vec![],
1078        ignored_derived_traits: Default::default(),
1079        propagated_comes_from_allow_expect: ComesFromAllowExpect::No,
1080        unsolved_items,
1081    };
1082    symbol_visitor.mark_live_symbols_and_ignored_derived_traits(true)?;
1083    let pre_deferred_seeding = DeadCodeLivenessSnapshot {
1084        live_symbols: symbol_visitor.live_symbols.clone(),
1085        ignored_derived_traits: symbol_visitor.ignored_derived_traits.clone(),
1086    };
1087
1088    if !deferred_seeds.pub_reachables.is_empty() {
1089        symbol_visitor.worklist.extend(deferred_seeds.pub_reachables);
1090        symbol_visitor.mark_live_symbols_and_ignored_derived_traits(true)?;
1091    }
1092
1093    if !deferred_seeds.come_from_allow.is_empty() {
1094        symbol_visitor.worklist.extend(deferred_seeds.come_from_allow);
1095        symbol_visitor.mark_live_symbols_and_ignored_derived_traits(false)?;
1096    }
1097
1098    Ok(DeadCodeLivenessSummary {
1099        pre_deferred_seeding,
1100        final_result: DeadCodeLivenessSnapshot {
1101            live_symbols: symbol_visitor.live_symbols,
1102            ignored_derived_traits: symbol_visitor.ignored_derived_traits,
1103        },
1104    })
1105}
1106
1107struct DeadItem {
1108    def_id: LocalDefId,
1109    name: Symbol,
1110    level_plus: (lint::Level, Option<StableLintExpectationId>),
1111}
1112
1113struct DeadVisitor<'tcx> {
1114    tcx: TyCtxt<'tcx>,
1115    target_lint: &'static Lint,
1116    live_symbols: &'tcx LocalDefIdSet,
1117    ignored_derived_traits: &'tcx LocalDefIdMap<FxIndexSet<DefId>>,
1118}
1119
1120enum ShouldWarnAboutField {
1121    Yes,
1122    No,
1123}
1124
1125#[derive(#[automatically_derived]
impl ::core::fmt::Debug for ReportOn {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                ReportOn::TupleField => "TupleField",
                ReportOn::NamedField => "NamedField",
            })
    }
}Debug, #[automatically_derived]
impl ::core::marker::Copy for ReportOn { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for ReportOn { }
#[automatically_derived]
impl ::core::clone::Clone for ReportOn {
    #[inline]
    fn clone(&self) -> ReportOn { *self }
}Clone, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for ReportOn { }
#[automatically_derived]
impl ::core::cmp::PartialEq for ReportOn {
    #[inline]
    fn eq(&self, other: &ReportOn) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for ReportOn { }Eq)]
1126enum ReportOn {
1127    /// Report on something that hasn't got a proper name to refer to
1128    TupleField,
1129    /// Report on something that has got a name, which could be a field but also a method
1130    NamedField,
1131}
1132
1133impl<'tcx> DeadVisitor<'tcx> {
1134    fn should_warn_about_field(&mut self, field: &ty::FieldDef) -> ShouldWarnAboutField {
1135        if self.live_symbols.contains(&field.did.expect_local()) {
1136            return ShouldWarnAboutField::No;
1137        }
1138        let field_type = self.tcx.type_of(field.did).instantiate_identity().skip_norm_wip();
1139        if field_type.is_phantom_data() {
1140            return ShouldWarnAboutField::No;
1141        }
1142        let is_positional = field.name.as_str().starts_with(|c: char| c.is_ascii_digit());
1143        if is_positional
1144            && self
1145                .tcx
1146                .layout_of(
1147                    ty::TypingEnv::non_body_analysis(self.tcx, field.did)
1148                        .as_query_input(field_type),
1149                )
1150                .map_or(true, |layout| layout.is_zst())
1151        {
1152            return ShouldWarnAboutField::No;
1153        }
1154        ShouldWarnAboutField::Yes
1155    }
1156
1157    fn def_lint_level_plus(
1158        &self,
1159        id: LocalDefId,
1160    ) -> (lint::Level, Option<StableLintExpectationId>) {
1161        let hir_id = self.tcx.local_def_id_to_hir_id(id);
1162        let level_spec = self.tcx.lint_level_spec_at_node(self.target_lint, hir_id);
1163        (level_spec.level(), level_spec.lint_id())
1164    }
1165
1166    fn dead_code_pub_in_binary_note(&self) -> Option<DeadCodePubInBinaryNote> {
1167        self.target_lint.name.eq(DEAD_CODE_PUB_IN_BINARY.name).then_some(DeadCodePubInBinaryNote)
1168    }
1169
1170    // # Panics
1171    // All `dead_codes` must have the same lint level, otherwise we will intentionally ICE.
1172    // This is because we emit a multi-spanned lint using the lint level of the `dead_codes`'s
1173    // first local def id.
1174    // Prefer calling `Self.warn_dead_code` or `Self.warn_dead_code_grouped_by_lint_level`
1175    // since those methods group by lint level before calling this method.
1176    fn lint_at_single_level(
1177        &self,
1178        dead_codes: &[&DeadItem],
1179        participle: &str,
1180        parent_item: Option<LocalDefId>,
1181        report_on: ReportOn,
1182    ) {
1183        let Some(&first_item) = dead_codes.first() else { return };
1184        let tcx = self.tcx;
1185
1186        let first_lint_level_plus = first_item.level_plus;
1187        if !dead_codes.iter().skip(1).all(|item|
                item.level_plus == first_lint_level_plus) {
    ::core::panicking::panic("assertion failed: dead_codes.iter().skip(1).all(|item| item.level_plus == first_lint_level_plus)")
};assert!(dead_codes.iter().skip(1).all(|item| item.level_plus == first_lint_level_plus));
1188
1189        let names: Vec<_> = dead_codes.iter().map(|item| item.name).collect();
1190        let spans: Vec<_> = dead_codes
1191            .iter()
1192            .map(|item| {
1193                let span = tcx.def_span(item.def_id);
1194                let ident_span = tcx.def_ident_span(item.def_id);
1195                // FIXME(cjgillot) this SyntaxContext manipulation does not make any sense.
1196                ident_span.map(|s| s.with_ctxt(span.ctxt())).unwrap_or(span)
1197            })
1198            .collect();
1199
1200        let mut descr = tcx.def_descr(first_item.def_id.to_def_id());
1201        // `impl` blocks are "batched" and (unlike other batching) might
1202        // contain different kinds of associated items.
1203        if dead_codes.iter().any(|item| tcx.def_descr(item.def_id.to_def_id()) != descr) {
1204            descr = "associated item"
1205        }
1206
1207        let num = dead_codes.len();
1208        let multiple = num > 6;
1209        let name_list = names.into();
1210
1211        let parent_info = parent_item.map(|parent_item| {
1212            let parent_descr = tcx.def_descr(parent_item.to_def_id());
1213            let span = if let DefKind::Impl { .. } = tcx.def_kind(parent_item) {
1214                tcx.def_span(parent_item)
1215            } else {
1216                tcx.def_ident_span(parent_item).unwrap()
1217            };
1218            ParentInfo { num, descr, parent_descr, span }
1219        });
1220
1221        let mut encl_def_id = parent_item.unwrap_or(first_item.def_id);
1222        // `ignored_derived_traits` is computed for the enum, not for the variants.
1223        if let DefKind::Variant = tcx.def_kind(encl_def_id) {
1224            encl_def_id = tcx.local_parent(encl_def_id);
1225        }
1226
1227        let ignored_derived_impls =
1228            self.ignored_derived_traits.get(&encl_def_id).map(|ign_traits| {
1229                let trait_list = ign_traits
1230                    .iter()
1231                    .map(|trait_id| self.tcx.item_name(*trait_id))
1232                    .collect::<Vec<_>>();
1233                let trait_list_len = trait_list.len();
1234                IgnoredDerivedImpls {
1235                    name: self.tcx.item_name(encl_def_id.to_def_id()),
1236                    trait_list: trait_list.into(),
1237                    trait_list_len,
1238                }
1239            });
1240
1241        let diag = match report_on {
1242            ReportOn::TupleField => {
1243                let tuple_fields = if let Some(parent_id) = parent_item
1244                    && let node = tcx.hir_node_by_def_id(parent_id)
1245                    && let hir::Node::Item(hir::Item {
1246                        kind: hir::ItemKind::Struct(_, _, hir::VariantData::Tuple(fields, _, _)),
1247                        ..
1248                    }) = node
1249                {
1250                    *fields
1251                } else {
1252                    &[]
1253                };
1254
1255                let trailing_tuple_fields = if tuple_fields.len() >= dead_codes.len() {
1256                    LocalDefIdSet::from_iter(
1257                        tuple_fields
1258                            .iter()
1259                            .skip(tuple_fields.len() - dead_codes.len())
1260                            .map(|f| f.def_id),
1261                    )
1262                } else {
1263                    LocalDefIdSet::default()
1264                };
1265
1266                let fields_suggestion =
1267                    // Suggest removal if all tuple fields are at the end.
1268                    // Otherwise suggest removal or changing to unit type
1269                    if dead_codes.iter().all(|dc| trailing_tuple_fields.contains(&dc.def_id)) {
1270                        ChangeFields::Remove { num }
1271                    } else {
1272                        ChangeFields::ChangeToUnitTypeOrRemove { num, spans: spans.clone() }
1273                    };
1274
1275                MultipleDeadCodes::UnusedTupleStructFields {
1276                    multiple,
1277                    num,
1278                    descr,
1279                    participle,
1280                    name_list,
1281                    dead_code_pub_in_binary_note: self.dead_code_pub_in_binary_note(),
1282                    change_fields_suggestion: fields_suggestion,
1283                    parent_info,
1284                    ignored_derived_impls,
1285                }
1286            }
1287            ReportOn::NamedField => {
1288                let enum_variants_with_same_name = dead_codes
1289                    .iter()
1290                    .filter_map(|dead_item| {
1291                        if let DefKind::AssocFn | DefKind::AssocConst =
1292                            tcx.def_kind(dead_item.def_id)
1293                            && let impl_did = tcx.local_parent(dead_item.def_id)
1294                            && let DefKind::Impl { of_trait: false } = tcx.def_kind(impl_did)
1295                            && let ty::Adt(maybe_enum, _) =
1296                                tcx.type_of(impl_did).instantiate_identity().skip_norm_wip().kind()
1297                            && maybe_enum.is_enum()
1298                            && let Some(variant) =
1299                                maybe_enum.variants().iter().find(|i| i.name == dead_item.name)
1300                        {
1301                            Some(crate::diagnostics::EnumVariantSameName {
1302                                dead_descr: tcx.def_descr(dead_item.def_id.to_def_id()),
1303                                dead_name: dead_item.name,
1304                                variant_span: tcx.def_span(variant.def_id),
1305                            })
1306                        } else {
1307                            None
1308                        }
1309                    })
1310                    .collect();
1311
1312                MultipleDeadCodes::DeadCodes {
1313                    multiple,
1314                    num,
1315                    descr,
1316                    participle,
1317                    name_list,
1318                    dead_code_pub_in_binary_note: self.dead_code_pub_in_binary_note(),
1319                    parent_info,
1320                    ignored_derived_impls,
1321                    enum_variants_with_same_name,
1322                }
1323            }
1324        };
1325
1326        let hir_id = tcx.local_def_id_to_hir_id(first_item.def_id);
1327        self.tcx.emit_node_span_lint(self.target_lint, hir_id, MultiSpan::from_spans(spans), diag);
1328    }
1329
1330    fn warn_multiple(
1331        &self,
1332        def_id: LocalDefId,
1333        participle: &str,
1334        dead_codes: Vec<DeadItem>,
1335        report_on: ReportOn,
1336    ) {
1337        let mut dead_codes = dead_codes
1338            .iter()
1339            .filter(|v| !v.name.as_str().starts_with('_'))
1340            .collect::<Vec<&DeadItem>>();
1341        if dead_codes.is_empty() {
1342            return;
1343        }
1344        // FIXME: `dead_codes` should probably be morally equivalent to
1345        // `IndexMap<(Level, StableLintExpectationId), (DefId, Symbol)>`
1346        dead_codes.sort_by_key(|v| v.level_plus.0);
1347        for group in dead_codes.chunk_by(|a, b| a.level_plus == b.level_plus) {
1348            self.lint_at_single_level(&group, participle, Some(def_id), report_on);
1349        }
1350    }
1351
1352    fn warn_dead_code(&mut self, id: LocalDefId, participle: &str) {
1353        let item = DeadItem {
1354            def_id: id,
1355            name: self.tcx.item_name(id.to_def_id()),
1356            level_plus: self.def_lint_level_plus(id),
1357        };
1358        self.lint_at_single_level(&[&item], participle, None, ReportOn::NamedField);
1359    }
1360
1361    fn check_definition(&mut self, def_id: LocalDefId) {
1362        if self.is_live_code(def_id) {
1363            return;
1364        }
1365        match self.tcx.def_kind(def_id) {
1366            DefKind::AssocConst
1367            | DefKind::AssocTy
1368            | DefKind::AssocFn
1369            | DefKind::Fn
1370            | DefKind::Static { .. }
1371            | DefKind::Const
1372            | DefKind::TyAlias
1373            | DefKind::Enum
1374            | DefKind::Union
1375            | DefKind::ForeignTy
1376            | DefKind::Trait => self.warn_dead_code(def_id, "used"),
1377            DefKind::Struct => self.warn_dead_code(def_id, "constructed"),
1378            DefKind::Variant | DefKind::Field => bug_impl(None, format_args!("should be handled specially"),
    Location::caller())bug!("should be handled specially"),
1379            _ => {}
1380        }
1381    }
1382
1383    fn is_live_code(&self, def_id: LocalDefId) -> bool {
1384        // if we cannot get a name for the item, then we just assume that it is
1385        // live. I mean, we can't really emit a lint.
1386        let Some(name) = self.tcx.opt_item_name(def_id.to_def_id()) else {
1387            return true;
1388        };
1389
1390        self.live_symbols.contains(&def_id) || name.as_str().starts_with('_')
1391    }
1392}
1393
1394fn check_mod_deathness(tcx: TyCtxt<'_>, module: LocalModId) {
1395    let Ok(DeadCodeLivenessSummary { pre_deferred_seeding, final_result }) =
1396        tcx.live_symbols_and_ignored_derived_traits(()).as_ref()
1397    else {
1398        return;
1399    };
1400
1401    let module_items = tcx.hir_module_items(module);
1402
1403    if tcx.crate_types().contains(&CrateType::Executable) {
1404        let is_unused_pub = |def_id: LocalDefId| {
1405            tcx.effective_visibilities(()).is_public_at_level(def_id, Level::Reachable)
1406                && !pre_deferred_seeding.live_symbols.contains(&def_id)
1407        };
1408
1409        lint_dead_codes(
1410            tcx,
1411            DEAD_CODE_PUB_IN_BINARY,
1412            module,
1413            &pre_deferred_seeding.live_symbols,
1414            &pre_deferred_seeding.ignored_derived_traits,
1415            module_items.free_items().filter(|free_item| is_unused_pub(free_item.owner_id.def_id)),
1416            module_items
1417                .foreign_items()
1418                .filter(|foreign_item| is_unused_pub(foreign_item.owner_id.def_id)),
1419        );
1420    }
1421
1422    lint_dead_codes(
1423        tcx,
1424        DEAD_CODE,
1425        module,
1426        &final_result.live_symbols,
1427        &final_result.ignored_derived_traits,
1428        module_items.free_items(),
1429        module_items.foreign_items(),
1430    );
1431}
1432
1433fn lint_dead_codes<'tcx>(
1434    tcx: TyCtxt<'tcx>,
1435    target_lint: &'static Lint,
1436    module: LocalModId,
1437    live_symbols: &'tcx LocalDefIdSet,
1438    ignored_derived_traits: &'tcx LocalDefIdMap<FxIndexSet<DefId>>,
1439    free_items: impl Iterator<Item = ItemId>,
1440    foreign_items: impl Iterator<Item = ForeignItemId>,
1441) {
1442    let mut visitor = DeadVisitor { tcx, target_lint, live_symbols, ignored_derived_traits };
1443    for item in free_items {
1444        let def_kind = tcx.def_kind(item.owner_id);
1445
1446        let mut dead_codes = Vec::new();
1447        // Only diagnose unused assoc items in inherent impl and used trait,
1448        // for unused assoc items in impls of trait,
1449        // we have diagnosed them in the trait if they are unused,
1450        // for unused assoc items in unused trait,
1451        // we have diagnosed the unused trait.
1452        if def_kind == (DefKind::Impl { of_trait: false })
1453            || (def_kind == DefKind::Trait && live_symbols.contains(&item.owner_id.def_id))
1454        {
1455            for &def_id in tcx.associated_item_def_ids(item.owner_id.def_id) {
1456                if let Some(local_def_id) = def_id.as_local()
1457                    && !visitor.is_live_code(local_def_id)
1458                {
1459                    let name = tcx.item_name(def_id);
1460                    let level_plus = visitor.def_lint_level_plus(local_def_id);
1461                    dead_codes.push(DeadItem { def_id: local_def_id, name, level_plus });
1462                }
1463            }
1464        }
1465        if !dead_codes.is_empty() {
1466            visitor.warn_multiple(item.owner_id.def_id, "used", dead_codes, ReportOn::NamedField);
1467        }
1468
1469        if !live_symbols.contains(&item.owner_id.def_id) {
1470            let parent = tcx.local_parent(item.owner_id.def_id);
1471            if parent != module.to_local_def_id() && !live_symbols.contains(&parent) {
1472                // We already have diagnosed something.
1473                continue;
1474            }
1475            visitor.check_definition(item.owner_id.def_id);
1476            continue;
1477        }
1478
1479        if let DefKind::Struct | DefKind::Union | DefKind::Enum = def_kind {
1480            let adt = tcx.adt_def(item.owner_id);
1481            let mut dead_variants = Vec::new();
1482
1483            for variant in adt.variants() {
1484                let def_id = variant.def_id.expect_local();
1485                if !live_symbols.contains(&def_id) {
1486                    // Record to group diagnostics.
1487                    let level_plus = visitor.def_lint_level_plus(def_id);
1488                    dead_variants.push(DeadItem { def_id, name: variant.name, level_plus });
1489                    continue;
1490                }
1491
1492                let is_positional = variant.fields.raw.first().is_some_and(|field| {
1493                    field.name.as_str().starts_with(|c: char| c.is_ascii_digit())
1494                });
1495                let report_on =
1496                    if is_positional { ReportOn::TupleField } else { ReportOn::NamedField };
1497                let dead_fields = variant
1498                    .fields
1499                    .iter()
1500                    .filter_map(|field| {
1501                        let def_id = field.did.expect_local();
1502                        if let ShouldWarnAboutField::Yes = visitor.should_warn_about_field(field) {
1503                            let level_plus = visitor.def_lint_level_plus(def_id);
1504                            Some(DeadItem { def_id, name: field.name, level_plus })
1505                        } else {
1506                            None
1507                        }
1508                    })
1509                    .collect();
1510                visitor.warn_multiple(def_id, "read", dead_fields, report_on);
1511            }
1512
1513            visitor.warn_multiple(
1514                item.owner_id.def_id,
1515                "constructed",
1516                dead_variants,
1517                ReportOn::NamedField,
1518            );
1519        }
1520    }
1521
1522    for foreign_item in foreign_items {
1523        visitor.check_definition(foreign_item.owner_id.def_id);
1524    }
1525}
1526
1527pub(crate) fn provide(providers: &mut Providers) {
1528    *providers =
1529        Providers { live_symbols_and_ignored_derived_traits, check_mod_deathness, ..*providers };
1530}