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