rustc_passes/
liveness.rs

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