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