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.
6 use rustc::hir::{self, PatKind, TyKind};
7 use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap};
8 use rustc::hir::itemlikevisit::ItemLikeVisitor;
10 use rustc::hir::def::{CtorOf, Res, DefKind};
11 use rustc::hir::CodegenFnAttrFlags;
12 use rustc::hir::def_id::{DefId, LOCAL_CRATE};
14 use rustc::middle::privacy;
15 use rustc::ty::{self, DefIdTree, TyCtxt};
16 use rustc::util::nodemap::FxHashSet;
18 use rustc_data_structures::fx::FxHashMap;
20 use syntax::{ast, attr};
21 use syntax::symbol::sym;
24 // Any local node that may call something in its body block should be
25 // explored. For example, if it's a live Node::Item that is a
26 // function, then we should explore its block to check for codes that
27 // may need to be marked as live.
28 fn should_explore(tcx: TyCtxt<'_>, hir_id: hir::HirId) -> bool {
29 match tcx.hir().find(hir_id) {
30 Some(Node::Item(..)) |
31 Some(Node::ImplItem(..)) |
32 Some(Node::ForeignItem(..)) |
33 Some(Node::TraitItem(..)) |
34 Some(Node::Variant(..)) |
35 Some(Node::AnonConst(..)) |
36 Some(Node::Pat(..)) => true,
41 struct MarkSymbolVisitor<'a, 'tcx> {
42 worklist: Vec<hir::HirId>,
44 tables: &'a ty::TypeckTables<'tcx>,
45 live_symbols: FxHashSet<hir::HirId>,
46 repr_has_repr_c: bool,
48 inherited_pub_visibility: bool,
49 ignore_variant_stack: Vec<DefId>,
50 // maps from tuple struct constructors to tuple struct items
51 struct_constructors: FxHashMap<hir::HirId, hir::HirId>,
54 impl<'a, 'tcx> MarkSymbolVisitor<'a, 'tcx> {
55 fn check_def_id(&mut self, def_id: DefId) {
56 if let Some(hir_id) = self.tcx.hir().as_local_hir_id(def_id) {
57 if should_explore(self.tcx, hir_id) || self.struct_constructors.contains_key(&hir_id) {
58 self.worklist.push(hir_id);
60 self.live_symbols.insert(hir_id);
64 fn insert_def_id(&mut self, def_id: DefId) {
65 if let Some(hir_id) = self.tcx.hir().as_local_hir_id(def_id) {
66 debug_assert!(!should_explore(self.tcx, hir_id));
67 self.live_symbols.insert(hir_id);
71 fn handle_res(&mut self, res: Res) {
73 Res::Def(DefKind::Const, _)
74 | Res::Def(DefKind::AssocConst, _)
75 | Res::Def(DefKind::TyAlias, _) => {
76 self.check_def_id(res.def_id());
78 _ if self.in_pat => {},
79 Res::PrimTy(..) | Res::SelfCtor(..) |
81 Res::Def(DefKind::Ctor(CtorOf::Variant, ..), ctor_def_id) => {
82 let variant_id = self.tcx.parent(ctor_def_id).unwrap();
83 let enum_id = self.tcx.parent(variant_id).unwrap();
84 self.check_def_id(enum_id);
85 if !self.ignore_variant_stack.contains(&ctor_def_id) {
86 self.check_def_id(variant_id);
89 Res::Def(DefKind::Variant, variant_id) => {
90 let enum_id = self.tcx.parent(variant_id).unwrap();
91 self.check_def_id(enum_id);
92 if !self.ignore_variant_stack.contains(&variant_id) {
93 self.check_def_id(variant_id);
96 Res::SelfTy(t, i) => {
101 self.check_def_id(i);
104 Res::ToolMod | Res::NonMacroAttr(..) | Res::Err => {}
106 self.check_def_id(res.def_id());
111 fn lookup_and_handle_method(&mut self, id: hir::HirId) {
112 if let Some(def_id) = self.tables.type_dependent_def_id(id) {
113 self.check_def_id(def_id);
115 bug!("no type-dependent def for method");
119 fn handle_field_access(&mut self, lhs: &hir::Expr, hir_id: hir::HirId) {
120 match self.tables.expr_ty_adjusted(lhs).kind {
122 let index = self.tcx.field_index(hir_id, self.tables);
123 self.insert_def_id(def.non_enum_variant().fields[index].did);
126 _ => span_bug!(lhs.span, "named field access on non-ADT"),
130 fn handle_field_pattern_match(&mut self, lhs: &hir::Pat, res: Res, pats: &[hir::FieldPat]) {
131 let variant = match self.tables.node_type(lhs.hir_id).kind {
132 ty::Adt(adt, _) => adt.variant_of_res(res),
133 _ => span_bug!(lhs.span, "non-ADT in struct pattern")
136 if let PatKind::Wild = pat.pat.kind {
139 let index = self.tcx.field_index(pat.hir_id, self.tables);
140 self.insert_def_id(variant.fields[index].did);
144 fn mark_live_symbols(&mut self) {
145 let mut scanned = FxHashSet::default();
146 while let Some(id) = self.worklist.pop() {
147 if !scanned.insert(id) {
151 // in the case of tuple struct constructors we want to check the item, not the generated
152 // tuple struct constructor function
153 let id = self.struct_constructors.get(&id).cloned().unwrap_or(id);
155 if let Some(node) = self.tcx.hir().find(id) {
156 self.live_symbols.insert(id);
157 self.visit_node(node);
162 fn visit_node(&mut self, node: Node<'tcx>) {
163 let had_repr_c = self.repr_has_repr_c;
164 self.repr_has_repr_c = false;
165 let had_inherited_pub_visibility = self.inherited_pub_visibility;
166 self.inherited_pub_visibility = false;
168 Node::Item(item) => {
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);
188 Node::TraitItem(trait_item) => {
189 intravisit::walk_trait_item(self, trait_item);
191 Node::ImplItem(impl_item) => {
192 intravisit::walk_impl_item(self, impl_item);
194 Node::ForeignItem(foreign_item) => {
195 intravisit::walk_foreign_item(self, &foreign_item);
199 self.repr_has_repr_c = had_repr_c;
200 self.inherited_pub_visibility = had_inherited_pub_visibility;
203 fn mark_as_used_if_union(&mut self, adt: &ty::AdtDef, fields: &hir::HirVec<hir::Field>) {
204 if adt.is_union() && adt.non_enum_variant().fields.len() > 1 && adt.did.is_local() {
205 for field in fields {
206 let index = self.tcx.field_index(field.hir_id, self.tables);
207 self.insert_def_id(adt.non_enum_variant().fields[index].did);
213 impl<'a, 'tcx> Visitor<'tcx> for MarkSymbolVisitor<'a, 'tcx> {
214 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
215 NestedVisitorMap::None
218 fn visit_nested_body(&mut self, body: hir::BodyId) {
219 let old_tables = self.tables;
220 self.tables = self.tcx.body_tables(body);
221 let body = self.tcx.hir().body(body);
222 self.visit_body(body);
223 self.tables = old_tables;
226 fn visit_variant_data(&mut self, def: &'tcx hir::VariantData, _: ast::Name,
227 _: &hir::Generics, _: hir::HirId, _: syntax_pos::Span) {
228 let has_repr_c = self.repr_has_repr_c;
229 let inherited_pub_visibility = self.inherited_pub_visibility;
230 let live_fields = def.fields().iter().filter(|f| {
231 has_repr_c || inherited_pub_visibility || f.vis.node.is_pub()
233 self.live_symbols.extend(live_fields.map(|f| f.hir_id));
235 intravisit::walk_struct_def(self, def);
238 fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
240 hir::ExprKind::Path(ref qpath @ hir::QPath::TypeRelative(..)) => {
241 let res = self.tables.qpath_res(qpath, expr.hir_id);
242 self.handle_res(res);
244 hir::ExprKind::MethodCall(..) => {
245 self.lookup_and_handle_method(expr.hir_id);
247 hir::ExprKind::Field(ref lhs, ..) => {
248 self.handle_field_access(&lhs, expr.hir_id);
250 hir::ExprKind::Struct(_, ref fields, _) => {
251 if let ty::Adt(ref adt, _) = self.tables.expr_ty(expr).kind {
252 self.mark_as_used_if_union(adt, fields);
258 intravisit::walk_expr(self, expr);
261 fn visit_arm(&mut self, arm: &'tcx hir::Arm) {
262 // Inside the body, ignore constructions of variants
263 // necessary for the pattern to match. Those construction sites
264 // can't be reached unless the variant is constructed elsewhere.
265 let len = self.ignore_variant_stack.len();
266 self.ignore_variant_stack.extend(arm.pat.necessary_variants());
267 intravisit::walk_arm(self, arm);
268 self.ignore_variant_stack.truncate(len);
271 fn visit_pat(&mut self, pat: &'tcx hir::Pat) {
273 PatKind::Struct(ref path, ref fields, _) => {
274 let res = self.tables.qpath_res(path, pat.hir_id);
275 self.handle_field_pattern_match(pat, res, fields);
277 PatKind::Path(ref qpath) => {
278 let res = self.tables.qpath_res(qpath, pat.hir_id);
279 self.handle_res(res);
285 intravisit::walk_pat(self, pat);
289 fn visit_path(&mut self, path: &'tcx hir::Path, _: hir::HirId) {
290 self.handle_res(path.res);
291 intravisit::walk_path(self, path);
294 fn visit_ty(&mut self, ty: &'tcx hir::Ty) {
296 TyKind::Def(item_id, _) => {
297 let item = self.tcx.hir().expect_item(item_id.id);
298 intravisit::walk_item(self, item);
302 intravisit::walk_ty(self, ty);
305 fn visit_anon_const(&mut self, c: &'tcx hir::AnonConst) {
306 self.live_symbols.insert(c.hir_id);
307 intravisit::walk_anon_const(self, c);
311 fn has_allow_dead_code_or_lang_attr(
314 attrs: &[ast::Attribute],
316 if attr::contains_name(attrs, sym::lang) {
320 // Stable attribute for #[lang = "panic_impl"]
321 if attr::contains_name(attrs, sym::panic_handler) {
325 // (To be) stable attribute for #[lang = "oom"]
326 if attr::contains_name(attrs, sym::alloc_error_handler) {
330 let def_id = tcx.hir().local_def_id(id);
331 let cg_attrs = tcx.codegen_fn_attrs(def_id);
333 // #[used], #[no_mangle], #[export_name], etc also keeps the item alive
334 // forcefully, e.g., for placing it in a specific section.
335 if cg_attrs.contains_extern_indicator() ||
336 cg_attrs.flags.contains(CodegenFnAttrFlags::USED) {
340 tcx.lint_level_at_node(lint::builtin::DEAD_CODE, id).0 == lint::Allow
343 // This visitor seeds items that
344 // 1) We want to explicitly consider as live:
345 // * Item annotated with #[allow(dead_code)]
346 // - This is done so that if we want to suppress warnings for a
347 // group of dead functions, we only have to annotate the "root".
348 // For example, if both `f` and `g` are dead and `f` calls `g`,
349 // then annotating `f` with `#[allow(dead_code)]` will suppress
350 // warning for both `f` and `g`.
351 // * Item annotated with #[lang=".."]
352 // - This is because lang items are always callable from elsewhere.
354 // 2) We are not sure to be live or not
355 // * Implementation of a trait method
356 struct LifeSeeder<'k, 'tcx> {
357 worklist: Vec<hir::HirId>,
358 krate: &'k hir::Crate,
360 // see `MarkSymbolVisitor::struct_constructors`
361 struct_constructors: FxHashMap<hir::HirId, hir::HirId>,
364 impl<'v, 'k, 'tcx> ItemLikeVisitor<'v> for LifeSeeder<'k, 'tcx> {
365 fn visit_item(&mut self, item: &hir::Item) {
366 let allow_dead_code = has_allow_dead_code_or_lang_attr(self.tcx,
370 self.worklist.push(item.hir_id);
373 hir::ItemKind::Enum(ref enum_def, _) => {
375 self.worklist.extend(enum_def.variants.iter().map(|variant| variant.id));
378 for variant in &enum_def.variants {
379 if let Some(ctor_hir_id) = variant.data.ctor_hir_id() {
380 self.struct_constructors.insert(ctor_hir_id, variant.id);
384 hir::ItemKind::Trait(.., ref trait_item_refs) => {
385 for trait_item_ref in trait_item_refs {
386 let trait_item = self.krate.trait_item(trait_item_ref.id);
387 match trait_item.kind {
388 hir::TraitItemKind::Const(_, Some(_)) |
389 hir::TraitItemKind::Method(_, hir::TraitMethod::Provided(_)) => {
390 if has_allow_dead_code_or_lang_attr(self.tcx,
393 self.worklist.push(trait_item.hir_id);
400 hir::ItemKind::Impl(.., ref opt_trait, _, ref impl_item_refs) => {
401 for impl_item_ref in impl_item_refs {
402 let impl_item = self.krate.impl_item(impl_item_ref.id);
403 if opt_trait.is_some() ||
404 has_allow_dead_code_or_lang_attr(self.tcx,
407 self.worklist.push(impl_item_ref.id.hir_id);
411 hir::ItemKind::Struct(ref variant_data, _) => {
412 if let Some(ctor_hir_id) = variant_data.ctor_hir_id() {
413 self.struct_constructors.insert(ctor_hir_id, item.hir_id);
420 fn visit_trait_item(&mut self, _item: &hir::TraitItem) {
421 // ignore: we are handling this in `visit_item` above
424 fn visit_impl_item(&mut self, _item: &hir::ImplItem) {
425 // ignore: we are handling this in `visit_item` above
429 fn create_and_seed_worklist<'tcx>(
431 access_levels: &privacy::AccessLevels,
433 ) -> (Vec<hir::HirId>, FxHashMap<hir::HirId, hir::HirId>) {
434 let worklist = access_levels.map.iter().filter_map(|(&id, level)| {
435 if level >= &privacy::AccessLevel::Reachable {
442 tcx.entry_fn(LOCAL_CRATE).map(|(def_id, _)| tcx.hir().as_local_hir_id(def_id).unwrap())
443 ).collect::<Vec<_>>();
445 // Seed implemented trait items
446 let mut life_seeder = LifeSeeder {
450 struct_constructors: Default::default(),
452 krate.visit_all_item_likes(&mut life_seeder);
454 (life_seeder.worklist, life_seeder.struct_constructors)
459 access_levels: &privacy::AccessLevels,
461 ) -> FxHashSet<hir::HirId> {
462 let (worklist, struct_constructors) = create_and_seed_worklist(tcx, access_levels, krate);
463 let mut symbol_visitor = MarkSymbolVisitor {
466 tables: &ty::TypeckTables::empty(None),
467 live_symbols: Default::default(),
468 repr_has_repr_c: false,
470 inherited_pub_visibility: false,
471 ignore_variant_stack: vec![],
474 symbol_visitor.mark_live_symbols();
475 symbol_visitor.live_symbols
478 struct DeadVisitor<'tcx> {
480 live_symbols: FxHashSet<hir::HirId>,
483 impl DeadVisitor<'tcx> {
484 fn should_warn_about_item(&mut self, item: &hir::Item) -> bool {
485 let should_warn = match item.kind {
486 hir::ItemKind::Static(..)
487 | hir::ItemKind::Const(..)
488 | hir::ItemKind::Fn(..)
489 | hir::ItemKind::TyAlias(..)
490 | hir::ItemKind::Enum(..)
491 | hir::ItemKind::Struct(..)
492 | hir::ItemKind::Union(..) => true,
495 should_warn && !self.symbol_is_live(item.hir_id)
498 fn should_warn_about_field(&mut self, field: &hir::StructField) -> bool {
499 let field_type = self.tcx.type_of(self.tcx.hir().local_def_id(field.hir_id));
500 !field.is_positional()
501 && !self.symbol_is_live(field.hir_id)
502 && !field_type.is_phantom_data()
503 && !has_allow_dead_code_or_lang_attr(self.tcx, field.hir_id, &field.attrs)
506 fn should_warn_about_variant(&mut self, variant: &hir::Variant) -> bool {
507 !self.symbol_is_live(variant.id)
508 && !has_allow_dead_code_or_lang_attr(self.tcx,
513 fn should_warn_about_foreign_item(&mut self, fi: &hir::ForeignItem) -> bool {
514 !self.symbol_is_live(fi.hir_id)
515 && !has_allow_dead_code_or_lang_attr(self.tcx, fi.hir_id, &fi.attrs)
518 // id := HIR id of an item's definition.
523 if self.live_symbols.contains(&id) {
526 // If it's a type whose items are live, then it's live, too.
527 // This is done to handle the case where, for example, the static
528 // method of a private type is used, but the type itself is never
530 let def_id = self.tcx.hir().local_def_id(id);
531 let inherent_impls = self.tcx.inherent_impls(def_id);
532 for &impl_did in inherent_impls.iter() {
533 for &item_did in &self.tcx.associated_item_def_ids(impl_did)[..] {
534 if let Some(item_hir_id) = self.tcx.hir().as_local_hir_id(item_did) {
535 if self.live_symbols.contains(&item_hir_id) {
544 fn warn_dead_code(&mut self,
546 span: syntax_pos::Span,
550 if !name.as_str().starts_with("_") {
552 .lint_hir(lint::builtin::DEAD_CODE,
555 &format!("{} is never {}: `{}`",
556 node_type, participle, name));
561 impl Visitor<'tcx> for DeadVisitor<'tcx> {
562 /// Walk nested items in place so that we don't report dead-code
563 /// on inner functions when the outer function is already getting
564 /// an error. We could do this also by checking the parents, but
565 /// this is how the code is setup and it seems harmless enough.
566 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
567 NestedVisitorMap::All(&self.tcx.hir())
570 fn visit_item(&mut self, item: &'tcx hir::Item) {
571 if self.should_warn_about_item(item) {
572 // For most items, we want to highlight its identifier
573 let span = match item.kind {
574 hir::ItemKind::Fn(..) |
575 hir::ItemKind::Mod(..) |
576 hir::ItemKind::Enum(..) |
577 hir::ItemKind::Struct(..) |
578 hir::ItemKind::Union(..) |
579 hir::ItemKind::Trait(..) |
580 hir::ItemKind::Impl(..) => {
581 // FIXME(66095): Because item.span is annotated with things
582 // like expansion data, and ident.span isn't, we use the
583 // def_span method if it's part of a macro invocation
584 // (and thus has asource_callee set).
585 // We should probably annotate ident.span with the macro
586 // context, but that's a larger change.
587 if item.span.source_callee().is_some() {
588 self.tcx.sess.source_map().def_span(item.span)
595 let participle = match item.kind {
596 hir::ItemKind::Struct(..) => "constructed", // Issue #52325
603 item.kind.descriptive_variant(),
607 // Only continue if we didn't warn
608 intravisit::walk_item(self, item);
612 fn visit_variant(&mut self,
613 variant: &'tcx hir::Variant,
614 g: &'tcx hir::Generics,
616 if self.should_warn_about_variant(&variant) {
617 self.warn_dead_code(variant.id, variant.span, variant.ident.name,
618 "variant", "constructed");
620 intravisit::walk_variant(self, variant, g, id);
624 fn visit_foreign_item(&mut self, fi: &'tcx hir::ForeignItem) {
625 if self.should_warn_about_foreign_item(fi) {
626 self.warn_dead_code(fi.hir_id, fi.span, fi.ident.name,
627 fi.kind.descriptive_variant(), "used");
629 intravisit::walk_foreign_item(self, fi);
632 fn visit_struct_field(&mut self, field: &'tcx hir::StructField) {
633 if self.should_warn_about_field(&field) {
634 self.warn_dead_code(field.hir_id, field.span, field.ident.name, "field", "read");
636 intravisit::walk_struct_field(self, field);
639 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem) {
640 match impl_item.kind {
641 hir::ImplItemKind::Const(_, body_id) => {
642 if !self.symbol_is_live(impl_item.hir_id) {
643 self.warn_dead_code(impl_item.hir_id,
645 impl_item.ident.name,
649 self.visit_nested_body(body_id)
651 hir::ImplItemKind::Method(_, body_id) => {
652 if !self.symbol_is_live(impl_item.hir_id) {
653 let span = self.tcx.sess.source_map().def_span(impl_item.span);
654 self.warn_dead_code(impl_item.hir_id, span, impl_item.ident.name, "method",
657 self.visit_nested_body(body_id)
659 hir::ImplItemKind::OpaqueTy(..) |
660 hir::ImplItemKind::TyAlias(..) => {}
664 // Overwrite so that we don't warn the trait item itself.
665 fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem) {
666 match trait_item.kind {
667 hir::TraitItemKind::Const(_, Some(body_id)) |
668 hir::TraitItemKind::Method(_, hir::TraitMethod::Provided(body_id)) => {
669 self.visit_nested_body(body_id)
671 hir::TraitItemKind::Const(_, None) |
672 hir::TraitItemKind::Method(_, hir::TraitMethod::Required(_)) |
673 hir::TraitItemKind::Type(..) => {}
678 pub fn check_crate(tcx: TyCtxt<'_>) {
679 let access_levels = &tcx.privacy_access_levels(LOCAL_CRATE);
680 let krate = tcx.hir().krate();
681 let live_symbols = find_live(tcx, access_levels, krate);
682 let mut visitor = DeadVisitor {
686 intravisit::walk_crate(&mut visitor, krate);