]> git.proxmox.com Git - rustc.git/blame - compiler/rustc_passes/src/liveness.rs
New upstream version 1.70.0+dfsg1
[rustc.git] / compiler / rustc_passes / src / liveness.rs
CommitLineData
9fa01778 1//! A classic liveness analysis based on dataflow over the AST. Computes,
1a4d82fc 2//! for each local variable in a function, whether that variable is live
9fa01778
XL
3//! at a given point. Program execution points are identified by their
4//! IDs.
1a4d82fc
JJ
5//!
6//! # Basic idea
7//!
9fa01778 8//! The basic model is that each local variable is assigned an index. We
1a4d82fc 9//! represent sets of local variables using a vector indexed by this
9fa01778
XL
10//! index. The value in the vector is either 0, indicating the variable
11//! is dead, or the ID of an expression that uses the variable.
1a4d82fc 12//!
9fa01778
XL
13//! We conceptually walk over the AST in reverse execution order. If we
14//! find a use of a variable, we add it to the set of live variables. If
1a4d82fc 15//! we find an assignment to a variable, we remove it from the set of live
9fa01778
XL
16//! variables. When we have to merge two flows, we take the union of
17//! those two flows -- if the variable is live on both paths, we simply
18//! pick one ID. In the event of loops, we continue doing this until a
1a4d82fc
JJ
19//! fixed point is reached.
20//!
21//! ## Checking initialization
22//!
9fa01778
XL
23//! At the function entry point, all variables must be dead. If this is
24//! not the case, we can report an error using the ID found in the set of
1a4d82fc
JJ
25//! live variables, which identifies a use of the variable which is not
26//! dominated by an assignment.
27//!
28//! ## Checking moves
29//!
30//! After each explicit move, the variable must be dead.
31//!
32//! ## Computing last uses
33//!
34//! Any use of the variable where the variable is dead afterwards is a
35//! last use.
36//!
37//! # Implementation details
38//!
39//! The actual implementation contains two (nested) walks over the AST.
40//! The outer walk has the job of building up the ir_maps instance for the
9fa01778 41//! enclosing function. On the way down the tree, it identifies those AST
1a4d82fc 42//! nodes and variable IDs that will be needed for the liveness analysis
9fa01778
XL
43//! and assigns them contiguous IDs. The liveness ID for an AST node is
44//! called a `live_node` (it's a newtype'd `u32`) and the ID for a variable
45//! is called a `variable` (another newtype'd `u32`).
1a4d82fc
JJ
46//!
47//! On the way back up the tree, as we are about to exit from a function
9fa01778 48//! declaration we allocate a `liveness` instance. Now that we know
1a4d82fc 49//! precisely how many nodes and variables we need, we can allocate all
9fa01778 50//! the various arrays that we will need to precisely the right size. We then
1a4d82fc
JJ
51//! perform the actual propagation on the `liveness` instance.
52//!
53//! This propagation is encoded in the various `propagate_through_*()`
9fa01778 54//! methods. It effectively does a reverse walk of the AST; whenever we
1a4d82fc
JJ
55//! reach a loop node, we iterate until a fixed point is reached.
56//!
0bf4aa26 57//! ## The `RWU` struct
1a4d82fc
JJ
58//!
59//! At each live node `N`, we track three pieces of information for each
0bf4aa26 60//! variable `V` (these are encapsulated in the `RWU` struct):
1a4d82fc
JJ
61//!
62//! - `reader`: the `LiveNode` ID of some node which will read the value
9fa01778 63//! that `V` holds on entry to `N`. Formally: a node `M` such
1a4d82fc 64//! that there exists a path `P` from `N` to `M` where `P` does not
1b1a35ee 65//! write `V`. If the `reader` is `None`, then the current
1a4d82fc
JJ
66//! value will never be read (the variable is dead, essentially).
67//!
68//! - `writer`: the `LiveNode` ID of some node which will write the
9fa01778 69//! variable `V` and which is reachable from `N`. Formally: a node `M`
1a4d82fc 70//! such that there exists a path `P` from `N` to `M` and `M` writes
1b1a35ee 71//! `V`. If the `writer` is `None`, then there is no writer
1a4d82fc
JJ
72//! of `V` that follows `N`.
73//!
9fa01778 74//! - `used`: a boolean value indicating whether `V` is *used*. We
1a4d82fc 75//! distinguish a *read* from a *use* in that a *use* is some read that
9fa01778
XL
76//! is not just used to generate a new value. For example, `x += 1` is
77//! a read but not a use. This is used to generate better warnings.
1a4d82fc 78//!
f9f354fc 79//! ## Special nodes and variables
1a4d82fc 80//!
f9f354fc 81//! We generate various special nodes for various, well, special purposes.
1b1a35ee 82//! These are described in the `Liveness` struct.
b7449926 83
1a4d82fc
JJ
84use self::LiveNodeKind::*;
85use self::VarKind::*;
86
3dfed10e 87use rustc_ast::InlineAsmOptions;
e74abb32 88use rustc_data_structures::fx::FxIndexMap;
dfeec247 89use rustc_errors::Applicability;
487cf647 90use rustc_errors::Diagnostic;
dfeec247
XL
91use rustc_hir as hir;
92use rustc_hir::def::*;
f2b60f7d 93use rustc_hir::def_id::{DefId, LocalDefId};
5099ac24 94use rustc_hir::intravisit::{self, Visitor};
1b1a35ee
XL
95use rustc_hir::{Expr, HirId, HirIdMap, HirIdSet};
96use rustc_index::vec::IndexVec;
ba9703b0 97use rustc_middle::ty::query::Providers;
353b0b11 98use rustc_middle::ty::{self, RootVariableMinCaptureList, Ty, TyCtxt};
ba9703b0 99use rustc_session::lint;
1b1a35ee 100use rustc_span::symbol::{kw, sym, Symbol};
f2b60f7d 101use rustc_span::{BytePos, Span};
dfeec247 102
e74abb32 103use std::collections::VecDeque;
c34b1796 104use std::io;
dfeec247 105use std::io::prelude::*;
c34b1796 106use std::rc::Rc;
e9174d1e 107
fc512014
XL
108mod rwu_table;
109
1b1a35ee 110rustc_index::newtype_index! {
9c376795
FG
111 #[debug_format = "v({})"]
112 pub struct Variable {}
1a4d82fc
JJ
113}
114
1b1a35ee 115rustc_index::newtype_index! {
9c376795
FG
116 #[debug_format = "ln({})"]
117 pub struct LiveNode {}
1a4d82fc
JJ
118}
119
c34b1796 120#[derive(Copy, Clone, PartialEq, Debug)]
223e47cc 121enum LiveNodeKind {
48663c56 122 UpvarNode(Span),
94222f64
XL
123 ExprNode(Span, HirId),
124 VarDefNode(Span, HirId),
f9f354fc 125 ClosureNode,
dfeec247 126 ExitNode,
223e47cc
LB
127}
128
dc9dc135 129fn live_node_kind_to_string(lnk: LiveNodeKind, tcx: TyCtxt<'_>) -> String {
74b04a01 130 let sm = tcx.sess.source_map();
223e47cc 131 match lnk {
17df50a5 132 UpvarNode(s) => format!("Upvar node [{}]", sm.span_to_diagnostic_string(s)),
94222f64
XL
133 ExprNode(s, _) => format!("Expr node [{}]", sm.span_to_diagnostic_string(s)),
134 VarDefNode(s, _) => format!("Var def node [{}]", sm.span_to_diagnostic_string(s)),
f9f354fc 135 ClosureNode => "Closure node".to_owned(),
0bf4aa26 136 ExitNode => "Exit node".to_owned(),
223e47cc
LB
137 }
138}
139
f2b60f7d
FG
140fn check_liveness(tcx: TyCtxt<'_>, def_id: DefId) {
141 let local_def_id = match def_id.as_local() {
142 None => return,
143 Some(def_id) => def_id,
144 };
145
146 // Don't run unused pass for #[derive()]
147 let parent = tcx.local_parent(local_def_id);
9ffffee4 148 if let DefKind::Impl { .. } = tcx.def_kind(parent)
353b0b11 149 && tcx.has_attr(parent, sym::automatically_derived)
f2b60f7d
FG
150 {
151 return;
152 }
153
154 // Don't run unused pass for #[naked]
155 if tcx.has_attr(def_id, sym::naked) {
156 return;
157 }
158
159 let mut maps = IrMaps::new(tcx);
160 let body_id = tcx.hir().body_owned_by(local_def_id);
161 let hir_id = tcx.hir().body_owner(body_id);
162 let body = tcx.hir().body(body_id);
163
164 if let Some(upvars) = tcx.upvars_mentioned(def_id) {
165 for &var_hir_id in upvars.keys() {
166 let var_name = tcx.hir().name(var_hir_id);
167 maps.add_variable(Upvar(var_hir_id, var_name));
168 }
169 }
170
171 // gather up the various local variables, significant expressions,
172 // and so forth:
173 maps.visit_body(body);
174
175 // compute liveness
176 let mut lsets = Liveness::new(&mut maps, local_def_id);
177 let entry_ln = lsets.compute(&body, hir_id);
178 lsets.log_liveness(entry_ln, body_id.hir_id);
179
180 // check for various error conditions
181 lsets.visit_body(body);
182 lsets.warn_about_unused_upvars(entry_ln);
183 lsets.warn_about_unused_args(body, entry_ln);
9fa01778
XL
184}
185
f035d41b 186pub fn provide(providers: &mut Providers) {
f2b60f7d 187 *providers = Providers { check_liveness, ..*providers };
223e47cc
LB
188}
189
223e47cc
LB
190// ______________________________________________________________________
191// Creating ir_maps
192//
193// This is the first pass and the one that drives the main
9c376795 194// computation. It walks up and down the IR once. On the way down,
223e47cc 195// we count for each function the number of variables as well as
9c376795 196// liveness nodes. A liveness node is basically an expression or
223e47cc
LB
197// capture clause that does something of interest: either it has
198// interesting control flow or it uses/defines a local variable.
199//
200// On the way back up, at each function node we create liveness sets
201// (we now know precisely how big to make our various vectors and so
202// forth) and then do the data-flow propagation to compute the set
203// of live variables at each program point.
204//
205// Finally, we run back over the IR one last time and, using the
9c376795 206// computed liveness, check various safety conditions. For example,
223e47cc 207// there must be no live nodes at the definition site for a variable
9c376795 208// unless it has an initializer. Similarly, each non-mutable local
223e47cc 209// variable must not be assigned if there is some successor
9c376795 210// assignment. And so forth.
223e47cc 211
223e47cc
LB
212struct CaptureInfo {
213 ln: LiveNode,
dfeec247 214 var_hid: HirId,
223e47cc
LB
215}
216
c34b1796 217#[derive(Copy, Clone, Debug)]
223e47cc 218struct LocalInfo {
94b46f34 219 id: HirId,
f9f354fc 220 name: Symbol,
2c00a5a8 221 is_shorthand: bool,
223e47cc
LB
222}
223
c34b1796 224#[derive(Copy, Clone, Debug)]
223e47cc 225enum VarKind {
f9f354fc 226 Param(HirId, Symbol),
223e47cc 227 Local(LocalInfo),
f9f354fc 228 Upvar(HirId, Symbol),
223e47cc
LB
229}
230
f2b60f7d
FG
231struct CollectLitsVisitor<'tcx> {
232 lit_exprs: Vec<&'tcx hir::Expr<'tcx>>,
233}
234
235impl<'tcx> Visitor<'tcx> for CollectLitsVisitor<'tcx> {
236 fn visit_expr(&mut self, expr: &'tcx Expr<'tcx>) {
237 if let hir::ExprKind::Lit(_) = expr.kind {
238 self.lit_exprs.push(expr);
239 }
240 intravisit::walk_expr(self, expr);
241 }
242}
243
dc9dc135
XL
244struct IrMaps<'tcx> {
245 tcx: TyCtxt<'tcx>,
94b46f34
XL
246 live_node_map: HirIdMap<LiveNode>,
247 variable_map: HirIdMap<Variable>,
532ac7d7 248 capture_info_map: HirIdMap<Rc<Vec<CaptureInfo>>>,
1b1a35ee
XL
249 var_kinds: IndexVec<Variable, VarKind>,
250 lnks: IndexVec<LiveNode, LiveNodeKind>,
223e47cc
LB
251}
252
a2a8927a 253impl<'tcx> IrMaps<'tcx> {
1b1a35ee 254 fn new(tcx: TyCtxt<'tcx>) -> IrMaps<'tcx> {
1a4d82fc 255 IrMaps {
041b39d2 256 tcx,
a1dfa0c6
XL
257 live_node_map: HirIdMap::default(),
258 variable_map: HirIdMap::default(),
259 capture_info_map: Default::default(),
1b1a35ee
XL
260 var_kinds: IndexVec::new(),
261 lnks: IndexVec::new(),
1a4d82fc 262 }
223e47cc 263 }
223e47cc 264
1a4d82fc 265 fn add_live_node(&mut self, lnk: LiveNodeKind) -> LiveNode {
1b1a35ee 266 let ln = self.lnks.push(lnk);
223e47cc 267
dfeec247 268 debug!("{:?} is of kind {}", ln, live_node_kind_to_string(lnk, self.tcx));
223e47cc
LB
269
270 ln
271 }
272
94b46f34 273 fn add_live_node_for_node(&mut self, hir_id: HirId, lnk: LiveNodeKind) {
223e47cc 274 let ln = self.add_live_node(lnk);
94b46f34 275 self.live_node_map.insert(hir_id, ln);
223e47cc 276
94b46f34 277 debug!("{:?} is node {:?}", ln, hir_id);
223e47cc
LB
278 }
279
1a4d82fc 280 fn add_variable(&mut self, vk: VarKind) -> Variable {
1b1a35ee 281 let v = self.var_kinds.push(vk);
223e47cc
LB
282
283 match vk {
f9f354fc 284 Local(LocalInfo { id: node_id, .. }) | Param(node_id, _) | Upvar(node_id, _) => {
223e47cc 285 self.variable_map.insert(node_id, v);
dfeec247 286 }
223e47cc
LB
287 }
288
1a4d82fc 289 debug!("{:?} is {:?}", v, vk);
223e47cc
LB
290
291 v
292 }
293
94b46f34
XL
294 fn variable(&self, hir_id: HirId, span: Span) -> Variable {
295 match self.variable_map.get(&hir_id) {
54a0048b
SL
296 Some(&var) => var,
297 None => {
94b46f34 298 span_bug!(span, "no variable registered for id {:?}", hir_id);
54a0048b 299 }
223e47cc
LB
300 }
301 }
302
1b1a35ee
XL
303 fn variable_name(&self, var: Variable) -> Symbol {
304 match self.var_kinds[var] {
305 Local(LocalInfo { name, .. }) | Param(_, name) | Upvar(_, name) => name,
223e47cc
LB
306 }
307 }
308
2c00a5a8 309 fn variable_is_shorthand(&self, var: Variable) -> bool {
1b1a35ee 310 match self.var_kinds[var] {
2c00a5a8 311 Local(LocalInfo { is_shorthand, .. }) => is_shorthand,
f9f354fc 312 Param(..) | Upvar(..) => false,
2c00a5a8
XL
313 }
314 }
315
532ac7d7
XL
316 fn set_captures(&mut self, hir_id: HirId, cs: Vec<CaptureInfo>) {
317 self.capture_info_map.insert(hir_id, Rc::new(cs));
223e47cc
LB
318 }
319
c295e0f8 320 fn collect_shorthand_field_ids(&self, pat: &hir::Pat<'tcx>) -> HirIdSet {
1b1a35ee
XL
321 // For struct patterns, take note of which fields used shorthand
322 // (`x` rather than `x: x`).
323 let mut shorthand_field_ids = HirIdSet::default();
324 let mut pats = VecDeque::new();
325 pats.push_back(pat);
c295e0f8 326
1b1a35ee
XL
327 while let Some(pat) = pats.pop_front() {
328 use rustc_hir::PatKind::*;
329 match &pat.kind {
330 Binding(.., inner_pat) => {
331 pats.extend(inner_pat.iter());
332 }
333 Struct(_, fields, _) => {
064997fb 334 let (short, not_short): (Vec<_>, _) =
c295e0f8
XL
335 fields.iter().partition(|f| f.is_shorthand);
336 shorthand_field_ids.extend(short.iter().map(|f| f.pat.hir_id));
337 pats.extend(not_short.iter().map(|f| f.pat));
1b1a35ee
XL
338 }
339 Ref(inner_pat, _) | Box(inner_pat) => {
340 pats.push_back(inner_pat);
341 }
342 TupleStruct(_, inner_pats, _) | Tuple(inner_pats, _) | Or(inner_pats) => {
343 pats.extend(inner_pats.iter());
344 }
345 Slice(pre_pats, inner_pat, post_pats) => {
346 pats.extend(pre_pats.iter());
347 pats.extend(inner_pat.iter());
348 pats.extend(post_pats.iter());
349 }
350 _ => {}
351 }
352 }
353
064997fb 354 shorthand_field_ids
c295e0f8
XL
355 }
356
357 fn add_from_pat(&mut self, pat: &hir::Pat<'tcx>) {
358 let shorthand_field_ids = self.collect_shorthand_field_ids(pat);
359
1b1a35ee 360 pat.each_binding(|_, hir_id, _, ident| {
94222f64 361 self.add_live_node_for_node(hir_id, VarDefNode(ident.span, hir_id));
1b1a35ee
XL
362 self.add_variable(Local(LocalInfo {
363 id: hir_id,
364 name: ident.name,
365 is_shorthand: shorthand_field_ids.contains(&hir_id),
366 }));
367 });
223e47cc 368 }
1a4d82fc 369}
223e47cc 370
1b1a35ee 371impl<'tcx> Visitor<'tcx> for IrMaps<'tcx> {
1b1a35ee
XL
372 fn visit_local(&mut self, local: &'tcx hir::Local<'tcx>) {
373 self.add_from_pat(&local.pat);
064997fb
FG
374 if local.els.is_some() {
375 self.add_live_node_for_node(local.hir_id, ExprNode(local.span, local.hir_id));
376 }
1b1a35ee
XL
377 intravisit::walk_local(self, local);
378 }
379
380 fn visit_arm(&mut self, arm: &'tcx hir::Arm<'tcx>) {
381 self.add_from_pat(&arm.pat);
923072b8
FG
382 if let Some(hir::Guard::IfLet(ref let_expr)) = arm.guard {
383 self.add_from_pat(let_expr.pat);
fc512014 384 }
1b1a35ee 385 intravisit::walk_arm(self, arm);
f9f354fc
XL
386 }
387
1b1a35ee 388 fn visit_param(&mut self, param: &'tcx hir::Param<'tcx>) {
c295e0f8 389 let shorthand_field_ids = self.collect_shorthand_field_ids(param.pat);
e1599b0c 390 param.pat.each_binding(|_bm, hir_id, _x, ident| {
6a06907d 391 let var = match param.pat.kind {
c295e0f8 392 rustc_hir::PatKind::Struct(..) => Local(LocalInfo {
6a06907d
XL
393 id: hir_id,
394 name: ident.name,
c295e0f8 395 is_shorthand: shorthand_field_ids.contains(&hir_id),
6a06907d
XL
396 }),
397 _ => Param(hir_id, ident.name),
532ac7d7 398 };
1b1a35ee
XL
399 self.add_variable(var);
400 });
401 intravisit::walk_param(self, param);
dfeec247 402 }
223e47cc 403
1b1a35ee
XL
404 fn visit_expr(&mut self, expr: &'tcx Expr<'tcx>) {
405 match expr.kind {
406 // live nodes required for uses or definitions of variables:
407 hir::ExprKind::Path(hir::QPath::Resolved(_, ref path)) => {
408 debug!("expr {}: path that leads to {:?}", expr.hir_id, path.res);
409 if let Res::Local(_var_hir_id) = path.res {
94222f64 410 self.add_live_node_for_node(expr.hir_id, ExprNode(expr.span, expr.hir_id));
1b1a35ee
XL
411 }
412 intravisit::walk_expr(self, expr);
94b46f34 413 }
487cf647 414 hir::ExprKind::Closure(closure) => {
1b1a35ee
XL
415 // Interesting control flow (for loops can contain labeled
416 // breaks or continues)
94222f64 417 self.add_live_node_for_node(expr.hir_id, ExprNode(expr.span, expr.hir_id));
1b1a35ee 418
94222f64 419 // Make a live_node for each mentioned variable, with the span
9c376795 420 // being the location that the variable is used. This results
1b1a35ee
XL
421 // in better error messages than just pointing at the closure
422 // construction site.
423 let mut call_caps = Vec::new();
487cf647 424 if let Some(upvars) = self.tcx.upvars_mentioned(closure.def_id) {
94222f64 425 call_caps.extend(upvars.keys().map(|var_id| {
fc512014 426 let upvar = upvars[var_id];
1b1a35ee 427 let upvar_ln = self.add_live_node(UpvarNode(upvar.span));
fc512014 428 CaptureInfo { ln: upvar_ln, var_hid: *var_id }
1b1a35ee
XL
429 }));
430 }
431 self.set_captures(expr.hir_id, call_caps);
432 intravisit::walk_expr(self, expr);
94b46f34 433 }
94b46f34 434
a2a8927a
XL
435 hir::ExprKind::Let(let_expr) => {
436 self.add_from_pat(let_expr.pat);
94222f64
XL
437 intravisit::walk_expr(self, expr);
438 }
439
1b1a35ee 440 // live nodes required for interesting control flow:
94222f64
XL
441 hir::ExprKind::If(..)
442 | hir::ExprKind::Match(..)
443 | hir::ExprKind::Loop(..)
444 | hir::ExprKind::Yield(..) => {
445 self.add_live_node_for_node(expr.hir_id, ExprNode(expr.span, expr.hir_id));
1b1a35ee 446 intravisit::walk_expr(self, expr);
dc9dc135 447 }
1b1a35ee 448 hir::ExprKind::Binary(op, ..) if op.node.is_lazy() => {
94222f64 449 self.add_live_node_for_node(expr.hir_id, ExprNode(expr.span, expr.hir_id));
1b1a35ee 450 intravisit::walk_expr(self, expr);
dfeec247 451 }
dfeec247 452
1b1a35ee
XL
453 // otherwise, live nodes are not required:
454 hir::ExprKind::Index(..)
455 | hir::ExprKind::Field(..)
456 | hir::ExprKind::Array(..)
457 | hir::ExprKind::Call(..)
458 | hir::ExprKind::MethodCall(..)
459 | hir::ExprKind::Tup(..)
460 | hir::ExprKind::Binary(..)
461 | hir::ExprKind::AddrOf(..)
462 | hir::ExprKind::Cast(..)
463 | hir::ExprKind::DropTemps(..)
464 | hir::ExprKind::Unary(..)
465 | hir::ExprKind::Break(..)
466 | hir::ExprKind::Continue(_)
467 | hir::ExprKind::Lit(_)
29967ef6 468 | hir::ExprKind::ConstBlock(..)
1b1a35ee
XL
469 | hir::ExprKind::Ret(..)
470 | hir::ExprKind::Block(..)
471 | hir::ExprKind::Assign(..)
472 | hir::ExprKind::AssignOp(..)
473 | hir::ExprKind::Struct(..)
474 | hir::ExprKind::Repeat(..)
475 | hir::ExprKind::InlineAsm(..)
1b1a35ee 476 | hir::ExprKind::Type(..)
9ffffee4 477 | hir::ExprKind::Err(_)
1b1a35ee
XL
478 | hir::ExprKind::Path(hir::QPath::TypeRelative(..))
479 | hir::ExprKind::Path(hir::QPath::LangItem(..)) => {
480 intravisit::walk_expr(self, expr);
481 }
48663c56 482 }
223e47cc
LB
483 }
484}
485
486// ______________________________________________________________________
487// Computing liveness sets
488//
489// Actually we compute just a bit more than just liveness, but we use
490// the same basic propagation framework in all cases.
491
c34b1796
AL
492const ACC_READ: u32 = 1;
493const ACC_WRITE: u32 = 2;
494const ACC_USE: u32 = 4;
223e47cc 495
dc9dc135
XL
496struct Liveness<'a, 'tcx> {
497 ir: &'a mut IrMaps<'tcx>,
3dfed10e 498 typeck_results: &'a ty::TypeckResults<'tcx>,
ba9703b0 499 param_env: ty::ParamEnv<'tcx>,
6a06907d 500 closure_min_captures: Option<&'tcx RootVariableMinCaptureList<'tcx>>,
1b1a35ee 501 successors: IndexVec<LiveNode, Option<LiveNode>>,
fc512014 502 rwu_table: rwu_table::RWUTable,
cc61c64b 503
1b1a35ee
XL
504 /// A live node representing a point of execution before closure entry &
505 /// after closure exit. Used to calculate liveness of captured variables
506 /// through calls to the same closure. Used for Fn & FnMut closures only.
507 closure_ln: LiveNode,
508 /// A live node representing every 'exit' from the function, whether it be
509 /// by explicit return, panic, or other means.
510 exit_ln: LiveNode,
511
223e47cc
LB
512 // mappings from loop node ID to LiveNode
513 // ("break" label should map to loop node ID,
514 // it probably doesn't now)
532ac7d7
XL
515 break_ln: HirIdMap<LiveNode>,
516 cont_ln: HirIdMap<LiveNode>,
223e47cc
LB
517}
518
1a4d82fc 519impl<'a, 'tcx> Liveness<'a, 'tcx> {
1b1a35ee
XL
520 fn new(ir: &'a mut IrMaps<'tcx>, body_owner: LocalDefId) -> Liveness<'a, 'tcx> {
521 let typeck_results = ir.tcx.typeck(body_owner);
522 let param_env = ir.tcx.param_env(body_owner);
064997fb 523 let closure_min_captures = typeck_results.closure_min_captures.get(&body_owner);
1b1a35ee
XL
524 let closure_ln = ir.add_live_node(ClosureNode);
525 let exit_ln = ir.add_live_node(ExitNode);
32a655c1 526
1b1a35ee
XL
527 let num_live_nodes = ir.lnks.len();
528 let num_vars = ir.var_kinds.len();
32a655c1 529
1a4d82fc 530 Liveness {
041b39d2 531 ir,
3dfed10e 532 typeck_results,
ba9703b0 533 param_env,
6a06907d 534 closure_min_captures,
1b1a35ee 535 successors: IndexVec::from_elem_n(None, num_live_nodes),
fc512014 536 rwu_table: rwu_table::RWUTable::new(num_live_nodes, num_vars),
1b1a35ee
XL
537 closure_ln,
538 exit_ln,
a1dfa0c6
XL
539 break_ln: Default::default(),
540 cont_ln: Default::default(),
1a4d82fc 541 }
223e47cc 542 }
223e47cc 543
94b46f34
XL
544 fn live_node(&self, hir_id: HirId, span: Span) -> LiveNode {
545 match self.ir.live_node_map.get(&hir_id) {
dfeec247
XL
546 Some(&ln) => ln,
547 None => {
548 // This must be a mismatch between the ir_map construction
549 // above and the propagation code below; the two sets of
550 // code have to agree about which AST nodes are worth
551 // creating liveness nodes for.
552 span_bug!(span, "no live node registered for node {:?}", hir_id);
553 }
223e47cc
LB
554 }
555 }
556
94b46f34
XL
557 fn variable(&self, hir_id: HirId, span: Span) -> Variable {
558 self.ir.variable(hir_id, span)
223e47cc
LB
559 }
560
dfeec247 561 fn define_bindings_in_pat(&mut self, pat: &hir::Pat<'_>, mut succ: LiveNode) -> LiveNode {
e74abb32
XL
562 // In an or-pattern, only consider the first pattern; any later patterns
563 // must have the same bindings, and we also consider the first pattern
564 // to be the "authoritative" set of ids.
565 pat.each_binding_or_first(&mut |_, hir_id, pat_sp, ident| {
566 let ln = self.live_node(hir_id, pat_sp);
567 let var = self.variable(hir_id, ident.span);
568 self.init_from_succ(ln, succ);
569 self.define(ln, var);
223e47cc 570 succ = ln;
1a4d82fc 571 });
223e47cc
LB
572 succ
573 }
574
fc512014
XL
575 fn live_on_entry(&self, ln: LiveNode, var: Variable) -> bool {
576 self.rwu_table.get_reader(ln, var)
223e47cc
LB
577 }
578
0bf4aa26 579 // Is this variable live on entry to any of its successor nodes?
fc512014 580 fn live_on_exit(&self, ln: LiveNode, var: Variable) -> bool {
1b1a35ee 581 let successor = self.successors[ln].unwrap();
1a4d82fc 582 self.live_on_entry(successor, var)
223e47cc
LB
583 }
584
1a4d82fc 585 fn used_on_entry(&self, ln: LiveNode, var: Variable) -> bool {
fc512014 586 self.rwu_table.get_used(ln, var)
223e47cc
LB
587 }
588
fc512014
XL
589 fn assigned_on_entry(&self, ln: LiveNode, var: Variable) -> bool {
590 self.rwu_table.get_writer(ln, var)
223e47cc
LB
591 }
592
fc512014 593 fn assigned_on_exit(&self, ln: LiveNode, var: Variable) -> bool {
1b1a35ee 594 let successor = self.successors[ln].unwrap();
1a4d82fc 595 self.assigned_on_entry(successor, var)
223e47cc
LB
596 }
597
fc512014 598 fn write_vars<F>(&self, wr: &mut dyn Write, mut test: F) -> io::Result<()>
dfeec247 599 where
fc512014 600 F: FnMut(Variable) -> bool,
1a4d82fc 601 {
1b1a35ee 602 for var_idx in 0..self.ir.var_kinds.len() {
fc512014
XL
603 let var = Variable::from(var_idx);
604 if test(var) {
605 write!(wr, " {:?}", var)?;
223e47cc
LB
606 }
607 }
1a4d82fc 608 Ok(())
223e47cc
LB
609 }
610
1a4d82fc
JJ
611 #[allow(unused_must_use)]
612 fn ln_str(&self, ln: LiveNode) -> String {
613 let mut wr = Vec::new();
614 {
0531ce1d 615 let wr = &mut wr as &mut dyn Write;
1b1a35ee 616 write!(wr, "[{:?} of kind {:?} reads", ln, self.ir.lnks[ln]);
fc512014 617 self.write_vars(wr, |var| self.rwu_table.get_reader(ln, var));
1a4d82fc 618 write!(wr, " writes");
fc512014 619 self.write_vars(wr, |var| self.rwu_table.get_writer(ln, var));
f9f354fc 620 write!(wr, " uses");
fc512014 621 self.write_vars(wr, |var| self.rwu_table.get_used(ln, var));
f9f354fc 622
1b1a35ee 623 write!(wr, " precedes {:?}]", self.successors[ln]);
223e47cc 624 }
1a4d82fc 625 String::from_utf8(wr).unwrap()
223e47cc
LB
626 }
627
f9f354fc
XL
628 fn log_liveness(&self, entry_ln: LiveNode, hir_id: hir::HirId) {
629 // hack to skip the loop unless debug! is enabled:
630 debug!(
631 "^^ liveness computation results for body {} (entry={:?})",
632 {
1b1a35ee
XL
633 for ln_idx in 0..self.ir.lnks.len() {
634 debug!("{:?}", self.ln_str(LiveNode::from(ln_idx)));
f9f354fc
XL
635 }
636 hir_id
637 },
638 entry_ln
639 );
640 }
641
1a4d82fc 642 fn init_empty(&mut self, ln: LiveNode, succ_ln: LiveNode) {
1b1a35ee 643 self.successors[ln] = Some(succ_ln);
223e47cc 644
0bf4aa26 645 // It is not necessary to initialize the RWUs here because they are all
fc512014 646 // empty when created, and the sets only grow during iterations.
223e47cc
LB
647 }
648
1a4d82fc 649 fn init_from_succ(&mut self, ln: LiveNode, succ_ln: LiveNode) {
223e47cc 650 // more efficient version of init_empty() / merge_from_succ()
1b1a35ee 651 self.successors[ln] = Some(succ_ln);
fc512014 652 self.rwu_table.copy(ln, succ_ln);
dfeec247 653 debug!("init_from_succ(ln={}, succ={})", self.ln_str(ln), self.ln_str(succ_ln));
223e47cc
LB
654 }
655
fc512014 656 fn merge_from_succ(&mut self, ln: LiveNode, succ_ln: LiveNode) -> bool {
dfeec247
XL
657 if ln == succ_ln {
658 return false;
659 }
223e47cc 660
fc512014
XL
661 let changed = self.rwu_table.union(ln, succ_ln);
662 debug!("merge_from_succ(ln={:?}, succ={}, changed={})", ln, self.ln_str(succ_ln), changed);
663 changed
223e47cc
LB
664 }
665
666 // Indicates that a local variable was *defined*; we know that no
667 // uses of the variable can precede the definition (resolve checks
668 // this) so we just clear out all the data.
1a4d82fc 669 fn define(&mut self, writer: LiveNode, var: Variable) {
fc512014
XL
670 let used = self.rwu_table.get_used(writer, var);
671 self.rwu_table.set(writer, var, rwu_table::RWU { reader: false, writer: false, used });
672 debug!("{:?} defines {:?}: {}", writer, var, self.ln_str(writer));
223e47cc
LB
673 }
674
675 // Either read, write, or both depending on the acc bitset
c34b1796 676 fn acc(&mut self, ln: LiveNode, var: Variable, acc: u32) {
dfeec247 677 debug!("{:?} accesses[{:x}] {:?}: {}", ln, acc, var, self.ln_str(ln));
1a4d82fc 678
fc512014 679 let mut rwu = self.rwu_table.get(ln, var);
223e47cc
LB
680
681 if (acc & ACC_WRITE) != 0 {
fc512014
XL
682 rwu.reader = false;
683 rwu.writer = true;
223e47cc
LB
684 }
685
686 // Important: if we both read/write, must do read second
687 // or else the write will override.
688 if (acc & ACC_READ) != 0 {
fc512014 689 rwu.reader = true;
223e47cc
LB
690 }
691
692 if (acc & ACC_USE) != 0 {
0bf4aa26 693 rwu.used = true;
223e47cc 694 }
223e47cc 695
fc512014 696 self.rwu_table.set(ln, var, rwu);
0bf4aa26 697 }
223e47cc 698
1b1a35ee
XL
699 fn compute(&mut self, body: &hir::Body<'_>, hir_id: HirId) -> LiveNode {
700 debug!("compute: for body {:?}", body.id().hir_id);
223e47cc 701
f9f354fc
XL
702 // # Liveness of captured variables
703 //
704 // When computing the liveness for captured variables we take into
705 // account how variable is captured (ByRef vs ByValue) and what is the
706 // closure kind (Generator / FnOnce vs Fn / FnMut).
707 //
708 // Variables captured by reference are assumed to be used on the exit
709 // from the closure.
710 //
711 // In FnOnce closures, variables captured by value are known to be dead
712 // on exit since it is impossible to call the closure again.
713 //
714 // In Fn / FnMut closures, variables captured by value are live on exit
715 // if they are live on the entry to the closure, since only the closure
716 // itself can access them on subsequent calls.
717
6a06907d 718 if let Some(closure_min_captures) = self.closure_min_captures {
f9f354fc 719 // Mark upvars captured by reference as used after closure exits.
6a06907d
XL
720 for (&var_hir_id, min_capture_list) in closure_min_captures {
721 for captured_place in min_capture_list {
722 match captured_place.info.capture_kind {
723 ty::UpvarCapture::ByRef(_) => {
724 let var = self.variable(
725 var_hir_id,
726 captured_place.get_capture_kind_span(self.ir.tcx),
727 );
728 self.acc(self.exit_ln, var, ACC_READ | ACC_USE);
729 }
5099ac24 730 ty::UpvarCapture::ByValue => {}
f9f354fc 731 }
f9f354fc
XL
732 }
733 }
734 }
cc61c64b 735
1b1a35ee 736 let succ = self.propagate_through_expr(&body.value, self.exit_ln);
223e47cc 737
6a06907d 738 if self.closure_min_captures.is_none() {
1b1a35ee
XL
739 // Either not a closure, or closure without any captured variables.
740 // No need to determine liveness of captured variables, since there
741 // are none.
742 return succ;
f9f354fc
XL
743 }
744
1b1a35ee
XL
745 let ty = self.typeck_results.node_type(hir_id);
746 match ty.kind() {
f9f354fc
XL
747 ty::Closure(_def_id, substs) => match substs.as_closure().kind() {
748 ty::ClosureKind::Fn => {}
749 ty::ClosureKind::FnMut => {}
750 ty::ClosureKind::FnOnce => return succ,
dfeec247 751 },
f9f354fc
XL
752 ty::Generator(..) => return succ,
753 _ => {
1b1a35ee
XL
754 span_bug!(
755 body.value.span,
756 "{} has upvars so it should have a closure type: {:?}",
757 hir_id,
758 ty
759 );
f9f354fc
XL
760 }
761 };
762
763 // Propagate through calls to the closure.
f9f354fc 764 loop {
1b1a35ee 765 self.init_from_succ(self.closure_ln, succ);
f9f354fc
XL
766 for param in body.params {
767 param.pat.each_binding(|_bm, hir_id, _x, ident| {
768 let var = self.variable(hir_id, ident.span);
1b1a35ee 769 self.define(self.closure_ln, var);
f9f354fc
XL
770 })
771 }
223e47cc 772
fc512014 773 if !self.merge_from_succ(self.exit_ln, self.closure_ln) {
f9f354fc
XL
774 break;
775 }
1b1a35ee 776 assert_eq!(succ, self.propagate_through_expr(&body.value, self.exit_ln));
f9f354fc
XL
777 }
778
779 succ
223e47cc
LB
780 }
781
dfeec247 782 fn propagate_through_block(&mut self, blk: &hir::Block<'_>, succ: LiveNode) -> LiveNode {
cc61c64b 783 if blk.targeted_by_break {
532ac7d7 784 self.break_ln.insert(blk.hir_id, succ);
cc61c64b 785 }
c295e0f8 786 let succ = self.propagate_through_opt_expr(blk.expr, succ);
dfeec247 787 blk.stmts.iter().rev().fold(succ, |succ, stmt| self.propagate_through_stmt(stmt, succ))
223e47cc
LB
788 }
789
dfeec247 790 fn propagate_through_stmt(&mut self, stmt: &hir::Stmt<'_>, succ: LiveNode) -> LiveNode {
e74abb32 791 match stmt.kind {
9fa01778
XL
792 hir::StmtKind::Local(ref local) => {
793 // Note: we mark the variable as defined regardless of whether
9c376795 794 // there is an initializer. Initially I had thought to only mark
9fa01778
XL
795 // the live variable as defined if it was initialized, and then we
796 // could check for uninit variables just by scanning what is live
797 // at the start of the function. But that doesn't work so well for
798 // immutable variables defined in a loop:
799 // loop { let x; x = 5; }
800 // because the "assignment" loops back around and generates an error.
801 //
802 // So now we just check that variables defined w/o an
803 // initializer are not live at the point of their
804 // initialization, which is mildly more complex than checking
805 // once at the func header but otherwise equivalent.
223e47cc 806
064997fb
FG
807 if let Some(els) = local.els {
808 // Eventually, `let pat: ty = init else { els };` is mostly equivalent to
809 // `let (bindings, ...) = match init { pat => (bindings, ...), _ => els };`
810 // except that extended lifetime applies at the `init` location.
811 //
812 // (e)
813 // |
814 // v
815 // (expr)
816 // / \
817 // | |
818 // v v
819 // bindings els
820 // |
821 // v
822 // ( succ )
823 //
824 if let Some(init) = local.init {
825 let else_ln = self.propagate_through_block(els, succ);
826 let ln = self.live_node(local.hir_id, local.span);
827 self.init_from_succ(ln, succ);
828 self.merge_from_succ(ln, else_ln);
829 let succ = self.propagate_through_expr(init, ln);
830 self.define_bindings_in_pat(&local.pat, succ)
831 } else {
832 span_bug!(
833 stmt.span,
834 "variable is uninitialized but an unexpected else branch is found"
835 )
836 }
837 } else {
838 let succ = self.propagate_through_opt_expr(local.init, succ);
839 self.define_bindings_in_pat(&local.pat, succ)
840 }
1a4d82fc 841 }
9fa01778
XL
842 hir::StmtKind::Item(..) => succ,
843 hir::StmtKind::Expr(ref expr) | hir::StmtKind::Semi(ref expr) => {
844 self.propagate_through_expr(&expr, succ)
223e47cc 845 }
223e47cc
LB
846 }
847 }
848
dfeec247
XL
849 fn propagate_through_exprs(&mut self, exprs: &[Expr<'_>], succ: LiveNode) -> LiveNode {
850 exprs.iter().rev().fold(succ, |succ, expr| self.propagate_through_expr(&expr, succ))
223e47cc
LB
851 }
852
dfeec247
XL
853 fn propagate_through_opt_expr(
854 &mut self,
855 opt_expr: Option<&Expr<'_>>,
856 succ: LiveNode,
857 ) -> LiveNode {
1a4d82fc 858 opt_expr.map_or(succ, |expr| self.propagate_through_expr(expr, succ))
223e47cc
LB
859 }
860
dfeec247 861 fn propagate_through_expr(&mut self, expr: &Expr<'_>, succ: LiveNode) -> LiveNode {
ba9703b0 862 debug!("propagate_through_expr: {:?}", expr);
223e47cc 863
e74abb32 864 match expr.kind {
0bf4aa26
XL
865 // Interesting cases with control flow or which gen/kill
866 hir::ExprKind::Path(hir::QPath::Resolved(_, ref path)) => {
867 self.access_path(expr.hir_id, path, succ, ACC_READ | ACC_USE)
868 }
223e47cc 869
dfeec247 870 hir::ExprKind::Field(ref e, _) => self.propagate_through_expr(&e, succ),
1a4d82fc 871
923072b8 872 hir::ExprKind::Closure { .. } => {
ba9703b0 873 debug!("{:?} is an ExprKind::Closure", expr);
0bf4aa26 874
0bf4aa26
XL
875 // the construction of a closure itself is not important,
876 // but we have to consider the closed over variables.
dfeec247
XL
877 let caps = self
878 .ir
879 .capture_info_map
880 .get(&expr.hir_id)
881 .cloned()
882 .unwrap_or_else(|| span_bug!(expr.span, "no registered caps"));
0bf4aa26
XL
883
884 caps.iter().rev().fold(succ, |succ, cap| {
885 self.init_from_succ(cap.ln, succ);
886 let var = self.variable(cap.var_hid, expr.span);
887 self.acc(cap.ln, var, ACC_READ | ACC_USE);
888 cap.ln
889 })
890 }
223e47cc 891
a2a8927a
XL
892 hir::ExprKind::Let(let_expr) => {
893 let succ = self.propagate_through_expr(let_expr.init, succ);
894 self.define_bindings_in_pat(let_expr.pat, succ)
94222f64
XL
895 }
896
0bf4aa26
XL
897 // Note that labels have been resolved, so we don't need to look
898 // at the label ident
5869c6ff
XL
899 hir::ExprKind::Loop(ref blk, ..) => self.propagate_through_loop(expr, &blk, succ),
900
94222f64
XL
901 hir::ExprKind::Yield(ref e, ..) => {
902 let yield_ln = self.live_node(expr.hir_id, expr.span);
903 self.init_from_succ(yield_ln, succ);
904 self.merge_from_succ(yield_ln, self.exit_ln);
905 self.propagate_through_expr(e, yield_ln)
906 }
907
5869c6ff
XL
908 hir::ExprKind::If(ref cond, ref then, ref else_opt) => {
909 //
910 // (cond)
911 // |
912 // v
913 // (expr)
914 // / \
915 // | |
916 // v v
917 // (then)(els)
918 // | |
919 // v v
920 // ( succ )
921 //
487cf647 922 let else_ln = self.propagate_through_opt_expr(else_opt.as_deref(), succ);
5869c6ff
XL
923 let then_ln = self.propagate_through_expr(&then, succ);
924 let ln = self.live_node(expr.hir_id, expr.span);
925 self.init_from_succ(ln, else_ln);
926 self.merge_from_succ(ln, then_ln);
927 self.propagate_through_expr(&cond, ln)
928 }
223e47cc 929
dfeec247 930 hir::ExprKind::Match(ref e, arms, _) => {
0bf4aa26
XL
931 //
932 // (e)
933 // |
934 // v
935 // (expr)
936 // / | \
937 // | | |
938 // v v v
939 // (..arms..)
940 // | | |
941 // v v v
942 // ( succ )
943 //
944 //
945 let ln = self.live_node(expr.hir_id, expr.span);
946 self.init_empty(ln, succ);
0bf4aa26
XL
947 for arm in arms {
948 let body_succ = self.propagate_through_expr(&arm.body, succ);
949
fc512014
XL
950 let guard_succ = arm.guard.as_ref().map_or(body_succ, |g| match g {
951 hir::Guard::If(e) => self.propagate_through_expr(e, body_succ),
923072b8
FG
952 hir::Guard::IfLet(let_expr) => {
953 let let_bind = self.define_bindings_in_pat(let_expr.pat, body_succ);
954 self.propagate_through_expr(let_expr.init, let_bind)
fc512014
XL
955 }
956 });
e74abb32 957 let arm_succ = self.define_bindings_in_pat(&arm.pat, guard_succ);
fc512014 958 self.merge_from_succ(ln, arm_succ);
dfeec247 959 }
0bf4aa26
XL
960 self.propagate_through_expr(&e, ln)
961 }
223e47cc 962
0bf4aa26 963 hir::ExprKind::Ret(ref o_e) => {
1b1a35ee 964 // Ignore succ and subst exit_ln.
487cf647 965 self.propagate_through_opt_expr(o_e.as_deref(), self.exit_ln)
0bf4aa26 966 }
223e47cc 967
0bf4aa26
XL
968 hir::ExprKind::Break(label, ref opt_expr) => {
969 // Find which label this break jumps to
970 let target = match label.target_id {
532ac7d7 971 Ok(hir_id) => self.break_ln.get(&hir_id),
94b46f34 972 Err(err) => span_bug!(expr.span, "loop scope error: {}", err),
dfeec247
XL
973 }
974 .cloned();
223e47cc 975
0bf4aa26
XL
976 // Now that we know the label we're going to,
977 // look it up in the break loop nodes table
8bb4bdeb 978
0bf4aa26 979 match target {
487cf647 980 Some(b) => self.propagate_through_opt_expr(opt_expr.as_deref(), b),
f035d41b 981 None => span_bug!(expr.span, "`break` to unknown label"),
0bf4aa26
XL
982 }
983 }
223e47cc 984
0bf4aa26
XL
985 hir::ExprKind::Continue(label) => {
986 // Find which label this expr continues to
dfeec247
XL
987 let sc = label
988 .target_id
989 .unwrap_or_else(|err| span_bug!(expr.span, "loop scope error: {}", err));
223e47cc 990
0bf4aa26
XL
991 // Now that we know the label we're going to,
992 // look it up in the continue loop nodes table
dfeec247
XL
993 self.cont_ln
994 .get(&sc)
995 .cloned()
996 .unwrap_or_else(|| span_bug!(expr.span, "continue to unknown label"))
0bf4aa26 997 }
223e47cc 998
dfeec247 999 hir::ExprKind::Assign(ref l, ref r, _) => {
2c00a5a8
XL
1000 // see comment on places in
1001 // propagate_through_place_components()
0bf4aa26
XL
1002 let succ = self.write_place(&l, succ, ACC_WRITE);
1003 let succ = self.propagate_through_place_components(&l, succ);
1004 self.propagate_through_expr(&r, succ)
54a0048b 1005 }
223e47cc 1006
0bf4aa26
XL
1007 hir::ExprKind::AssignOp(_, ref l, ref r) => {
1008 // an overloaded assign op is like a method call
3dfed10e 1009 if self.typeck_results.is_method_call(expr) {
0bf4aa26
XL
1010 let succ = self.propagate_through_expr(&l, succ);
1011 self.propagate_through_expr(&r, succ)
1012 } else {
1013 // see comment on places in
1014 // propagate_through_place_components()
dfeec247 1015 let succ = self.write_place(&l, succ, ACC_WRITE | ACC_READ);
0bf4aa26
XL
1016 let succ = self.propagate_through_expr(&r, succ);
1017 self.propagate_through_place_components(&l, succ)
1018 }
1019 }
223e47cc 1020
0bf4aa26 1021 // Uninteresting cases: just propagate in rev exec order
dfeec247 1022 hir::ExprKind::Array(ref exprs) => self.propagate_through_exprs(exprs, succ),
223e47cc 1023
0bf4aa26 1024 hir::ExprKind::Struct(_, ref fields, ref with_expr) => {
487cf647 1025 let succ = self.propagate_through_opt_expr(with_expr.as_deref(), succ);
dfeec247
XL
1026 fields
1027 .iter()
1028 .rev()
1029 .fold(succ, |succ, field| self.propagate_through_expr(&field.expr, succ))
0bf4aa26 1030 }
223e47cc 1031
0bf4aa26 1032 hir::ExprKind::Call(ref f, ref args) => {
94222f64 1033 let succ = self.check_is_ty_uninhabited(expr, succ);
0bf4aa26
XL
1034 let succ = self.propagate_through_exprs(args, succ);
1035 self.propagate_through_expr(&f, succ)
1036 }
223e47cc 1037
f2b60f7d 1038 hir::ExprKind::MethodCall(.., receiver, ref args, _) => {
94222f64 1039 let succ = self.check_is_ty_uninhabited(expr, succ);
f2b60f7d
FG
1040 let succ = self.propagate_through_exprs(args, succ);
1041 self.propagate_through_expr(receiver, succ)
0bf4aa26 1042 }
223e47cc 1043
dfeec247 1044 hir::ExprKind::Tup(ref exprs) => self.propagate_through_exprs(exprs, succ),
223e47cc 1045
0bf4aa26
XL
1046 hir::ExprKind::Binary(op, ref l, ref r) if op.node.is_lazy() => {
1047 let r_succ = self.propagate_through_expr(&r, succ);
223e47cc 1048
0bf4aa26
XL
1049 let ln = self.live_node(expr.hir_id, expr.span);
1050 self.init_from_succ(ln, succ);
fc512014 1051 self.merge_from_succ(ln, r_succ);
223e47cc 1052
0bf4aa26
XL
1053 self.propagate_through_expr(&l, ln)
1054 }
1a4d82fc 1055
dfeec247 1056 hir::ExprKind::Index(ref l, ref r) | hir::ExprKind::Binary(_, ref l, ref r) => {
0bf4aa26
XL
1057 let r_succ = self.propagate_through_expr(&r, succ);
1058 self.propagate_through_expr(&l, r_succ)
1059 }
1060
353b0b11 1061 hir::ExprKind::AddrOf(_, _, ref e)
dfeec247
XL
1062 | hir::ExprKind::Cast(ref e, _)
1063 | hir::ExprKind::Type(ref e, _)
1064 | hir::ExprKind::DropTemps(ref e)
1065 | hir::ExprKind::Unary(_, ref e)
dfeec247 1066 | hir::ExprKind::Repeat(ref e, _) => self.propagate_through_expr(&e, succ),
0bf4aa26 1067
f9f354fc
XL
1068 hir::ExprKind::InlineAsm(ref asm) => {
1069 // Handle non-returning asm
1070 let mut succ = if asm.options.contains(InlineAsmOptions::NORETURN) {
1b1a35ee 1071 self.exit_ln
f9f354fc
XL
1072 } else {
1073 succ
1074 };
1075
1076 // Do a first pass for writing outputs only
fc512014 1077 for (op, _op_sp) in asm.operands.iter().rev() {
f9f354fc
XL
1078 match op {
1079 hir::InlineAsmOperand::In { .. }
1080 | hir::InlineAsmOperand::Const { .. }
04454e1e
FG
1081 | hir::InlineAsmOperand::SymFn { .. }
1082 | hir::InlineAsmOperand::SymStatic { .. } => {}
f9f354fc
XL
1083 hir::InlineAsmOperand::Out { expr, .. } => {
1084 if let Some(expr) = expr {
1085 succ = self.write_place(expr, succ, ACC_WRITE);
1086 }
1087 }
1088 hir::InlineAsmOperand::InOut { expr, .. } => {
29967ef6 1089 succ = self.write_place(expr, succ, ACC_READ | ACC_WRITE | ACC_USE);
f9f354fc
XL
1090 }
1091 hir::InlineAsmOperand::SplitInOut { out_expr, .. } => {
1092 if let Some(expr) = out_expr {
1093 succ = self.write_place(expr, succ, ACC_WRITE);
1094 }
1095 }
1096 }
1097 }
1098
1099 // Then do a second pass for inputs
1100 let mut succ = succ;
fc512014 1101 for (op, _op_sp) in asm.operands.iter().rev() {
f9f354fc 1102 match op {
04454e1e 1103 hir::InlineAsmOperand::In { expr, .. } => {
f9f354fc
XL
1104 succ = self.propagate_through_expr(expr, succ)
1105 }
1106 hir::InlineAsmOperand::Out { expr, .. } => {
1107 if let Some(expr) = expr {
1108 succ = self.propagate_through_place_components(expr, succ);
1109 }
1110 }
1111 hir::InlineAsmOperand::InOut { expr, .. } => {
1112 succ = self.propagate_through_place_components(expr, succ);
1113 }
1114 hir::InlineAsmOperand::SplitInOut { in_expr, out_expr, .. } => {
1115 if let Some(expr) = out_expr {
1116 succ = self.propagate_through_place_components(expr, succ);
1117 }
1118 succ = self.propagate_through_expr(in_expr, succ);
1119 }
04454e1e
FG
1120 hir::InlineAsmOperand::Const { .. }
1121 | hir::InlineAsmOperand::SymFn { .. }
1122 | hir::InlineAsmOperand::SymStatic { .. } => {}
f9f354fc
XL
1123 }
1124 }
1125 succ
1126 }
1127
dfeec247 1128 hir::ExprKind::Lit(..)
29967ef6 1129 | hir::ExprKind::ConstBlock(..)
9ffffee4 1130 | hir::ExprKind::Err(_)
3dfed10e
XL
1131 | hir::ExprKind::Path(hir::QPath::TypeRelative(..))
1132 | hir::ExprKind::Path(hir::QPath::LangItem(..)) => succ,
223e47cc 1133
0bf4aa26
XL
1134 // Note that labels have been resolved, so we don't need to look
1135 // at the label ident
dfeec247 1136 hir::ExprKind::Block(ref blk, _) => self.propagate_through_block(&blk, succ),
223e47cc
LB
1137 }
1138 }
1139
dfeec247 1140 fn propagate_through_place_components(&mut self, expr: &Expr<'_>, succ: LiveNode) -> LiveNode {
2c00a5a8 1141 // # Places
223e47cc
LB
1142 //
1143 // In general, the full flow graph structure for an
1144 // assignment/move/etc can be handled in one of two ways,
1145 // depending on whether what is being assigned is a "tracked
1146 // value" or not. A tracked value is basically a local
1147 // variable or argument.
1148 //
1149 // The two kinds of graphs are:
1150 //
2c00a5a8 1151 // Tracked place Untracked place
223e47cc
LB
1152 // ----------------------++-----------------------
1153 // ||
1154 // | || |
1155 // v || v
1156 // (rvalue) || (rvalue)
1157 // | || |
1158 // v || v
064997fb 1159 // (write of place) || (place components)
223e47cc
LB
1160 // | || |
1161 // v || v
1162 // (succ) || (succ)
1163 // ||
1164 // ----------------------++-----------------------
1165 //
1166 // I will cover the two cases in turn:
1167 //
2c00a5a8 1168 // # Tracked places
223e47cc 1169 //
9c376795 1170 // A tracked place is a local variable/argument `x`. In
223e47cc 1171 // these cases, the link_node where the write occurs is linked
9c376795
FG
1172 // to node id of `x`. The `write_place()` routine generates
1173 // the contents of this node. There are no subcomponents to
223e47cc
LB
1174 // consider.
1175 //
2c00a5a8 1176 // # Non-tracked places
223e47cc 1177 //
9c376795 1178 // These are places like `x[5]` or `x.f`. In that case, we
223e47cc 1179 // basically ignore the value which is written to but generate
9c376795 1180 // reads for the components---`x` in these two examples. The
223e47cc 1181 // components reads are generated by
2c00a5a8 1182 // `propagate_through_place_components()` (this fn).
223e47cc 1183 //
2c00a5a8 1184 // # Illegal places
223e47cc 1185 //
2c00a5a8 1186 // It is still possible to observe assignments to non-places;
9c376795 1187 // these errors are detected in the later pass borrowck. We
223e47cc
LB
1188 // just ignore such cases and treat them as reads.
1189
e74abb32 1190 match expr.kind {
8faf50e0
XL
1191 hir::ExprKind::Path(_) => succ,
1192 hir::ExprKind::Field(ref e, _) => self.propagate_through_expr(&e, succ),
dfeec247 1193 _ => self.propagate_through_expr(expr, succ),
223e47cc
LB
1194 }
1195 }
1196
2c00a5a8 1197 // see comment on propagate_through_place()
dfeec247 1198 fn write_place(&mut self, expr: &Expr<'_>, succ: LiveNode, acc: u32) -> LiveNode {
e74abb32 1199 match expr.kind {
0bf4aa26
XL
1200 hir::ExprKind::Path(hir::QPath::Resolved(_, ref path)) => {
1201 self.access_path(expr.hir_id, path, succ, acc)
1202 }
223e47cc 1203
0bf4aa26 1204 // We do not track other places, so just propagate through
9c376795 1205 // to their subcomponents. Also, it may happen that
0bf4aa26
XL
1206 // non-places occur here, because those are detected in the
1207 // later pass borrowck.
dfeec247 1208 _ => succ,
223e47cc
LB
1209 }
1210 }
1211
dfeec247
XL
1212 fn access_var(
1213 &mut self,
1214 hir_id: HirId,
1215 var_hid: HirId,
1216 succ: LiveNode,
1217 acc: u32,
1218 span: Span,
1219 ) -> LiveNode {
94b46f34 1220 let ln = self.live_node(hir_id, span);
ea8adc8c
XL
1221 if acc != 0 {
1222 self.init_from_succ(ln, succ);
94b46f34 1223 let var = self.variable(var_hid, span);
ea8adc8c
XL
1224 self.acc(ln, var, acc);
1225 }
1226 ln
1227 }
1228
dfeec247
XL
1229 fn access_path(
1230 &mut self,
1231 hir_id: HirId,
1232 path: &hir::Path<'_>,
1233 succ: LiveNode,
1234 acc: u32,
1235 ) -> LiveNode {
48663c56 1236 match path.res {
94222f64 1237 Res::Local(hid) => self.access_var(hir_id, hid, succ, acc, path.span),
dfeec247 1238 _ => succ,
223e47cc
LB
1239 }
1240 }
1241
416331ca
XL
1242 fn propagate_through_loop(
1243 &mut self,
dfeec247
XL
1244 expr: &Expr<'_>,
1245 body: &hir::Block<'_>,
1246 succ: LiveNode,
416331ca 1247 ) -> LiveNode {
223e47cc 1248 /*
223e47cc
LB
1249 We model control flow like this:
1250
416331ca
XL
1251 (expr) <-+
1252 | |
1253 v |
1254 (body) --+
223e47cc 1255
416331ca
XL
1256 Note that a `continue` expression targeting the `loop` will have a successor of `expr`.
1257 Meanwhile, a `break` expression will have a successor of `succ`.
223e47cc
LB
1258 */
1259
223e47cc 1260 // first iteration:
94b46f34 1261 let ln = self.live_node(expr.hir_id, expr.span);
223e47cc 1262 self.init_empty(ln, succ);
ba9703b0 1263 debug!("propagate_through_loop: using id for loop body {} {:?}", expr.hir_id, body);
9fa01778 1264
532ac7d7 1265 self.break_ln.insert(expr.hir_id, succ);
cc61c64b 1266
416331ca 1267 self.cont_ln.insert(expr.hir_id, ln);
9fa01778 1268
416331ca 1269 let body_ln = self.propagate_through_block(body, ln);
223e47cc
LB
1270
1271 // repeat until fixed point is reached:
fc512014 1272 while self.merge_from_succ(ln, body_ln) {
416331ca 1273 assert_eq!(body_ln, self.propagate_through_block(body, ln));
223e47cc
LB
1274 }
1275
416331ca 1276 ln
223e47cc 1277 }
94222f64
XL
1278
1279 fn check_is_ty_uninhabited(&mut self, expr: &Expr<'_>, succ: LiveNode) -> LiveNode {
1280 let ty = self.typeck_results.expr_ty(expr);
1281 let m = self.ir.tcx.parent_module(expr.hir_id).to_def_id();
487cf647
FG
1282 if ty.is_inhabited_from(self.ir.tcx, m, self.param_env) {
1283 return succ;
94222f64 1284 }
487cf647
FG
1285 match self.ir.lnks[succ] {
1286 LiveNodeKind::ExprNode(succ_span, succ_id) => {
1287 self.warn_about_unreachable(expr.span, ty, succ_span, succ_id, "expression");
1288 }
1289 LiveNodeKind::VarDefNode(succ_span, succ_id) => {
1290 self.warn_about_unreachable(expr.span, ty, succ_span, succ_id, "definition");
1291 }
1292 _ => {}
1293 };
1294 self.exit_ln
94222f64
XL
1295 }
1296
1297 fn warn_about_unreachable(
1298 &mut self,
1299 orig_span: Span,
1300 orig_ty: Ty<'tcx>,
1301 expr_span: Span,
1302 expr_id: HirId,
1303 descr: &str,
1304 ) {
1305 if !orig_ty.is_never() {
1306 // Unreachable code warnings are already emitted during type checking.
1307 // However, during type checking, full type information is being
1308 // calculated but not yet available, so the check for diverging
1309 // expressions due to uninhabited result types is pretty crude and
1310 // only checks whether ty.is_never(). Here, we have full type
1311 // information available and can issue warnings for less obviously
1312 // uninhabited types (e.g. empty enums). The check above is used so
1313 // that we do not emit the same warning twice if the uninhabited type
1314 // is indeed `!`.
1315
2b03887a 1316 let msg = format!("unreachable {}", descr);
94222f64
XL
1317 self.ir.tcx.struct_span_lint_hir(
1318 lint::builtin::UNREACHABLE_CODE,
1319 expr_id,
1320 expr_span,
2b03887a
FG
1321 &msg,
1322 |diag| {
1323 diag.span_label(expr_span, &msg)
94222f64
XL
1324 .span_label(orig_span, "any code following this expression is unreachable")
1325 .span_note(
1326 orig_span,
1327 &format!(
1328 "this expression has type `{}`, which is uninhabited",
1329 orig_ty
1330 ),
1331 )
94222f64
XL
1332 },
1333 );
1334 }
1335 }
223e47cc
LB
1336}
1337
1338// _______________________________________________________________________
1339// Checking for error conditions
1340
32a655c1 1341impl<'a, 'tcx> Visitor<'tcx> for Liveness<'a, 'tcx> {
dfeec247 1342 fn visit_local(&mut self, local: &'tcx hir::Local<'tcx>) {
f2b60f7d 1343 self.check_unused_vars_in_pat(&local.pat, None, None, |spans, hir_id, ln, var| {
e74abb32
XL
1344 if local.init.is_some() {
1345 self.warn_about_dead_assign(spans, hir_id, ln, var);
1346 }
1347 });
32a655c1 1348
e74abb32 1349 intravisit::walk_local(self, local);
223e47cc
LB
1350 }
1351
dfeec247 1352 fn visit_expr(&mut self, ex: &'tcx Expr<'tcx>) {
e74abb32 1353 check_expr(self, ex);
94222f64 1354 intravisit::walk_expr(self, ex);
9fa01778
XL
1355 }
1356
dfeec247 1357 fn visit_arm(&mut self, arm: &'tcx hir::Arm<'tcx>) {
f2b60f7d 1358 self.check_unused_vars_in_pat(&arm.pat, None, None, |_, _, _, _| {});
e74abb32 1359 intravisit::walk_arm(self, arm);
9fa01778 1360 }
223e47cc
LB
1361}
1362
dfeec247 1363fn check_expr<'tcx>(this: &mut Liveness<'_, 'tcx>, expr: &'tcx Expr<'tcx>) {
e74abb32 1364 match expr.kind {
dfeec247 1365 hir::ExprKind::Assign(ref l, ..) => {
2c00a5a8 1366 this.check_place(&l);
54a0048b 1367 }
223e47cc 1368
0bf4aa26 1369 hir::ExprKind::AssignOp(_, ref l, _) => {
3dfed10e 1370 if !this.typeck_results.is_method_call(expr) {
0bf4aa26
XL
1371 this.check_place(&l);
1372 }
223e47cc
LB
1373 }
1374
f9f354fc 1375 hir::ExprKind::InlineAsm(ref asm) => {
fc512014 1376 for (op, _op_sp) in asm.operands {
f9f354fc
XL
1377 match op {
1378 hir::InlineAsmOperand::Out { expr, .. } => {
1379 if let Some(expr) = expr {
1380 this.check_place(expr);
1381 }
1382 }
1383 hir::InlineAsmOperand::InOut { expr, .. } => {
1384 this.check_place(expr);
1385 }
1386 hir::InlineAsmOperand::SplitInOut { out_expr, .. } => {
1387 if let Some(out_expr) = out_expr {
1388 this.check_place(out_expr);
1389 }
1390 }
1391 _ => {}
1392 }
1393 }
1394 }
1395
a2a8927a 1396 hir::ExprKind::Let(let_expr) => {
f2b60f7d 1397 this.check_unused_vars_in_pat(let_expr.pat, None, None, |_, _, _, _| {});
94222f64
XL
1398 }
1399
0bf4aa26 1400 // no correctness conditions related to liveness
dfeec247
XL
1401 hir::ExprKind::Call(..)
1402 | hir::ExprKind::MethodCall(..)
1403 | hir::ExprKind::Match(..)
1404 | hir::ExprKind::Loop(..)
1405 | hir::ExprKind::Index(..)
1406 | hir::ExprKind::Field(..)
1407 | hir::ExprKind::Array(..)
1408 | hir::ExprKind::Tup(..)
1409 | hir::ExprKind::Binary(..)
1410 | hir::ExprKind::Cast(..)
5869c6ff 1411 | hir::ExprKind::If(..)
dfeec247
XL
1412 | hir::ExprKind::DropTemps(..)
1413 | hir::ExprKind::Unary(..)
1414 | hir::ExprKind::Ret(..)
1415 | hir::ExprKind::Break(..)
1416 | hir::ExprKind::Continue(..)
1417 | hir::ExprKind::Lit(_)
29967ef6 1418 | hir::ExprKind::ConstBlock(..)
dfeec247
XL
1419 | hir::ExprKind::Block(..)
1420 | hir::ExprKind::AddrOf(..)
1421 | hir::ExprKind::Struct(..)
1422 | hir::ExprKind::Repeat(..)
923072b8 1423 | hir::ExprKind::Closure { .. }
dfeec247
XL
1424 | hir::ExprKind::Path(_)
1425 | hir::ExprKind::Yield(..)
dfeec247 1426 | hir::ExprKind::Type(..)
9ffffee4 1427 | hir::ExprKind::Err(_) => {}
223e47cc
LB
1428 }
1429}
1430
e74abb32 1431impl<'tcx> Liveness<'_, 'tcx> {
dfeec247 1432 fn check_place(&mut self, expr: &'tcx Expr<'tcx>) {
e74abb32 1433 match expr.kind {
8faf50e0 1434 hir::ExprKind::Path(hir::QPath::Resolved(_, ref path)) => {
48663c56 1435 if let Res::Local(var_hid) = path.res {
f9f354fc
XL
1436 // Assignment to an immutable variable or argument: only legal
1437 // if there is no later assignment. If this local is actually
1438 // mutable, then check for a reassignment to flag the mutability
1439 // as being used.
1440 let ln = self.live_node(expr.hir_id, expr.span);
1441 let var = self.variable(var_hid, expr.span);
1442 self.warn_about_dead_assign(vec![expr.span], expr.hir_id, ln, var);
223e47cc 1443 }
223e47cc 1444 }
1a4d82fc 1445 _ => {
2c00a5a8 1446 // For other kinds of places, no checks are required,
1a4d82fc 1447 // and any embedded expressions are actually rvalues
92a42be0 1448 intravisit::walk_expr(self, expr);
1a4d82fc 1449 }
223e47cc
LB
1450 }
1451 }
1452
1a4d82fc 1453 fn should_warn(&self, var: Variable) -> Option<String> {
223e47cc 1454 let name = self.ir.variable_name(var);
5869c6ff 1455 if name == kw::Empty {
1b1a35ee
XL
1456 return None;
1457 }
a2a8927a 1458 let name = name.as_str();
1b1a35ee
XL
1459 if name.as_bytes()[0] == b'_' {
1460 return None;
1461 }
1462 Some(name.to_owned())
223e47cc
LB
1463 }
1464
f9f354fc 1465 fn warn_about_unused_upvars(&self, entry_ln: LiveNode) {
5e7ed085
FG
1466 let Some(closure_min_captures) = self.closure_min_captures else {
1467 return;
f9f354fc 1468 };
fc512014 1469
6a06907d
XL
1470 // If closure_min_captures is Some(), upvars must be Some() too.
1471 for (&var_hir_id, min_capture_list) in closure_min_captures {
1472 for captured_place in min_capture_list {
1473 match captured_place.info.capture_kind {
5099ac24 1474 ty::UpvarCapture::ByValue => {}
6a06907d
XL
1475 ty::UpvarCapture::ByRef(..) => continue,
1476 };
1477 let span = captured_place.get_capture_kind_span(self.ir.tcx);
1478 let var = self.variable(var_hir_id, span);
1479 if self.used_on_entry(entry_ln, var) {
1480 if !self.live_on_entry(entry_ln, var) {
1481 if let Some(name) = self.should_warn(var) {
1482 self.ir.tcx.struct_span_lint_hir(
1483 lint::builtin::UNUSED_ASSIGNMENTS,
1484 var_hir_id,
1485 vec![span],
2b03887a
FG
1486 format!("value captured by `{}` is never read", name),
1487 |lint| lint.help("did you mean to capture by reference instead?"),
6a06907d
XL
1488 );
1489 }
1490 }
1491 } else {
f9f354fc
XL
1492 if let Some(name) = self.should_warn(var) {
1493 self.ir.tcx.struct_span_lint_hir(
6a06907d 1494 lint::builtin::UNUSED_VARIABLES,
f9f354fc 1495 var_hir_id,
6a06907d 1496 vec![span],
2b03887a
FG
1497 format!("unused variable: `{}`", name),
1498 |lint| lint.help("did you mean to capture by reference instead?"),
f9f354fc
XL
1499 );
1500 }
1501 }
f9f354fc
XL
1502 }
1503 }
1504 }
1505
dfeec247
XL
1506 fn warn_about_unused_args(&self, body: &hir::Body<'_>, entry_ln: LiveNode) {
1507 for p in body.params {
f2b60f7d
FG
1508 self.check_unused_vars_in_pat(
1509 &p.pat,
1510 Some(entry_ln),
1511 Some(body),
1512 |spans, hir_id, ln, var| {
1513 if !self.live_on_entry(ln, var) {
1514 self.report_unused_assign(hir_id, spans, var, |name| {
1515 format!("value passed to `{}` is never read", name)
1516 });
1517 }
1518 },
1519 );
223e47cc
LB
1520 }
1521 }
1522
e74abb32
XL
1523 fn check_unused_vars_in_pat(
1524 &self,
dfeec247 1525 pat: &hir::Pat<'_>,
e74abb32 1526 entry_ln: Option<LiveNode>,
f2b60f7d 1527 opt_body: Option<&hir::Body<'_>>,
e74abb32
XL
1528 on_used_on_entry: impl Fn(Vec<Span>, HirId, LiveNode, Variable),
1529 ) {
1530 // In an or-pattern, only consider the variable; any later patterns must have the same
1531 // bindings, and we also consider the first pattern to be the "authoritative" set of ids.
ba9703b0 1532 // However, we should take the ids and spans of variables with the same name from the later
e74abb32 1533 // patterns so the suggestions to prefix with underscores will apply to those too.
6a06907d
XL
1534 let mut vars: FxIndexMap<Symbol, (LiveNode, Variable, Vec<(HirId, Span, Span)>)> =
1535 <_>::default();
e74abb32
XL
1536
1537 pat.each_binding(|_, hir_id, pat_sp, ident| {
1538 let ln = entry_ln.unwrap_or_else(|| self.live_node(hir_id, pat_sp));
1539 let var = self.variable(hir_id, ident.span);
6a06907d 1540 let id_and_sp = (hir_id, pat_sp, ident.span);
e74abb32 1541 vars.entry(self.ir.variable_name(var))
ba9703b0
XL
1542 .and_modify(|(.., hir_ids_and_spans)| hir_ids_and_spans.push(id_and_sp))
1543 .or_insert_with(|| (ln, var, vec![id_and_sp]));
e74abb32
XL
1544 });
1545
487cf647
FG
1546 let can_remove = match pat.kind {
1547 hir::PatKind::Struct(_, fields, true) => {
1548 // if all fields are shorthand, remove the struct field, otherwise, mark with _ as prefix
1549 fields.iter().all(|f| f.is_shorthand)
1550 }
1551 _ => false,
1552 };
f2b60f7d 1553
ba9703b0 1554 for (_, (ln, var, hir_ids_and_spans)) in vars {
e74abb32 1555 if self.used_on_entry(ln, var) {
ba9703b0 1556 let id = hir_ids_and_spans[0].0;
6a06907d
XL
1557 let spans =
1558 hir_ids_and_spans.into_iter().map(|(_, _, ident_span)| ident_span).collect();
e74abb32
XL
1559 on_used_on_entry(spans, id, ln, var);
1560 } else {
f2b60f7d 1561 self.report_unused(hir_ids_and_spans, ln, var, can_remove, pat, opt_body);
223e47cc 1562 }
e74abb32 1563 }
223e47cc
LB
1564 }
1565
f2b60f7d 1566 #[instrument(skip(self), level = "INFO")]
6a06907d
XL
1567 fn report_unused(
1568 &self,
1569 hir_ids_and_spans: Vec<(HirId, Span, Span)>,
1570 ln: LiveNode,
1571 var: Variable,
f2b60f7d
FG
1572 can_remove: bool,
1573 pat: &hir::Pat<'_>,
1574 opt_body: Option<&hir::Body<'_>>,
6a06907d 1575 ) {
ba9703b0
XL
1576 let first_hir_id = hir_ids_and_spans[0].0;
1577
e74abb32
XL
1578 if let Some(name) = self.should_warn(var).filter(|name| name != "self") {
1579 // annoying: for parameters in funcs like `fn(x: i32)
1580 // {ret}`, there is only one node, so asking about
1581 // assigned_on_exit() is not meaningful.
dfeec247 1582 let is_assigned =
fc512014 1583 if ln == self.exit_ln { false } else { self.assigned_on_exit(ln, var) };
223e47cc 1584
e74abb32 1585 if is_assigned {
74b04a01
XL
1586 self.ir.tcx.struct_span_lint_hir(
1587 lint::builtin::UNUSED_VARIABLES,
ba9703b0 1588 first_hir_id,
6a06907d
XL
1589 hir_ids_and_spans
1590 .into_iter()
1591 .map(|(_, _, ident_span)| ident_span)
1592 .collect::<Vec<_>>(),
2b03887a
FG
1593 format!("variable `{}` is assigned to, but never used", name),
1594 |lint| lint.note(&format!("consider using `_{}` instead", name)),
74b04a01 1595 )
f2b60f7d
FG
1596 } else if can_remove {
1597 self.ir.tcx.struct_span_lint_hir(
1598 lint::builtin::UNUSED_VARIABLES,
1599 first_hir_id,
1600 hir_ids_and_spans.iter().map(|(_, pat_span, _)| *pat_span).collect::<Vec<_>>(),
2b03887a 1601 format!("unused variable: `{}`", name),
f2b60f7d 1602 |lint| {
2b03887a 1603 lint.multipart_suggestion(
f2b60f7d
FG
1604 "try removing the field",
1605 hir_ids_and_spans
1606 .iter()
1607 .map(|(_, pat_span, _)| {
1608 let span = self
1609 .ir
1610 .tcx
1611 .sess
1612 .source_map()
1613 .span_extend_to_next_char(*pat_span, ',', true);
1614 (span.with_hi(BytePos(span.hi().0 + 1)), String::new())
1615 })
1616 .collect(),
1617 Applicability::MachineApplicable,
2b03887a 1618 )
f2b60f7d
FG
1619 },
1620 );
e74abb32 1621 } else {
6a06907d
XL
1622 let (shorthands, non_shorthands): (Vec<_>, Vec<_>) =
1623 hir_ids_and_spans.iter().copied().partition(|(hir_id, _, ident_span)| {
1624 let var = self.variable(*hir_id, *ident_span);
1625 self.ir.variable_is_shorthand(var)
1626 });
ba9703b0 1627
6a06907d
XL
1628 // If we have both shorthand and non-shorthand, prefer the "try ignoring
1629 // the field" message, and suggest `_` for the non-shorthands. If we only
1630 // have non-shorthand, then prefix with an underscore instead.
1631 if !shorthands.is_empty() {
1632 let shorthands = shorthands
1633 .into_iter()
1634 .map(|(_, pat_span, _)| (pat_span, format!("{}: _", name)))
1635 .chain(
1636 non_shorthands
1637 .into_iter()
1638 .map(|(_, pat_span, _)| (pat_span, "_".to_string())),
1639 )
1640 .collect::<Vec<_>>();
1641
1642 self.ir.tcx.struct_span_lint_hir(
1643 lint::builtin::UNUSED_VARIABLES,
1644 first_hir_id,
1645 hir_ids_and_spans
1646 .iter()
1647 .map(|(_, pat_span, _)| *pat_span)
1648 .collect::<Vec<_>>(),
2b03887a 1649 format!("unused variable: `{}`", name),
6a06907d 1650 |lint| {
2b03887a 1651 lint.multipart_suggestion(
ba9703b0
XL
1652 "try ignoring the field",
1653 shorthands,
1654 Applicability::MachineApplicable,
2b03887a 1655 )
6a06907d
XL
1656 },
1657 );
1658 } else {
1659 let non_shorthands = non_shorthands
1660 .into_iter()
1661 .map(|(_, _, ident_span)| (ident_span, format!("_{}", name)))
1662 .collect::<Vec<_>>();
1663
1664 self.ir.tcx.struct_span_lint_hir(
1665 lint::builtin::UNUSED_VARIABLES,
1666 first_hir_id,
1667 hir_ids_and_spans
1668 .iter()
1669 .map(|(_, _, ident_span)| *ident_span)
1670 .collect::<Vec<_>>(),
2b03887a 1671 format!("unused variable: `{}`", name),
6a06907d 1672 |lint| {
2b03887a
FG
1673 if self.has_added_lit_match_name_span(&name, opt_body, lint) {
1674 lint.span_label(pat.span, "unused variable");
f2b60f7d 1675 }
2b03887a 1676 lint.multipart_suggestion(
ba9703b0 1677 "if this is intentional, prefix it with an underscore",
6a06907d 1678 non_shorthands,
74b04a01 1679 Applicability::MachineApplicable,
2b03887a 1680 )
6a06907d
XL
1681 },
1682 );
1683 }
223e47cc 1684 }
223e47cc 1685 }
223e47cc
LB
1686 }
1687
f2b60f7d
FG
1688 fn has_added_lit_match_name_span(
1689 &self,
1690 name: &str,
1691 opt_body: Option<&hir::Body<'_>>,
487cf647 1692 err: &mut Diagnostic,
f2b60f7d
FG
1693 ) -> bool {
1694 let mut has_litstring = false;
1695 let Some(opt_body) = opt_body else {return false;};
1696 let mut visitor = CollectLitsVisitor { lit_exprs: vec![] };
1697 intravisit::walk_body(&mut visitor, opt_body);
1698 for lit_expr in visitor.lit_exprs {
1699 let hir::ExprKind::Lit(litx) = &lit_expr.kind else { continue };
1700 let rustc_ast::LitKind::Str(syb, _) = litx.node else{ continue; };
1701 let name_str: &str = syb.as_str();
1702 let mut name_pa = String::from("{");
1703 name_pa.push_str(&name);
1704 name_pa.push('}');
1705 if name_str.contains(&name_pa) {
1706 err.span_label(
1707 lit_expr.span,
1708 "you might have meant to use string interpolation in this string literal",
1709 );
1710 err.multipart_suggestion(
1711 "string interpolation only works in `format!` invocations",
1712 vec![
1713 (lit_expr.span.shrink_to_lo(), "format!(".to_string()),
1714 (lit_expr.span.shrink_to_hi(), ")".to_string()),
1715 ],
1716 Applicability::MachineApplicable,
1717 );
1718 has_litstring = true;
1719 }
1720 }
1721 has_litstring
1722 }
1723
e74abb32 1724 fn warn_about_dead_assign(&self, spans: Vec<Span>, hir_id: HirId, ln: LiveNode, var: Variable) {
fc512014 1725 if !self.live_on_exit(ln, var) {
cdc7bbd5 1726 self.report_unused_assign(hir_id, spans, var, |name| {
f9f354fc
XL
1727 format!("value assigned to `{}` is never read", name)
1728 });
92a42be0
SL
1729 }
1730 }
1731
cdc7bbd5 1732 fn report_unused_assign(
f9f354fc
XL
1733 &self,
1734 hir_id: HirId,
1735 spans: Vec<Span>,
1736 var: Variable,
1737 message: impl Fn(&str) -> String,
1738 ) {
92a42be0 1739 if let Some(name) = self.should_warn(var) {
f9f354fc
XL
1740 self.ir.tcx.struct_span_lint_hir(
1741 lint::builtin::UNUSED_ASSIGNMENTS,
1742 hir_id,
1743 spans,
2b03887a
FG
1744 message(&name),
1745 |lint| lint.help("maybe it is overwritten before being read?"),
f9f354fc 1746 )
223e47cc
LB
1747 }
1748 }
92a42be0 1749}