1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! A classic liveness analysis based on dataflow over the AST. Computes,
12 //! for each local variable in a function, whether that variable is live
13 //! at a given point. Program execution points are identified by their
18 //! The basic model is that each local variable is assigned an index. We
19 //! represent sets of local variables using a vector indexed by this
20 //! index. The value in the vector is either 0, indicating the variable
21 //! is dead, or the id of an expression that uses the variable.
23 //! We conceptually walk over the AST in reverse execution order. If we
24 //! find a use of a variable, we add it to the set of live variables. If
25 //! we find an assignment to a variable, we remove it from the set of live
26 //! variables. When we have to merge two flows, we take the union of
27 //! those two flows---if the variable is live on both paths, we simply
28 //! pick one id. In the event of loops, we continue doing this until a
29 //! fixed point is reached.
31 //! ## Checking initialization
33 //! At the function entry point, all variables must be dead. If this is
34 //! not the case, we can report an error using the id found in the set of
35 //! live variables, which identifies a use of the variable which is not
36 //! dominated by an assignment.
40 //! After each explicit move, the variable must be dead.
42 //! ## Computing last uses
44 //! Any use of the variable where the variable is dead afterwards is a
47 //! # Implementation details
49 //! The actual implementation contains two (nested) walks over the AST.
50 //! The outer walk has the job of building up the ir_maps instance for the
51 //! enclosing function. On the way down the tree, it identifies those AST
52 //! nodes and variable IDs that will be needed for the liveness analysis
53 //! and assigns them contiguous IDs. The liveness id for an AST node is
54 //! called a `live_node` (it's a newtype'd usize) and the id for a variable
55 //! is called a `variable` (another newtype'd usize).
57 //! On the way back up the tree, as we are about to exit from a function
58 //! declaration we allocate a `liveness` instance. Now that we know
59 //! precisely how many nodes and variables we need, we can allocate all
60 //! the various arrays that we will need to precisely the right size. We then
61 //! perform the actual propagation on the `liveness` instance.
63 //! This propagation is encoded in the various `propagate_through_*()`
64 //! methods. It effectively does a reverse walk of the AST; whenever we
65 //! reach a loop node, we iterate until a fixed point is reached.
67 //! ## The `Users` struct
69 //! At each live node `N`, we track three pieces of information for each
70 //! variable `V` (these are encapsulated in the `Users` struct):
72 //! - `reader`: the `LiveNode` ID of some node which will read the value
73 //! that `V` holds on entry to `N`. Formally: a node `M` such
74 //! that there exists a path `P` from `N` to `M` where `P` does not
75 //! write `V`. If the `reader` is `invalid_node()`, then the current
76 //! value will never be read (the variable is dead, essentially).
78 //! - `writer`: the `LiveNode` ID of some node which will write the
79 //! variable `V` and which is reachable from `N`. Formally: a node `M`
80 //! such that there exists a path `P` from `N` to `M` and `M` writes
81 //! `V`. If the `writer` is `invalid_node()`, then there is no writer
82 //! of `V` that follows `N`.
84 //! - `used`: a boolean value indicating whether `V` is *used*. We
85 //! distinguish a *read* from a *use* in that a *use* is some read that
86 //! is not just used to generate a new value. For example, `x += 1` is
87 //! a read but not a use. This is used to generate better warnings.
89 //! ## Special Variables
91 //! We generate various special variables for various, well, special purposes.
92 //! These are described in the `specials` struct:
94 //! - `exit_ln`: a live node that is generated to represent every 'exit' from
95 //! the function, whether it be by explicit return, panic, or other means.
97 //! - `fallthrough_ln`: a live node that represents a fallthrough
99 //! - `clean_exit_var`: a synthetic variable that is only 'read' from the
100 //! fallthrough node. It is only live if the function could converge
101 //! via means other than an explicit `return` expression. That is, it is
102 //! only dead if the end of the function's block can never be reached.
103 //! It is the responsibility of typeck to ensure that there are no
104 //! `return` expressions in a function declared as diverging.
105 use self::LoopKind::*;
106 use self::LiveNodeKind::*;
107 use self::VarKind::*;
110 use ty::{self, TyCtxt};
112 use util::nodemap::{NodeMap, NodeSet};
114 use std::collections::VecDeque;
115 use std::{fmt, usize};
116 use std::io::prelude::*;
119 use syntax::ast::{self, NodeId};
120 use syntax::symbol::keywords;
121 use syntax_pos::Span;
125 use hir::intravisit::{self, Visitor, FnKind, NestedVisitorMap};
127 /// For use with `propagate_through_loop`.
129 /// An endless `loop` loop.
131 /// A `while` loop, with the given expression as condition.
135 #[derive(Copy, Clone, PartialEq)]
136 struct Variable(usize);
138 #[derive(Copy, PartialEq)]
139 struct LiveNode(usize);
142 fn get(&self) -> usize { let Variable(v) = *self; v }
146 fn get(&self) -> usize { let LiveNode(v) = *self; v }
149 impl Clone for LiveNode {
150 fn clone(&self) -> LiveNode {
155 #[derive(Copy, Clone, PartialEq, Debug)]
163 fn live_node_kind_to_string(lnk: LiveNodeKind, tcx: TyCtxt) -> String {
164 let cm = tcx.sess.codemap();
167 format!("Free var node [{}]", cm.span_to_string(s))
170 format!("Expr node [{}]", cm.span_to_string(s))
173 format!("Var def node [{}]", cm.span_to_string(s))
175 ExitNode => "Exit node".to_string(),
179 impl<'a, 'tcx> Visitor<'tcx> for IrMaps<'a, 'tcx> {
180 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
181 NestedVisitorMap::OnlyBodies(&self.tcx.hir)
184 fn visit_fn(&mut self, fk: FnKind<'tcx>, fd: &'tcx hir::FnDecl,
185 b: hir::BodyId, s: Span, id: NodeId) {
186 visit_fn(self, fk, fd, b, s, id);
189 fn visit_local(&mut self, l: &'tcx hir::Local) { visit_local(self, l); }
190 fn visit_expr(&mut self, ex: &'tcx Expr) { visit_expr(self, ex); }
191 fn visit_arm(&mut self, a: &'tcx hir::Arm) { visit_arm(self, a); }
194 pub fn check_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
195 tcx.hir.krate().visit_all_item_likes(&mut IrMaps::new(tcx).as_deep_visitor());
196 tcx.sess.abort_if_errors();
199 impl fmt::Debug for LiveNode {
200 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
201 write!(f, "ln({})", self.get())
205 impl fmt::Debug for Variable {
206 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
207 write!(f, "v({})", self.get())
211 // ______________________________________________________________________
214 // This is the first pass and the one that drives the main
215 // computation. It walks up and down the IR once. On the way down,
216 // we count for each function the number of variables as well as
217 // liveness nodes. A liveness node is basically an expression or
218 // capture clause that does something of interest: either it has
219 // interesting control flow or it uses/defines a local variable.
221 // On the way back up, at each function node we create liveness sets
222 // (we now know precisely how big to make our various vectors and so
223 // forth) and then do the data-flow propagation to compute the set
224 // of live variables at each program point.
226 // Finally, we run back over the IR one last time and, using the
227 // computed liveness, check various safety conditions. For example,
228 // there must be no live nodes at the definition site for a variable
229 // unless it has an initializer. Similarly, each non-mutable local
230 // variable must not be assigned if there is some successor
231 // assignment. And so forth.
234 fn is_valid(&self) -> bool {
235 self.get() != usize::MAX
239 fn invalid_node() -> LiveNode { LiveNode(usize::MAX) }
246 #[derive(Copy, Clone, Debug)]
253 #[derive(Copy, Clone, Debug)]
255 Arg(NodeId, ast::Name),
260 struct IrMaps<'a, 'tcx: 'a> {
261 tcx: TyCtxt<'a, 'tcx, 'tcx>,
263 num_live_nodes: usize,
265 live_node_map: NodeMap<LiveNode>,
266 variable_map: NodeMap<Variable>,
267 capture_info_map: NodeMap<Rc<Vec<CaptureInfo>>>,
268 var_kinds: Vec<VarKind>,
269 lnks: Vec<LiveNodeKind>,
272 impl<'a, 'tcx> IrMaps<'a, 'tcx> {
273 fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> IrMaps<'a, 'tcx> {
278 live_node_map: NodeMap(),
279 variable_map: NodeMap(),
280 capture_info_map: NodeMap(),
281 var_kinds: Vec::new(),
286 fn add_live_node(&mut self, lnk: LiveNodeKind) -> LiveNode {
287 let ln = LiveNode(self.num_live_nodes);
289 self.num_live_nodes += 1;
291 debug!("{:?} is of kind {}", ln,
292 live_node_kind_to_string(lnk, self.tcx));
297 fn add_live_node_for_node(&mut self, node_id: NodeId, lnk: LiveNodeKind) {
298 let ln = self.add_live_node(lnk);
299 self.live_node_map.insert(node_id, ln);
301 debug!("{:?} is node {}", ln, node_id);
304 fn add_variable(&mut self, vk: VarKind) -> Variable {
305 let v = Variable(self.num_vars);
306 self.var_kinds.push(vk);
310 Local(LocalInfo { id: node_id, .. }) | Arg(node_id, _) => {
311 self.variable_map.insert(node_id, v);
316 debug!("{:?} is {:?}", v, vk);
321 fn variable(&self, node_id: NodeId, span: Span) -> Variable {
322 match self.variable_map.get(&node_id) {
325 span_bug!(span, "no variable registered for id {}", node_id);
330 fn variable_name(&self, var: Variable) -> String {
331 match self.var_kinds[var.get()] {
332 Local(LocalInfo { name, .. }) | Arg(_, name) => {
335 CleanExit => "<clean-exit>".to_string()
339 fn variable_is_shorthand(&self, var: Variable) -> bool {
340 match self.var_kinds[var.get()] {
341 Local(LocalInfo { is_shorthand, .. }) => is_shorthand,
342 Arg(..) | CleanExit => false
346 fn set_captures(&mut self, node_id: NodeId, cs: Vec<CaptureInfo>) {
347 self.capture_info_map.insert(node_id, Rc::new(cs));
350 fn lnk(&self, ln: LiveNode) -> LiveNodeKind {
355 fn visit_fn<'a, 'tcx: 'a>(ir: &mut IrMaps<'a, 'tcx>,
357 decl: &'tcx hir::FnDecl,
358 body_id: hir::BodyId,
363 // swap in a new set of IR maps for this function body:
364 let mut fn_maps = IrMaps::new(ir.tcx);
366 // Don't run unused pass for #[derive()]
367 if let FnKind::Method(..) = fk {
368 let parent = ir.tcx.hir.get_parent(id);
369 if let Some(hir::map::Node::NodeItem(i)) = ir.tcx.hir.find(parent) {
370 if i.attrs.iter().any(|a| a.check_name("automatically_derived")) {
376 debug!("creating fn_maps: {:?}", &fn_maps as *const IrMaps);
378 let body = ir.tcx.hir.body(body_id);
380 for arg in &body.arguments {
381 arg.pat.each_binding(|_bm, arg_id, _x, path1| {
382 debug!("adding argument {}", arg_id);
383 let name = path1.node;
384 fn_maps.add_variable(Arg(arg_id, name));
388 // gather up the various local variables, significant expressions,
390 intravisit::walk_fn(&mut fn_maps, fk, decl, body_id, sp, id);
393 let mut lsets = Liveness::new(&mut fn_maps, body_id);
394 let entry_ln = lsets.compute(&body.value);
396 // check for various error conditions
397 lsets.visit_body(body);
398 lsets.warn_about_unused_args(body, entry_ln);
401 fn visit_local<'a, 'tcx>(ir: &mut IrMaps<'a, 'tcx>, local: &'tcx hir::Local) {
402 local.pat.each_binding(|_, p_id, sp, path1| {
403 debug!("adding local variable {}", p_id);
404 let name = path1.node;
405 ir.add_live_node_for_node(p_id, VarDefNode(sp));
406 ir.add_variable(Local(LocalInfo {
412 intravisit::walk_local(ir, local);
415 fn visit_arm<'a, 'tcx>(ir: &mut IrMaps<'a, 'tcx>, arm: &'tcx hir::Arm) {
416 for mut pat in &arm.pats {
417 // For struct patterns, take note of which fields used shorthand
418 // (`x` rather than `x: x`).
420 // FIXME: according to the rust-lang-nursery/rustc-guide book, `NodeId`s are to be
421 // phased out in favor of `HirId`s; however, we need to match the signature of
422 // `each_binding`, which uses `NodeIds`.
423 let mut shorthand_field_ids = NodeSet();
424 let mut pats = VecDeque::new();
426 while let Some(pat) = pats.pop_front() {
429 Binding(_, _, _, ref inner_pat) => {
430 pats.extend(inner_pat.iter());
432 Struct(_, ref fields, _) => {
433 for field in fields {
434 if field.node.is_shorthand {
435 shorthand_field_ids.insert(field.node.pat.id);
439 Ref(ref inner_pat, _) |
440 Box(ref inner_pat) => {
441 pats.push_back(inner_pat);
443 TupleStruct(_, ref inner_pats, _) |
444 Tuple(ref inner_pats, _) => {
445 pats.extend(inner_pats.iter());
447 Slice(ref pre_pats, ref inner_pat, ref post_pats) => {
448 pats.extend(pre_pats.iter());
449 pats.extend(inner_pat.iter());
450 pats.extend(post_pats.iter());
456 pat.each_binding(|bm, p_id, _sp, path1| {
457 debug!("adding local variable {} from match with bm {:?}",
459 let name = path1.node;
460 ir.add_live_node_for_node(p_id, VarDefNode(path1.span));
461 ir.add_variable(Local(LocalInfo {
464 is_shorthand: shorthand_field_ids.contains(&p_id)
468 intravisit::walk_arm(ir, arm);
471 fn visit_expr<'a, 'tcx>(ir: &mut IrMaps<'a, 'tcx>, expr: &'tcx Expr) {
473 // live nodes required for uses or definitions of variables:
474 hir::ExprPath(hir::QPath::Resolved(_, ref path)) => {
475 debug!("expr {}: path that leads to {:?}", expr.id, path.def);
476 if let Def::Local(..) = path.def {
477 ir.add_live_node_for_node(expr.id, ExprNode(expr.span));
479 intravisit::walk_expr(ir, expr);
481 hir::ExprClosure(..) => {
482 // Interesting control flow (for loops can contain labeled
483 // breaks or continues)
484 ir.add_live_node_for_node(expr.id, ExprNode(expr.span));
486 // Make a live_node for each captured variable, with the span
487 // being the location that the variable is used. This results
488 // in better error messages than just pointing at the closure
489 // construction site.
490 let mut call_caps = Vec::new();
491 ir.tcx.with_freevars(expr.id, |freevars| {
493 if let Def::Local(rv) = fv.def {
494 let fv_ln = ir.add_live_node(FreeVarNode(fv.span));
495 call_caps.push(CaptureInfo {ln: fv_ln,
500 ir.set_captures(expr.id, call_caps);
502 intravisit::walk_expr(ir, expr);
505 // live nodes required for interesting control flow:
506 hir::ExprIf(..) | hir::ExprMatch(..) | hir::ExprWhile(..) | hir::ExprLoop(..) => {
507 ir.add_live_node_for_node(expr.id, ExprNode(expr.span));
508 intravisit::walk_expr(ir, expr);
510 hir::ExprBinary(op, ..) if op.node.is_lazy() => {
511 ir.add_live_node_for_node(expr.id, ExprNode(expr.span));
512 intravisit::walk_expr(ir, expr);
515 // otherwise, live nodes are not required:
516 hir::ExprIndex(..) | hir::ExprField(..) |
517 hir::ExprArray(..) | hir::ExprCall(..) | hir::ExprMethodCall(..) |
518 hir::ExprTup(..) | hir::ExprBinary(..) | hir::ExprAddrOf(..) |
519 hir::ExprCast(..) | hir::ExprUnary(..) | hir::ExprBreak(..) |
520 hir::ExprAgain(_) | hir::ExprLit(_) | hir::ExprRet(..) |
521 hir::ExprBlock(..) | hir::ExprAssign(..) | hir::ExprAssignOp(..) |
522 hir::ExprStruct(..) | hir::ExprRepeat(..) |
523 hir::ExprInlineAsm(..) | hir::ExprBox(..) | hir::ExprYield(..) |
524 hir::ExprType(..) | hir::ExprPath(hir::QPath::TypeRelative(..)) => {
525 intravisit::walk_expr(ir, expr);
530 // ______________________________________________________________________
531 // Computing liveness sets
533 // Actually we compute just a bit more than just liveness, but we use
534 // the same basic propagation framework in all cases.
536 #[derive(Clone, Copy)]
543 fn invalid_users() -> Users {
545 reader: invalid_node(),
546 writer: invalid_node(),
551 #[derive(Copy, Clone)]
554 fallthrough_ln: LiveNode,
555 clean_exit_var: Variable
558 const ACC_READ: u32 = 1;
559 const ACC_WRITE: u32 = 2;
560 const ACC_USE: u32 = 4;
562 struct Liveness<'a, 'tcx: 'a> {
563 ir: &'a mut IrMaps<'a, 'tcx>,
564 tables: &'a ty::TypeckTables<'tcx>,
566 successors: Vec<LiveNode>,
569 // mappings from loop node ID to LiveNode
570 // ("break" label should map to loop node ID,
571 // it probably doesn't now)
572 break_ln: NodeMap<LiveNode>,
573 cont_ln: NodeMap<LiveNode>,
576 impl<'a, 'tcx> Liveness<'a, 'tcx> {
577 fn new(ir: &'a mut IrMaps<'a, 'tcx>, body: hir::BodyId) -> Liveness<'a, 'tcx> {
578 // Special nodes and variables:
579 // - exit_ln represents the end of the fn, either by return or panic
580 // - implicit_ret_var is a pseudo-variable that represents
581 // an implicit return
582 let specials = Specials {
583 exit_ln: ir.add_live_node(ExitNode),
584 fallthrough_ln: ir.add_live_node(ExitNode),
585 clean_exit_var: ir.add_variable(CleanExit)
588 let tables = ir.tcx.body_tables(body);
590 let num_live_nodes = ir.num_live_nodes;
591 let num_vars = ir.num_vars;
597 successors: vec![invalid_node(); num_live_nodes],
598 users: vec![invalid_users(); num_live_nodes * num_vars],
604 fn live_node(&self, node_id: NodeId, span: Span) -> LiveNode {
605 match self.ir.live_node_map.get(&node_id) {
608 // This must be a mismatch between the ir_map construction
609 // above and the propagation code below; the two sets of
610 // code have to agree about which AST nodes are worth
611 // creating liveness nodes for.
614 "no live node registered for node {}",
620 fn variable(&self, node_id: NodeId, span: Span) -> Variable {
621 self.ir.variable(node_id, span)
624 fn pat_bindings<F>(&mut self, pat: &hir::Pat, mut f: F) where
625 F: FnMut(&mut Liveness<'a, 'tcx>, LiveNode, Variable, Span, NodeId),
627 pat.each_binding(|_bm, p_id, sp, n| {
628 let ln = self.live_node(p_id, sp);
629 let var = self.variable(p_id, n.span);
630 f(self, ln, var, n.span, p_id);
634 fn arm_pats_bindings<F>(&mut self, pat: Option<&hir::Pat>, f: F) where
635 F: FnMut(&mut Liveness<'a, 'tcx>, LiveNode, Variable, Span, NodeId),
637 if let Some(pat) = pat {
638 self.pat_bindings(pat, f);
642 fn define_bindings_in_pat(&mut self, pat: &hir::Pat, succ: LiveNode)
644 self.define_bindings_in_arm_pats(Some(pat), succ)
647 fn define_bindings_in_arm_pats(&mut self, pat: Option<&hir::Pat>, succ: LiveNode)
650 self.arm_pats_bindings(pat, |this, ln, var, _sp, _id| {
651 this.init_from_succ(ln, succ);
652 this.define(ln, var);
658 fn idx(&self, ln: LiveNode, var: Variable) -> usize {
659 ln.get() * self.ir.num_vars + var.get()
662 fn live_on_entry(&self, ln: LiveNode, var: Variable)
663 -> Option<LiveNodeKind> {
664 assert!(ln.is_valid());
665 let reader = self.users[self.idx(ln, var)].reader;
666 if reader.is_valid() {Some(self.ir.lnk(reader))} else {None}
670 Is this variable live on entry to any of its successor nodes?
672 fn live_on_exit(&self, ln: LiveNode, var: Variable)
673 -> Option<LiveNodeKind> {
674 let successor = self.successors[ln.get()];
675 self.live_on_entry(successor, var)
678 fn used_on_entry(&self, ln: LiveNode, var: Variable) -> bool {
679 assert!(ln.is_valid());
680 self.users[self.idx(ln, var)].used
683 fn assigned_on_entry(&self, ln: LiveNode, var: Variable)
684 -> Option<LiveNodeKind> {
685 assert!(ln.is_valid());
686 let writer = self.users[self.idx(ln, var)].writer;
687 if writer.is_valid() {Some(self.ir.lnk(writer))} else {None}
690 fn assigned_on_exit(&self, ln: LiveNode, var: Variable)
691 -> Option<LiveNodeKind> {
692 let successor = self.successors[ln.get()];
693 self.assigned_on_entry(successor, var)
696 fn indices2<F>(&mut self, ln: LiveNode, succ_ln: LiveNode, mut op: F) where
697 F: FnMut(&mut Liveness<'a, 'tcx>, usize, usize),
699 let node_base_idx = self.idx(ln, Variable(0));
700 let succ_base_idx = self.idx(succ_ln, Variable(0));
701 for var_idx in 0..self.ir.num_vars {
702 op(self, node_base_idx + var_idx, succ_base_idx + var_idx);
706 fn write_vars<F>(&self,
710 -> io::Result<()> where
711 F: FnMut(usize) -> LiveNode,
713 let node_base_idx = self.idx(ln, Variable(0));
714 for var_idx in 0..self.ir.num_vars {
715 let idx = node_base_idx + var_idx;
716 if test(idx).is_valid() {
717 write!(wr, " {:?}", Variable(var_idx))?;
724 #[allow(unused_must_use)]
725 fn ln_str(&self, ln: LiveNode) -> String {
726 let mut wr = Vec::new();
728 let wr = &mut wr as &mut dyn Write;
729 write!(wr, "[ln({:?}) of kind {:?} reads", ln.get(), self.ir.lnk(ln));
730 self.write_vars(wr, ln, |idx| self.users[idx].reader);
731 write!(wr, " writes");
732 self.write_vars(wr, ln, |idx| self.users[idx].writer);
733 write!(wr, " precedes {:?}]", self.successors[ln.get()]);
735 String::from_utf8(wr).unwrap()
738 fn init_empty(&mut self, ln: LiveNode, succ_ln: LiveNode) {
739 self.successors[ln.get()] = succ_ln;
741 // It is not necessary to initialize the
742 // values to empty because this is the value
743 // they have when they are created, and the sets
744 // only grow during iterations.
746 // self.indices(ln) { |idx|
747 // self.users[idx] = invalid_users();
751 fn init_from_succ(&mut self, ln: LiveNode, succ_ln: LiveNode) {
752 // more efficient version of init_empty() / merge_from_succ()
753 self.successors[ln.get()] = succ_ln;
755 self.indices2(ln, succ_ln, |this, idx, succ_idx| {
756 this.users[idx] = this.users[succ_idx]
758 debug!("init_from_succ(ln={}, succ={})",
759 self.ln_str(ln), self.ln_str(succ_ln));
762 fn merge_from_succ(&mut self,
767 if ln == succ_ln { return false; }
769 let mut changed = false;
770 self.indices2(ln, succ_ln, |this, idx, succ_idx| {
771 changed |= copy_if_invalid(this.users[succ_idx].reader,
772 &mut this.users[idx].reader);
773 changed |= copy_if_invalid(this.users[succ_idx].writer,
774 &mut this.users[idx].writer);
775 if this.users[succ_idx].used && !this.users[idx].used {
776 this.users[idx].used = true;
781 debug!("merge_from_succ(ln={:?}, succ={}, first_merge={}, changed={})",
782 ln, self.ln_str(succ_ln), first_merge, changed);
785 fn copy_if_invalid(src: LiveNode, dst: &mut LiveNode) -> bool {
786 if src.is_valid() && !dst.is_valid() {
795 // Indicates that a local variable was *defined*; we know that no
796 // uses of the variable can precede the definition (resolve checks
797 // this) so we just clear out all the data.
798 fn define(&mut self, writer: LiveNode, var: Variable) {
799 let idx = self.idx(writer, var);
800 self.users[idx].reader = invalid_node();
801 self.users[idx].writer = invalid_node();
803 debug!("{:?} defines {:?} (idx={}): {}", writer, var,
804 idx, self.ln_str(writer));
807 // Either read, write, or both depending on the acc bitset
808 fn acc(&mut self, ln: LiveNode, var: Variable, acc: u32) {
809 debug!("{:?} accesses[{:x}] {:?}: {}",
810 ln, acc, var, self.ln_str(ln));
812 let idx = self.idx(ln, var);
813 let user = &mut self.users[idx];
815 if (acc & ACC_WRITE) != 0 {
816 user.reader = invalid_node();
820 // Important: if we both read/write, must do read second
821 // or else the write will override.
822 if (acc & ACC_READ) != 0 {
826 if (acc & ACC_USE) != 0 {
831 // _______________________________________________________________________
833 fn compute(&mut self, body: &hir::Expr) -> LiveNode {
834 // if there is a `break` or `again` at the top level, then it's
835 // effectively a return---this only occurs in `for` loops,
836 // where the body is really a closure.
838 debug!("compute: using id for body, {}", self.ir.tcx.hir.node_to_pretty_string(body.id));
840 let exit_ln = self.s.exit_ln;
842 self.break_ln.insert(body.id, exit_ln);
843 self.cont_ln.insert(body.id, exit_ln);
845 // the fallthrough exit is only for those cases where we do not
846 // explicitly return:
848 self.init_from_succ(s.fallthrough_ln, s.exit_ln);
849 self.acc(s.fallthrough_ln, s.clean_exit_var, ACC_READ);
851 let entry_ln = self.propagate_through_expr(body, s.fallthrough_ln);
853 // hack to skip the loop unless debug! is enabled:
854 debug!("^^ liveness computation results for body {} (entry={:?})",
856 for ln_idx in 0..self.ir.num_live_nodes {
857 debug!("{:?}", self.ln_str(LiveNode(ln_idx)));
866 fn propagate_through_block(&mut self, blk: &hir::Block, succ: LiveNode)
868 if blk.targeted_by_break {
869 self.break_ln.insert(blk.id, succ);
871 let succ = self.propagate_through_opt_expr(blk.expr.as_ref().map(|e| &**e), succ);
872 blk.stmts.iter().rev().fold(succ, |succ, stmt| {
873 self.propagate_through_stmt(stmt, succ)
877 fn propagate_through_stmt(&mut self, stmt: &hir::Stmt, succ: LiveNode)
880 hir::StmtDecl(ref decl, _) => {
881 self.propagate_through_decl(&decl, succ)
884 hir::StmtExpr(ref expr, _) | hir::StmtSemi(ref expr, _) => {
885 self.propagate_through_expr(&expr, succ)
890 fn propagate_through_decl(&mut self, decl: &hir::Decl, succ: LiveNode)
893 hir::DeclLocal(ref local) => {
894 self.propagate_through_local(&local, succ)
896 hir::DeclItem(_) => succ,
900 fn propagate_through_local(&mut self, local: &hir::Local, succ: LiveNode)
902 // Note: we mark the variable as defined regardless of whether
903 // there is an initializer. Initially I had thought to only mark
904 // the live variable as defined if it was initialized, and then we
905 // could check for uninit variables just by scanning what is live
906 // at the start of the function. But that doesn't work so well for
907 // immutable variables defined in a loop:
908 // loop { let x; x = 5; }
909 // because the "assignment" loops back around and generates an error.
911 // So now we just check that variables defined w/o an
912 // initializer are not live at the point of their
913 // initialization, which is mildly more complex than checking
914 // once at the func header but otherwise equivalent.
916 let succ = self.propagate_through_opt_expr(local.init.as_ref().map(|e| &**e), succ);
917 self.define_bindings_in_pat(&local.pat, succ)
920 fn propagate_through_exprs(&mut self, exprs: &[Expr], succ: LiveNode)
922 exprs.iter().rev().fold(succ, |succ, expr| {
923 self.propagate_through_expr(&expr, succ)
927 fn propagate_through_opt_expr(&mut self,
928 opt_expr: Option<&Expr>,
931 opt_expr.map_or(succ, |expr| self.propagate_through_expr(expr, succ))
934 fn propagate_through_expr(&mut self, expr: &Expr, succ: LiveNode)
936 debug!("propagate_through_expr: {}", self.ir.tcx.hir.node_to_pretty_string(expr.id));
939 // Interesting cases with control flow or which gen/kill
940 hir::ExprPath(hir::QPath::Resolved(_, ref path)) => {
941 self.access_path(expr.id, path, succ, ACC_READ | ACC_USE)
944 hir::ExprField(ref e, _) => {
945 self.propagate_through_expr(&e, succ)
948 hir::ExprClosure(.., blk_id, _, _) => {
949 debug!("{} is an ExprClosure", self.ir.tcx.hir.node_to_pretty_string(expr.id));
952 The next-node for a break is the successor of the entire
953 loop. The next-node for a continue is the top of this loop.
955 let node = self.live_node(expr.id, expr.span);
959 self.break_ln.insert(blk_id.node_id, break_ln);
960 self.cont_ln.insert(blk_id.node_id, cont_ln);
962 // the construction of a closure itself is not important,
963 // but we have to consider the closed over variables.
964 let caps = match self.ir.capture_info_map.get(&expr.id) {
965 Some(caps) => caps.clone(),
967 span_bug!(expr.span, "no registered caps");
970 caps.iter().rev().fold(succ, |succ, cap| {
971 self.init_from_succ(cap.ln, succ);
972 let var = self.variable(cap.var_nid, expr.span);
973 self.acc(cap.ln, var, ACC_READ | ACC_USE);
978 hir::ExprIf(ref cond, ref then, ref els) => {
992 let else_ln = self.propagate_through_opt_expr(els.as_ref().map(|e| &**e), succ);
993 let then_ln = self.propagate_through_expr(&then, succ);
994 let ln = self.live_node(expr.id, expr.span);
995 self.init_from_succ(ln, else_ln);
996 self.merge_from_succ(ln, then_ln, false);
997 self.propagate_through_expr(&cond, ln)
1000 hir::ExprWhile(ref cond, ref blk, _) => {
1001 self.propagate_through_loop(expr, WhileLoop(&cond), &blk, succ)
1004 // Note that labels have been resolved, so we don't need to look
1005 // at the label ident
1006 hir::ExprLoop(ref blk, _, _) => {
1007 self.propagate_through_loop(expr, LoopLoop, &blk, succ)
1010 hir::ExprMatch(ref e, ref arms, _) => {
1025 let ln = self.live_node(expr.id, expr.span);
1026 self.init_empty(ln, succ);
1027 let mut first_merge = true;
1030 self.propagate_through_expr(&arm.body, succ);
1032 self.propagate_through_opt_expr(arm.guard.as_ref().map(|e| &**e), body_succ);
1033 // only consider the first pattern; any later patterns must have
1034 // the same bindings, and we also consider the first pattern to be
1035 // the "authoritative" set of ids
1037 self.define_bindings_in_arm_pats(arm.pats.first().map(|p| &**p),
1039 self.merge_from_succ(ln, arm_succ, first_merge);
1040 first_merge = false;
1042 self.propagate_through_expr(&e, ln)
1045 hir::ExprRet(ref o_e) => {
1046 // ignore succ and subst exit_ln:
1047 let exit_ln = self.s.exit_ln;
1048 self.propagate_through_opt_expr(o_e.as_ref().map(|e| &**e), exit_ln)
1051 hir::ExprBreak(label, ref opt_expr) => {
1052 // Find which label this break jumps to
1053 let target = match label.target_id {
1054 Ok(node_id) => self.break_ln.get(&node_id),
1055 Err(err) => span_bug!(expr.span, "loop scope error: {}", err),
1058 // Now that we know the label we're going to,
1059 // look it up in the break loop nodes table
1062 Some(b) => self.propagate_through_opt_expr(opt_expr.as_ref().map(|e| &**e), b),
1063 None => span_bug!(expr.span, "break to unknown label")
1067 hir::ExprAgain(label) => {
1068 // Find which label this expr continues to
1069 let sc = match label.target_id {
1070 Ok(node_id) => node_id,
1071 Err(err) => span_bug!(expr.span, "loop scope error: {}", err),
1074 // Now that we know the label we're going to,
1075 // look it up in the continue loop nodes table
1077 match self.cont_ln.get(&sc) {
1079 None => span_bug!(expr.span, "continue to unknown label")
1083 hir::ExprAssign(ref l, ref r) => {
1084 // see comment on places in
1085 // propagate_through_place_components()
1086 let succ = self.write_place(&l, succ, ACC_WRITE);
1087 let succ = self.propagate_through_place_components(&l, succ);
1088 self.propagate_through_expr(&r, succ)
1091 hir::ExprAssignOp(_, ref l, ref r) => {
1092 // an overloaded assign op is like a method call
1093 if self.tables.is_method_call(expr) {
1094 let succ = self.propagate_through_expr(&l, succ);
1095 self.propagate_through_expr(&r, succ)
1097 // see comment on places in
1098 // propagate_through_place_components()
1099 let succ = self.write_place(&l, succ, ACC_WRITE|ACC_READ);
1100 let succ = self.propagate_through_expr(&r, succ);
1101 self.propagate_through_place_components(&l, succ)
1105 // Uninteresting cases: just propagate in rev exec order
1107 hir::ExprArray(ref exprs) => {
1108 self.propagate_through_exprs(exprs, succ)
1111 hir::ExprStruct(_, ref fields, ref with_expr) => {
1112 let succ = self.propagate_through_opt_expr(with_expr.as_ref().map(|e| &**e), succ);
1113 fields.iter().rev().fold(succ, |succ, field| {
1114 self.propagate_through_expr(&field.expr, succ)
1118 hir::ExprCall(ref f, ref args) => {
1119 // FIXME(canndrew): This is_never should really be an is_uninhabited
1120 let succ = if self.tables.expr_ty(expr).is_never() {
1125 let succ = self.propagate_through_exprs(args, succ);
1126 self.propagate_through_expr(&f, succ)
1129 hir::ExprMethodCall(.., ref args) => {
1130 // FIXME(canndrew): This is_never should really be an is_uninhabited
1131 let succ = if self.tables.expr_ty(expr).is_never() {
1136 self.propagate_through_exprs(args, succ)
1139 hir::ExprTup(ref exprs) => {
1140 self.propagate_through_exprs(exprs, succ)
1143 hir::ExprBinary(op, ref l, ref r) if op.node.is_lazy() => {
1144 let r_succ = self.propagate_through_expr(&r, succ);
1146 let ln = self.live_node(expr.id, expr.span);
1147 self.init_from_succ(ln, succ);
1148 self.merge_from_succ(ln, r_succ, false);
1150 self.propagate_through_expr(&l, ln)
1153 hir::ExprIndex(ref l, ref r) |
1154 hir::ExprBinary(_, ref l, ref r) => {
1155 let r_succ = self.propagate_through_expr(&r, succ);
1156 self.propagate_through_expr(&l, r_succ)
1159 hir::ExprBox(ref e) |
1160 hir::ExprAddrOf(_, ref e) |
1161 hir::ExprCast(ref e, _) |
1162 hir::ExprType(ref e, _) |
1163 hir::ExprUnary(_, ref e) |
1164 hir::ExprYield(ref e) |
1165 hir::ExprRepeat(ref e, _) => {
1166 self.propagate_through_expr(&e, succ)
1169 hir::ExprInlineAsm(ref ia, ref outputs, ref inputs) => {
1170 let succ = ia.outputs.iter().zip(outputs).rev().fold(succ, |succ, (o, output)| {
1171 // see comment on places
1172 // in propagate_through_place_components()
1174 self.propagate_through_expr(output, succ)
1176 let acc = if o.is_rw { ACC_WRITE|ACC_READ } else { ACC_WRITE };
1177 let succ = self.write_place(output, succ, acc);
1178 self.propagate_through_place_components(output, succ)
1182 // Inputs are executed first. Propagate last because of rev order
1183 self.propagate_through_exprs(inputs, succ)
1186 hir::ExprLit(..) | hir::ExprPath(hir::QPath::TypeRelative(..)) => {
1190 hir::ExprBlock(ref blk) => {
1191 self.propagate_through_block(&blk, succ)
1196 fn propagate_through_place_components(&mut self,
1202 // In general, the full flow graph structure for an
1203 // assignment/move/etc can be handled in one of two ways,
1204 // depending on whether what is being assigned is a "tracked
1205 // value" or not. A tracked value is basically a local
1206 // variable or argument.
1208 // The two kinds of graphs are:
1210 // Tracked place Untracked place
1211 // ----------------------++-----------------------
1215 // (rvalue) || (rvalue)
1218 // (write of place) || (place components)
1223 // ----------------------++-----------------------
1225 // I will cover the two cases in turn:
1229 // A tracked place is a local variable/argument `x`. In
1230 // these cases, the link_node where the write occurs is linked
1231 // to node id of `x`. The `write_place()` routine generates
1232 // the contents of this node. There are no subcomponents to
1235 // # Non-tracked places
1237 // These are places like `x[5]` or `x.f`. In that case, we
1238 // basically ignore the value which is written to but generate
1239 // reads for the components---`x` in these two examples. The
1240 // components reads are generated by
1241 // `propagate_through_place_components()` (this fn).
1245 // It is still possible to observe assignments to non-places;
1246 // these errors are detected in the later pass borrowck. We
1247 // just ignore such cases and treat them as reads.
1250 hir::ExprPath(_) => succ,
1251 hir::ExprField(ref e, _) => self.propagate_through_expr(&e, succ),
1252 _ => self.propagate_through_expr(expr, succ)
1256 // see comment on propagate_through_place()
1257 fn write_place(&mut self, expr: &Expr, succ: LiveNode, acc: u32)
1260 hir::ExprPath(hir::QPath::Resolved(_, ref path)) => {
1261 self.access_path(expr.id, path, succ, acc)
1264 // We do not track other places, so just propagate through
1265 // to their subcomponents. Also, it may happen that
1266 // non-places occur here, because those are detected in the
1267 // later pass borrowck.
1272 fn access_var(&mut self, id: NodeId, nid: NodeId, succ: LiveNode, acc: u32, span: Span)
1274 let ln = self.live_node(id, span);
1276 self.init_from_succ(ln, succ);
1277 let var = self.variable(nid, span);
1278 self.acc(ln, var, acc);
1283 fn access_path(&mut self, id: NodeId, path: &hir::Path, succ: LiveNode, acc: u32)
1286 Def::Local(nid) => {
1287 self.access_var(id, nid, succ, acc, path.span)
1293 fn propagate_through_loop(&mut self,
1302 We model control flow like this:
1320 let mut first_merge = true;
1321 let ln = self.live_node(expr.id, expr.span);
1322 self.init_empty(ln, succ);
1326 // If this is not a `loop` loop, then it's possible we bypass
1327 // the body altogether. Otherwise, the only way is via a `break`
1328 // in the loop body.
1329 self.merge_from_succ(ln, succ, first_merge);
1330 first_merge = false;
1333 debug!("propagate_through_loop: using id for loop body {} {}",
1334 expr.id, self.ir.tcx.hir.node_to_pretty_string(body.id));
1336 let break_ln = succ;
1338 self.break_ln.insert(expr.id, break_ln);
1339 self.cont_ln.insert(expr.id, cont_ln);
1341 let cond_ln = match kind {
1343 WhileLoop(ref cond) => self.propagate_through_expr(&cond, ln),
1345 let body_ln = self.propagate_through_block(body, cond_ln);
1347 // repeat until fixed point is reached:
1348 while self.merge_from_succ(ln, body_ln, first_merge) {
1349 first_merge = false;
1351 let new_cond_ln = match kind {
1353 WhileLoop(ref cond) => {
1354 self.propagate_through_expr(&cond, ln)
1357 assert!(cond_ln == new_cond_ln);
1358 assert!(body_ln == self.propagate_through_block(body, cond_ln));
1365 // _______________________________________________________________________
1366 // Checking for error conditions
1368 impl<'a, 'tcx> Visitor<'tcx> for Liveness<'a, 'tcx> {
1369 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1370 NestedVisitorMap::None
1373 fn visit_local(&mut self, l: &'tcx hir::Local) {
1374 check_local(self, l);
1376 fn visit_expr(&mut self, ex: &'tcx Expr) {
1377 check_expr(self, ex);
1379 fn visit_arm(&mut self, a: &'tcx hir::Arm) {
1384 fn check_local<'a, 'tcx>(this: &mut Liveness<'a, 'tcx>, local: &'tcx hir::Local) {
1387 this.warn_about_unused_or_dead_vars_in_pat(&local.pat);
1390 this.pat_bindings(&local.pat, |this, ln, var, sp, id| {
1391 let span = local.pat.simple_span().unwrap_or(sp);
1392 this.warn_about_unused(span, id, ln, var);
1397 intravisit::walk_local(this, local);
1400 fn check_arm<'a, 'tcx>(this: &mut Liveness<'a, 'tcx>, arm: &'tcx hir::Arm) {
1401 // only consider the first pattern; any later patterns must have
1402 // the same bindings, and we also consider the first pattern to be
1403 // the "authoritative" set of ids
1404 this.arm_pats_bindings(arm.pats.first().map(|p| &**p), |this, ln, var, sp, id| {
1405 this.warn_about_unused(sp, id, ln, var);
1407 intravisit::walk_arm(this, arm);
1410 fn check_expr<'a, 'tcx>(this: &mut Liveness<'a, 'tcx>, expr: &'tcx Expr) {
1412 hir::ExprAssign(ref l, _) => {
1413 this.check_place(&l);
1415 intravisit::walk_expr(this, expr);
1418 hir::ExprAssignOp(_, ref l, _) => {
1419 if !this.tables.is_method_call(expr) {
1420 this.check_place(&l);
1423 intravisit::walk_expr(this, expr);
1426 hir::ExprInlineAsm(ref ia, ref outputs, ref inputs) => {
1427 for input in inputs {
1428 this.visit_expr(input);
1431 // Output operands must be places
1432 for (o, output) in ia.outputs.iter().zip(outputs) {
1434 this.check_place(output);
1436 this.visit_expr(output);
1439 intravisit::walk_expr(this, expr);
1442 // no correctness conditions related to liveness
1443 hir::ExprCall(..) | hir::ExprMethodCall(..) | hir::ExprIf(..) |
1444 hir::ExprMatch(..) | hir::ExprWhile(..) | hir::ExprLoop(..) |
1445 hir::ExprIndex(..) | hir::ExprField(..) |
1446 hir::ExprArray(..) | hir::ExprTup(..) | hir::ExprBinary(..) |
1447 hir::ExprCast(..) | hir::ExprUnary(..) | hir::ExprRet(..) |
1448 hir::ExprBreak(..) | hir::ExprAgain(..) | hir::ExprLit(_) |
1449 hir::ExprBlock(..) | hir::ExprAddrOf(..) |
1450 hir::ExprStruct(..) | hir::ExprRepeat(..) |
1451 hir::ExprClosure(..) | hir::ExprPath(_) | hir::ExprYield(..) |
1452 hir::ExprBox(..) | hir::ExprType(..) => {
1453 intravisit::walk_expr(this, expr);
1458 impl<'a, 'tcx> Liveness<'a, 'tcx> {
1459 fn check_place(&mut self, expr: &'tcx Expr) {
1461 hir::ExprPath(hir::QPath::Resolved(_, ref path)) => {
1462 if let Def::Local(nid) = path.def {
1463 // Assignment to an immutable variable or argument: only legal
1464 // if there is no later assignment. If this local is actually
1465 // mutable, then check for a reassignment to flag the mutability
1467 let ln = self.live_node(expr.id, expr.span);
1468 let var = self.variable(nid, expr.span);
1469 self.warn_about_dead_assign(expr.span, expr.id, ln, var);
1473 // For other kinds of places, no checks are required,
1474 // and any embedded expressions are actually rvalues
1475 intravisit::walk_expr(self, expr);
1480 fn should_warn(&self, var: Variable) -> Option<String> {
1481 let name = self.ir.variable_name(var);
1482 if name.is_empty() || name.as_bytes()[0] == ('_' as u8) {
1489 fn warn_about_unused_args(&self, body: &hir::Body, entry_ln: LiveNode) {
1490 for arg in &body.arguments {
1491 arg.pat.each_binding(|_bm, p_id, _, path1| {
1492 let sp = path1.span;
1493 let var = self.variable(p_id, sp);
1494 // Ignore unused self.
1495 let name = path1.node;
1496 if name != keywords::SelfValue.name() {
1497 if !self.warn_about_unused(sp, p_id, entry_ln, var) {
1498 if self.live_on_entry(entry_ln, var).is_none() {
1499 self.report_dead_assign(p_id, sp, var, true);
1507 fn warn_about_unused_or_dead_vars_in_pat(&mut self, pat: &hir::Pat) {
1508 self.pat_bindings(pat, |this, ln, var, sp, id| {
1509 if !this.warn_about_unused(sp, id, ln, var) {
1510 this.warn_about_dead_assign(sp, id, ln, var);
1515 fn warn_about_unused(&self,
1521 if !self.used_on_entry(ln, var) {
1522 let r = self.should_warn(var);
1523 if let Some(name) = r {
1525 // annoying: for parameters in funcs like `fn(x: i32)
1526 // {ret}`, there is only one node, so asking about
1527 // assigned_on_exit() is not meaningful.
1528 let is_assigned = if ln == self.s.exit_ln {
1531 self.assigned_on_exit(ln, var).is_some()
1534 let suggest_underscore_msg = format!("consider using `_{}` instead",
1539 .lint_node_note(lint::builtin::UNUSED_VARIABLES, id, sp,
1540 &format!("variable `{}` is assigned to, but never used",
1542 &suggest_underscore_msg);
1543 } else if name != "self" {
1544 let msg = format!("unused variable: `{}`", name);
1545 let mut err = self.ir.tcx
1546 .struct_span_lint_node(lint::builtin::UNUSED_VARIABLES, id, sp, &msg);
1547 if self.ir.variable_is_shorthand(var) {
1548 err.span_suggestion(sp, "try ignoring the field",
1549 format!("{}: _", name));
1551 err.span_suggestion_short(sp, &suggest_underscore_msg,
1552 format!("_{}", name));
1563 fn warn_about_dead_assign(&self,
1568 if self.live_on_exit(ln, var).is_none() {
1569 self.report_dead_assign(id, sp, var, false);
1573 fn report_dead_assign(&self, id: NodeId, sp: Span, var: Variable, is_argument: bool) {
1574 if let Some(name) = self.should_warn(var) {
1576 self.ir.tcx.lint_node(lint::builtin::UNUSED_ASSIGNMENTS, id, sp,
1577 &format!("value passed to `{}` is never read", name));
1579 self.ir.tcx.lint_node(lint::builtin::UNUSED_ASSIGNMENTS, id, sp,
1580 &format!("value assigned to `{}` is never read", name));