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.
5 use rustc::hir::map::Map;
6 use rustc::middle::codegen_fn_attrs::CodegenFnAttrFlags;
7 use rustc::middle::privacy;
8 use rustc::ty::{self, DefIdTree, TyCtxt};
9 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
11 use rustc_hir::def::{CtorOf, DefKind, Res};
12 use rustc_hir::def_id::{DefId, LOCAL_CRATE};
13 use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor};
14 use rustc_hir::itemlikevisit::ItemLikeVisitor;
15 use rustc_hir::{Node, PatKind, TyKind};
16 use rustc_session::lint;
18 use rustc_span::symbol::sym;
19 use syntax::{ast, attr};
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<'_>, hir_id: hir::HirId) -> bool {
26 match tcx.hir().find(hir_id) {
28 | Some(Node::ImplItem(..))
29 | Some(Node::ForeignItem(..))
30 | Some(Node::TraitItem(..))
31 | Some(Node::Variant(..))
32 | Some(Node::AnonConst(..))
33 | Some(Node::Pat(..)) => true,
38 struct MarkSymbolVisitor<'a, 'tcx> {
39 worklist: Vec<hir::HirId>,
41 tables: &'a ty::TypeckTables<'tcx>,
42 live_symbols: FxHashSet<hir::HirId>,
43 repr_has_repr_c: bool,
45 inherited_pub_visibility: bool,
46 ignore_variant_stack: Vec<DefId>,
47 // maps from tuple struct constructors to tuple struct items
48 struct_constructors: FxHashMap<hir::HirId, hir::HirId>,
51 impl<'a, 'tcx> MarkSymbolVisitor<'a, 'tcx> {
52 fn check_def_id(&mut self, def_id: DefId) {
53 if let Some(hir_id) = self.tcx.hir().as_local_hir_id(def_id) {
54 if should_explore(self.tcx, hir_id) || self.struct_constructors.contains_key(&hir_id) {
55 self.worklist.push(hir_id);
57 self.live_symbols.insert(hir_id);
61 fn insert_def_id(&mut self, def_id: DefId) {
62 if let Some(hir_id) = self.tcx.hir().as_local_hir_id(def_id) {
63 debug_assert!(!should_explore(self.tcx, hir_id));
64 self.live_symbols.insert(hir_id);
68 fn handle_res(&mut self, res: Res) {
70 Res::Def(DefKind::Const, _)
71 | Res::Def(DefKind::AssocConst, _)
72 | Res::Def(DefKind::TyAlias, _) => {
73 self.check_def_id(res.def_id());
75 _ if self.in_pat => {}
76 Res::PrimTy(..) | Res::SelfCtor(..) | Res::Local(..) => {}
77 Res::Def(DefKind::Ctor(CtorOf::Variant, ..), ctor_def_id) => {
78 let variant_id = self.tcx.parent(ctor_def_id).unwrap();
79 let enum_id = self.tcx.parent(variant_id).unwrap();
80 self.check_def_id(enum_id);
81 if !self.ignore_variant_stack.contains(&ctor_def_id) {
82 self.check_def_id(variant_id);
85 Res::Def(DefKind::Variant, variant_id) => {
86 let enum_id = self.tcx.parent(variant_id).unwrap();
87 self.check_def_id(enum_id);
88 if !self.ignore_variant_stack.contains(&variant_id) {
89 self.check_def_id(variant_id);
92 Res::SelfTy(t, i) => {
100 Res::ToolMod | Res::NonMacroAttr(..) | Res::Err => {}
102 self.check_def_id(res.def_id());
107 fn lookup_and_handle_method(&mut self, id: hir::HirId) {
108 if let Some(def_id) = self.tables.type_dependent_def_id(id) {
109 self.check_def_id(def_id);
111 bug!("no type-dependent def for method");
115 fn handle_field_access(&mut self, lhs: &hir::Expr<'_>, hir_id: hir::HirId) {
116 match self.tables.expr_ty_adjusted(lhs).kind {
118 let index = self.tcx.field_index(hir_id, self.tables);
119 self.insert_def_id(def.non_enum_variant().fields[index].did);
122 _ => span_bug!(lhs.span, "named field access on non-ADT"),
126 fn handle_field_pattern_match(
130 pats: &[hir::FieldPat<'_>],
132 let variant = match self.tables.node_type(lhs.hir_id).kind {
133 ty::Adt(adt, _) => adt.variant_of_res(res),
134 _ => span_bug!(lhs.span, "non-ADT in struct pattern"),
137 if let PatKind::Wild = pat.pat.kind {
140 let index = self.tcx.field_index(pat.hir_id, self.tables);
141 self.insert_def_id(variant.fields[index].did);
145 fn mark_live_symbols(&mut self) {
146 let mut scanned = FxHashSet::default();
147 while let Some(id) = self.worklist.pop() {
148 if !scanned.insert(id) {
152 // in the case of tuple struct constructors we want to check the item, not the generated
153 // tuple struct constructor function
154 let id = self.struct_constructors.get(&id).cloned().unwrap_or(id);
156 if let Some(node) = self.tcx.hir().find(id) {
157 self.live_symbols.insert(id);
158 self.visit_node(node);
163 fn visit_node(&mut self, node: Node<'tcx>) {
164 let had_repr_c = self.repr_has_repr_c;
165 self.repr_has_repr_c = false;
166 let had_inherited_pub_visibility = self.inherited_pub_visibility;
167 self.inherited_pub_visibility = false;
169 Node::Item(item) => match item.kind {
170 hir::ItemKind::Struct(..) | hir::ItemKind::Union(..) => {
171 let def_id = self.tcx.hir().local_def_id(item.hir_id);
172 let def = self.tcx.adt_def(def_id);
173 self.repr_has_repr_c = def.repr.c();
175 intravisit::walk_item(self, &item);
177 hir::ItemKind::Enum(..) => {
178 self.inherited_pub_visibility = item.vis.node.is_pub();
180 intravisit::walk_item(self, &item);
182 hir::ItemKind::ForeignMod(..) => {}
184 intravisit::walk_item(self, &item);
187 Node::TraitItem(trait_item) => {
188 intravisit::walk_trait_item(self, trait_item);
190 Node::ImplItem(impl_item) => {
191 intravisit::walk_impl_item(self, impl_item);
193 Node::ForeignItem(foreign_item) => {
194 intravisit::walk_foreign_item(self, &foreign_item);
198 self.repr_has_repr_c = had_repr_c;
199 self.inherited_pub_visibility = had_inherited_pub_visibility;
202 fn mark_as_used_if_union(&mut self, adt: &ty::AdtDef, fields: &[hir::Field<'_>]) {
203 if adt.is_union() && adt.non_enum_variant().fields.len() > 1 && adt.did.is_local() {
204 for field in fields {
205 let index = self.tcx.field_index(field.hir_id, self.tables);
206 self.insert_def_id(adt.non_enum_variant().fields[index].did);
212 impl<'a, 'tcx> Visitor<'tcx> for MarkSymbolVisitor<'a, 'tcx> {
213 type Map = Map<'tcx>;
215 fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<'_, Self::Map> {
216 NestedVisitorMap::None
219 fn visit_nested_body(&mut self, body: hir::BodyId) {
220 let old_tables = self.tables;
221 self.tables = self.tcx.body_tables(body);
222 let body = self.tcx.hir().body(body);
223 self.visit_body(body);
224 self.tables = old_tables;
227 fn visit_variant_data(
229 def: &'tcx hir::VariantData<'tcx>,
231 _: &hir::Generics<'_>,
235 let has_repr_c = self.repr_has_repr_c;
236 let inherited_pub_visibility = self.inherited_pub_visibility;
237 let live_fields = def
240 .filter(|f| has_repr_c || inherited_pub_visibility || f.vis.node.is_pub());
241 self.live_symbols.extend(live_fields.map(|f| f.hir_id));
243 intravisit::walk_struct_def(self, def);
246 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
248 hir::ExprKind::Path(ref qpath @ hir::QPath::TypeRelative(..)) => {
249 let res = self.tables.qpath_res(qpath, expr.hir_id);
250 self.handle_res(res);
252 hir::ExprKind::MethodCall(..) => {
253 self.lookup_and_handle_method(expr.hir_id);
255 hir::ExprKind::Field(ref lhs, ..) => {
256 self.handle_field_access(&lhs, expr.hir_id);
258 hir::ExprKind::Struct(_, ref fields, _) => {
259 if let ty::Adt(ref adt, _) = self.tables.expr_ty(expr).kind {
260 self.mark_as_used_if_union(adt, fields);
266 intravisit::walk_expr(self, expr);
269 fn visit_arm(&mut self, arm: &'tcx hir::Arm<'tcx>) {
270 // Inside the body, ignore constructions of variants
271 // necessary for the pattern to match. Those construction sites
272 // can't be reached unless the variant is constructed elsewhere.
273 let len = self.ignore_variant_stack.len();
274 self.ignore_variant_stack.extend(arm.pat.necessary_variants());
275 intravisit::walk_arm(self, arm);
276 self.ignore_variant_stack.truncate(len);
279 fn visit_pat(&mut self, pat: &'tcx hir::Pat<'tcx>) {
281 PatKind::Struct(ref path, ref fields, _) => {
282 let res = self.tables.qpath_res(path, pat.hir_id);
283 self.handle_field_pattern_match(pat, res, fields);
285 PatKind::Path(ref qpath) => {
286 let res = self.tables.qpath_res(qpath, pat.hir_id);
287 self.handle_res(res);
293 intravisit::walk_pat(self, pat);
297 fn visit_path(&mut self, path: &'tcx hir::Path<'tcx>, _: hir::HirId) {
298 self.handle_res(path.res);
299 intravisit::walk_path(self, path);
302 fn visit_ty(&mut self, ty: &'tcx hir::Ty<'tcx>) {
304 TyKind::Def(item_id, _) => {
305 let item = self.tcx.hir().expect_item(item_id.id);
306 intravisit::walk_item(self, item);
310 intravisit::walk_ty(self, ty);
313 fn visit_anon_const(&mut self, c: &'tcx hir::AnonConst) {
314 self.live_symbols.insert(c.hir_id);
315 intravisit::walk_anon_const(self, c);
319 fn has_allow_dead_code_or_lang_attr(
322 attrs: &[ast::Attribute],
324 if attr::contains_name(attrs, sym::lang) {
328 // Stable attribute for #[lang = "panic_impl"]
329 if attr::contains_name(attrs, sym::panic_handler) {
333 // (To be) stable attribute for #[lang = "oom"]
334 if attr::contains_name(attrs, sym::alloc_error_handler) {
338 let def_id = tcx.hir().local_def_id(id);
339 let cg_attrs = tcx.codegen_fn_attrs(def_id);
341 // #[used], #[no_mangle], #[export_name], etc also keeps the item alive
342 // forcefully, e.g., for placing it in a specific section.
343 if cg_attrs.contains_extern_indicator() || cg_attrs.flags.contains(CodegenFnAttrFlags::USED) {
347 tcx.lint_level_at_node(lint::builtin::DEAD_CODE, id).0 == lint::Allow
350 // This visitor seeds items that
351 // 1) We want to explicitly consider as live:
352 // * Item annotated with #[allow(dead_code)]
353 // - This is done so that if we want to suppress warnings for a
354 // group of dead functions, we only have to annotate the "root".
355 // For example, if both `f` and `g` are dead and `f` calls `g`,
356 // then annotating `f` with `#[allow(dead_code)]` will suppress
357 // warning for both `f` and `g`.
358 // * Item annotated with #[lang=".."]
359 // - This is because lang items are always callable from elsewhere.
361 // 2) We are not sure to be live or not
362 // * Implementation of a trait method
363 struct LifeSeeder<'k, 'tcx> {
364 worklist: Vec<hir::HirId>,
365 krate: &'k hir::Crate<'k>,
367 // see `MarkSymbolVisitor::struct_constructors`
368 struct_constructors: FxHashMap<hir::HirId, hir::HirId>,
371 impl<'v, 'k, 'tcx> ItemLikeVisitor<'v> for LifeSeeder<'k, 'tcx> {
372 fn visit_item(&mut self, item: &hir::Item<'_>) {
373 let allow_dead_code = has_allow_dead_code_or_lang_attr(self.tcx, item.hir_id, &item.attrs);
375 self.worklist.push(item.hir_id);
378 hir::ItemKind::Enum(ref enum_def, _) => {
380 self.worklist.extend(enum_def.variants.iter().map(|variant| variant.id));
383 for variant in enum_def.variants {
384 if let Some(ctor_hir_id) = variant.data.ctor_hir_id() {
385 self.struct_constructors.insert(ctor_hir_id, variant.id);
389 hir::ItemKind::Trait(.., trait_item_refs) => {
390 for trait_item_ref in trait_item_refs {
391 let trait_item = self.krate.trait_item(trait_item_ref.id);
392 match trait_item.kind {
393 hir::TraitItemKind::Const(_, Some(_))
394 | hir::TraitItemKind::Method(_, hir::TraitMethod::Provided(_)) => {
395 if has_allow_dead_code_or_lang_attr(
400 self.worklist.push(trait_item.hir_id);
407 hir::ItemKind::Impl { ref of_trait, items, .. } => {
408 for impl_item_ref in items {
409 let impl_item = self.krate.impl_item(impl_item_ref.id);
410 if of_trait.is_some()
411 || has_allow_dead_code_or_lang_attr(
417 self.worklist.push(impl_item_ref.id.hir_id);
421 hir::ItemKind::Struct(ref variant_data, _) => {
422 if let Some(ctor_hir_id) = variant_data.ctor_hir_id() {
423 self.struct_constructors.insert(ctor_hir_id, item.hir_id);
430 fn visit_trait_item(&mut self, _item: &hir::TraitItem<'_>) {
431 // ignore: we are handling this in `visit_item` above
434 fn visit_impl_item(&mut self, _item: &hir::ImplItem<'_>) {
435 // ignore: we are handling this in `visit_item` above
439 fn create_and_seed_worklist<'tcx>(
441 access_levels: &privacy::AccessLevels,
442 krate: &hir::Crate<'_>,
443 ) -> (Vec<hir::HirId>, FxHashMap<hir::HirId, hir::HirId>) {
444 let worklist = access_levels
449 if level >= &privacy::AccessLevel::Reachable { Some(id) } else { None }
454 tcx.entry_fn(LOCAL_CRATE).map(|(def_id, _)| tcx.hir().as_local_hir_id(def_id).unwrap()),
456 .collect::<Vec<_>>();
458 // Seed implemented trait items
459 let mut life_seeder =
460 LifeSeeder { worklist, krate, tcx, struct_constructors: Default::default() };
461 krate.visit_all_item_likes(&mut life_seeder);
463 (life_seeder.worklist, life_seeder.struct_constructors)
468 access_levels: &privacy::AccessLevels,
469 krate: &hir::Crate<'_>,
470 ) -> FxHashSet<hir::HirId> {
471 let (worklist, struct_constructors) = create_and_seed_worklist(tcx, access_levels, krate);
472 let mut symbol_visitor = MarkSymbolVisitor {
475 tables: &ty::TypeckTables::empty(None),
476 live_symbols: Default::default(),
477 repr_has_repr_c: false,
479 inherited_pub_visibility: false,
480 ignore_variant_stack: vec![],
483 symbol_visitor.mark_live_symbols();
484 symbol_visitor.live_symbols
487 struct DeadVisitor<'tcx> {
489 live_symbols: FxHashSet<hir::HirId>,
492 impl DeadVisitor<'tcx> {
493 fn should_warn_about_item(&mut self, item: &hir::Item<'_>) -> bool {
494 let should_warn = match item.kind {
495 hir::ItemKind::Static(..)
496 | hir::ItemKind::Const(..)
497 | hir::ItemKind::Fn(..)
498 | hir::ItemKind::TyAlias(..)
499 | hir::ItemKind::Enum(..)
500 | hir::ItemKind::Struct(..)
501 | hir::ItemKind::Union(..) => true,
504 should_warn && !self.symbol_is_live(item.hir_id)
507 fn should_warn_about_field(&mut self, field: &hir::StructField<'_>) -> bool {
508 let field_type = self.tcx.type_of(self.tcx.hir().local_def_id(field.hir_id));
509 !field.is_positional()
510 && !self.symbol_is_live(field.hir_id)
511 && !field_type.is_phantom_data()
512 && !has_allow_dead_code_or_lang_attr(self.tcx, field.hir_id, &field.attrs)
515 fn should_warn_about_variant(&mut self, variant: &hir::Variant<'_>) -> bool {
516 !self.symbol_is_live(variant.id)
517 && !has_allow_dead_code_or_lang_attr(self.tcx, variant.id, &variant.attrs)
520 fn should_warn_about_foreign_item(&mut self, fi: &hir::ForeignItem<'_>) -> bool {
521 !self.symbol_is_live(fi.hir_id)
522 && !has_allow_dead_code_or_lang_attr(self.tcx, fi.hir_id, &fi.attrs)
525 // id := HIR id of an item's definition.
526 fn symbol_is_live(&mut self, id: hir::HirId) -> bool {
527 if self.live_symbols.contains(&id) {
530 // If it's a type whose items are live, then it's live, too.
531 // This is done to handle the case where, for example, the static
532 // method of a private type is used, but the type itself is never
534 let def_id = self.tcx.hir().local_def_id(id);
535 let inherent_impls = self.tcx.inherent_impls(def_id);
536 for &impl_did in inherent_impls.iter() {
537 for &item_did in &self.tcx.associated_item_def_ids(impl_did)[..] {
538 if let Some(item_hir_id) = self.tcx.hir().as_local_hir_id(item_did) {
539 if self.live_symbols.contains(&item_hir_id) {
551 span: rustc_span::Span,
556 if !name.as_str().starts_with("_") {
558 lint::builtin::DEAD_CODE,
561 &format!("{} is never {}: `{}`", node_type, participle, name),
567 impl Visitor<'tcx> for DeadVisitor<'tcx> {
568 type Map = Map<'tcx>;
570 /// Walk nested items in place so that we don't report dead-code
571 /// on inner functions when the outer function is already getting
572 /// an error. We could do this also by checking the parents, but
573 /// this is how the code is setup and it seems harmless enough.
574 fn nested_visit_map(&mut self) -> NestedVisitorMap<'_, Self::Map> {
575 NestedVisitorMap::All(&self.tcx.hir())
578 fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
579 if self.should_warn_about_item(item) {
580 // For most items, we want to highlight its identifier
581 let span = match item.kind {
582 hir::ItemKind::Fn(..)
583 | hir::ItemKind::Mod(..)
584 | hir::ItemKind::Enum(..)
585 | hir::ItemKind::Struct(..)
586 | hir::ItemKind::Union(..)
587 | hir::ItemKind::Trait(..)
588 | hir::ItemKind::Impl { .. } => {
589 // FIXME(66095): Because item.span is annotated with things
590 // like expansion data, and ident.span isn't, we use the
591 // def_span method if it's part of a macro invocation
592 // (and thus has asource_callee set).
593 // We should probably annotate ident.span with the macro
594 // context, but that's a larger change.
595 if item.span.source_callee().is_some() {
596 self.tcx.sess.source_map().def_span(item.span)
603 let participle = match item.kind {
604 hir::ItemKind::Struct(..) => "constructed", // Issue #52325
611 item.kind.descriptive_variant(),
615 // Only continue if we didn't warn
616 intravisit::walk_item(self, item);
622 variant: &'tcx hir::Variant<'tcx>,
623 g: &'tcx hir::Generics<'tcx>,
626 if self.should_warn_about_variant(&variant) {
635 intravisit::walk_variant(self, variant, g, id);
639 fn visit_foreign_item(&mut self, fi: &'tcx hir::ForeignItem<'tcx>) {
640 if self.should_warn_about_foreign_item(fi) {
645 fi.kind.descriptive_variant(),
649 intravisit::walk_foreign_item(self, fi);
652 fn visit_struct_field(&mut self, field: &'tcx hir::StructField<'tcx>) {
653 if self.should_warn_about_field(&field) {
654 self.warn_dead_code(field.hir_id, field.span, field.ident.name, "field", "read");
656 intravisit::walk_struct_field(self, field);
659 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
660 match impl_item.kind {
661 hir::ImplItemKind::Const(_, body_id) => {
662 if !self.symbol_is_live(impl_item.hir_id) {
666 impl_item.ident.name,
671 self.visit_nested_body(body_id)
673 hir::ImplItemKind::Method(_, body_id) => {
674 if !self.symbol_is_live(impl_item.hir_id) {
675 let span = self.tcx.sess.source_map().def_span(impl_item.span);
679 impl_item.ident.name,
684 self.visit_nested_body(body_id)
686 hir::ImplItemKind::OpaqueTy(..) | hir::ImplItemKind::TyAlias(..) => {}
690 // Overwrite so that we don't warn the trait item itself.
691 fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>) {
692 match trait_item.kind {
693 hir::TraitItemKind::Const(_, Some(body_id))
694 | hir::TraitItemKind::Method(_, hir::TraitMethod::Provided(body_id)) => {
695 self.visit_nested_body(body_id)
697 hir::TraitItemKind::Const(_, None)
698 | hir::TraitItemKind::Method(_, hir::TraitMethod::Required(_))
699 | hir::TraitItemKind::Type(..) => {}
704 pub fn check_crate(tcx: TyCtxt<'_>) {
705 let access_levels = &tcx.privacy_access_levels(LOCAL_CRATE);
706 let krate = tcx.hir().krate();
707 let live_symbols = find_live(tcx, access_levels, krate);
708 let mut visitor = DeadVisitor { tcx, live_symbols };
709 intravisit::walk_crate(&mut visitor, krate);