]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_mir_build/src/lints.rs
Rollup merge of #99957 - chotchki:ip-globally-reachable_rebase, r=Mark-Simulacrum
[rust.git] / compiler / rustc_mir_build / src / lints.rs
1 use rustc_data_structures::graph::iterate::{
2     NodeStatus, TriColorDepthFirstSearch, TriColorVisitor,
3 };
4 use rustc_hir::def::DefKind;
5 use rustc_middle::mir::{BasicBlock, BasicBlocks, Body, Operand, TerminatorKind};
6 use rustc_middle::ty::subst::{GenericArg, InternalSubsts};
7 use rustc_middle::ty::{self, Instance, TyCtxt};
8 use rustc_session::lint::builtin::UNCONDITIONAL_RECURSION;
9 use rustc_span::Span;
10 use std::ops::ControlFlow;
11
12 pub(crate) fn check<'tcx>(tcx: TyCtxt<'tcx>, body: &Body<'tcx>) {
13     let def_id = body.source.def_id().expect_local();
14
15     if let DefKind::Fn | DefKind::AssocFn = tcx.def_kind(def_id) {
16         // If this is trait/impl method, extract the trait's substs.
17         let trait_substs = match tcx.trait_of_item(def_id.to_def_id()) {
18             Some(trait_def_id) => {
19                 let trait_substs_count = tcx.generics_of(trait_def_id).count();
20                 &InternalSubsts::identity_for_item(tcx, def_id.to_def_id())[..trait_substs_count]
21             }
22             _ => &[],
23         };
24
25         let mut vis = Search { tcx, body, reachable_recursive_calls: vec![], trait_substs };
26         if let Some(NonRecursive) =
27             TriColorDepthFirstSearch::new(&body.basic_blocks).run_from_start(&mut vis)
28         {
29             return;
30         }
31         if vis.reachable_recursive_calls.is_empty() {
32             return;
33         }
34
35         vis.reachable_recursive_calls.sort();
36
37         let sp = tcx.def_span(def_id);
38         let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
39         tcx.struct_span_lint_hir(UNCONDITIONAL_RECURSION, hir_id, sp, |lint| {
40             let mut db = lint.build("function cannot return without recursing");
41             db.span_label(sp, "cannot return without recursing");
42             // offer some help to the programmer.
43             for call_span in vis.reachable_recursive_calls {
44                 db.span_label(call_span, "recursive call site");
45             }
46             db.help("a `loop` may express intention better if this is on purpose");
47             db.emit();
48         });
49     }
50 }
51
52 struct NonRecursive;
53
54 struct Search<'mir, 'tcx> {
55     tcx: TyCtxt<'tcx>,
56     body: &'mir Body<'tcx>,
57     trait_substs: &'tcx [GenericArg<'tcx>],
58
59     reachable_recursive_calls: Vec<Span>,
60 }
61
62 impl<'mir, 'tcx> Search<'mir, 'tcx> {
63     /// Returns `true` if `func` refers to the function we are searching in.
64     fn is_recursive_call(&self, func: &Operand<'tcx>, args: &[Operand<'tcx>]) -> bool {
65         let Search { tcx, body, trait_substs, .. } = *self;
66         // Resolving function type to a specific instance that is being called is expensive.  To
67         // avoid the cost we check the number of arguments first, which is sufficient to reject
68         // most of calls as non-recursive.
69         if args.len() != body.arg_count {
70             return false;
71         }
72         let caller = body.source.def_id();
73         let param_env = tcx.param_env(caller);
74
75         let func_ty = func.ty(body, tcx);
76         if let ty::FnDef(callee, substs) = *func_ty.kind() {
77             let normalized_substs = tcx.normalize_erasing_regions(param_env, substs);
78             let (callee, call_substs) = if let Ok(Some(instance)) =
79                 Instance::resolve(tcx, param_env, callee, normalized_substs)
80             {
81                 (instance.def_id(), instance.substs)
82             } else {
83                 (callee, normalized_substs)
84             };
85
86             // FIXME(#57965): Make this work across function boundaries
87
88             // If this is a trait fn, the substs on the trait have to match, or we might be
89             // calling into an entirely different method (for example, a call from the default
90             // method in the trait to `<A as Trait<B>>::method`, where `A` and/or `B` are
91             // specific types).
92             return callee == caller && &call_substs[..trait_substs.len()] == trait_substs;
93         }
94
95         false
96     }
97 }
98
99 impl<'mir, 'tcx> TriColorVisitor<BasicBlocks<'tcx>> for Search<'mir, 'tcx> {
100     type BreakVal = NonRecursive;
101
102     fn node_examined(
103         &mut self,
104         bb: BasicBlock,
105         prior_status: Option<NodeStatus>,
106     ) -> ControlFlow<Self::BreakVal> {
107         // Back-edge in the CFG (loop).
108         if let Some(NodeStatus::Visited) = prior_status {
109             return ControlFlow::Break(NonRecursive);
110         }
111
112         match self.body[bb].terminator().kind {
113             // These terminators return control flow to the caller.
114             TerminatorKind::Abort
115             | TerminatorKind::GeneratorDrop
116             | TerminatorKind::Resume
117             | TerminatorKind::Return
118             | TerminatorKind::Unreachable
119             | TerminatorKind::Yield { .. } => ControlFlow::Break(NonRecursive),
120
121             // A diverging InlineAsm is treated as non-recursing
122             TerminatorKind::InlineAsm { destination, .. } => {
123                 if destination.is_some() {
124                     ControlFlow::CONTINUE
125                 } else {
126                     ControlFlow::Break(NonRecursive)
127                 }
128             }
129
130             // These do not.
131             TerminatorKind::Assert { .. }
132             | TerminatorKind::Call { .. }
133             | TerminatorKind::Drop { .. }
134             | TerminatorKind::DropAndReplace { .. }
135             | TerminatorKind::FalseEdge { .. }
136             | TerminatorKind::FalseUnwind { .. }
137             | TerminatorKind::Goto { .. }
138             | TerminatorKind::SwitchInt { .. } => ControlFlow::CONTINUE,
139         }
140     }
141
142     fn node_settled(&mut self, bb: BasicBlock) -> ControlFlow<Self::BreakVal> {
143         // When we examine a node for the last time, remember it if it is a recursive call.
144         let terminator = self.body[bb].terminator();
145         if let TerminatorKind::Call { func, args, .. } = &terminator.kind {
146             if self.is_recursive_call(func, args) {
147                 self.reachable_recursive_calls.push(terminator.source_info.span);
148             }
149         }
150
151         ControlFlow::CONTINUE
152     }
153
154     fn ignore_edge(&mut self, bb: BasicBlock, target: BasicBlock) -> bool {
155         let terminator = self.body[bb].terminator();
156         if terminator.unwind() == Some(&Some(target)) && terminator.successors().count() > 1 {
157             return true;
158         }
159         // Don't traverse successors of recursive calls or false CFG edges.
160         match self.body[bb].terminator().kind {
161             TerminatorKind::Call { ref func, ref args, .. } => self.is_recursive_call(func, args),
162             TerminatorKind::FalseEdge { imaginary_target, .. } => imaginary_target == target,
163             _ => false,
164         }
165     }
166 }