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.
12 * A classic liveness analysis based on dataflow over the AST. Computes,
13 * for each local variable in a function, whether that variable is live
14 * at a given point. Program execution points are identified by their
19 * The basic model is that each local variable is assigned an index. We
20 * represent sets of local variables using a vector indexed by this
21 * index. The value in the vector is either 0, indicating the variable
22 * is dead, or the id of an expression that uses the variable.
24 * We conceptually walk over the AST in reverse execution order. If we
25 * find a use of a variable, we add it to the set of live variables. If
26 * we find an assignment to a variable, we remove it from the set of live
27 * variables. When we have to merge two flows, we take the union of
28 * those two flows---if the variable is live on both paths, we simply
29 * pick one id. In the event of loops, we continue doing this until a
30 * fixed point is reached.
32 * ## Checking initialization
34 * At the function entry point, all variables must be dead. If this is
35 * not the case, we can report an error using the id found in the set of
36 * live variables, which identifies a use of the variable which is not
37 * dominated by an assignment.
41 * After each explicit move, the variable must be dead.
43 * ## Computing last uses
45 * Any use of the variable where the variable is dead afterwards is a
48 * # Implementation details
50 * The actual implementation contains two (nested) walks over the AST.
51 * The outer walk has the job of building up the ir_maps instance for the
52 * enclosing function. On the way down the tree, it identifies those AST
53 * nodes and variable IDs that will be needed for the liveness analysis
54 * and assigns them contiguous IDs. The liveness id for an AST node is
55 * called a `live_node` (it's a newtype'd uint) and the id for a variable
56 * is called a `variable` (another newtype'd uint).
58 * On the way back up the tree, as we are about to exit from a function
59 * declaration we allocate a `liveness` instance. Now that we know
60 * precisely how many nodes and variables we need, we can allocate all
61 * the various arrays that we will need to precisely the right size. We then
62 * perform the actual propagation on the `liveness` instance.
64 * This propagation is encoded in the various `propagate_through_*()`
65 * methods. It effectively does a reverse walk of the AST; whenever we
66 * reach a loop node, we iterate until a fixed point is reached.
68 * ## The `Users` struct
70 * At each live node `N`, we track three pieces of information for each
71 * variable `V` (these are encapsulated in the `Users` struct):
73 * - `reader`: the `LiveNode` ID of some node which will read the value
74 * that `V` holds on entry to `N`. Formally: a node `M` such
75 * that there exists a path `P` from `N` to `M` where `P` does not
76 * write `V`. If the `reader` is `invalid_node()`, then the current
77 * value will never be read (the variable is dead, essentially).
79 * - `writer`: the `LiveNode` ID of some node which will write the
80 * variable `V` and which is reachable from `N`. Formally: a node `M`
81 * such that there exists a path `P` from `N` to `M` and `M` writes
82 * `V`. If the `writer` is `invalid_node()`, then there is no writer
83 * of `V` that follows `N`.
85 * - `used`: a boolean value indicating whether `V` is *used*. We
86 * distinguish a *read* from a *use* in that a *use* is some read that
87 * is not just used to generate a new value. For example, `x += 1` is
88 * a read but not a use. This is used to generate better warnings.
90 * ## Special Variables
92 * We generate various special variables for various, well, special purposes.
93 * These are described in the `specials` struct:
95 * - `exit_ln`: a live node that is generated to represent every 'exit' from
96 * the function, whether it be by explicit return, fail, or other means.
98 * - `fallthrough_ln`: a live node that represents a fallthrough
100 * - `no_ret_var`: a synthetic variable that is only 'read' from, the
101 * fallthrough node. This allows us to detect functions where we fail
102 * to return explicitly.
106 use middle::freevars;
107 use middle::mem_categorization::Typer;
108 use middle::pat_util;
111 use util::nodemap::NodeMap;
116 use std::mem::transmute;
121 use syntax::codemap::{BytePos, original_sp, Span};
122 use syntax::parse::token::special_idents;
123 use syntax::parse::token;
124 use syntax::print::pprust::{expr_to_string, block_to_string};
125 use syntax::{visit, ast_util};
126 use syntax::visit::{Visitor, FnKind};
128 /// For use with `propagate_through_loop`.
129 #[deriving(PartialEq, Eq)]
131 /// An endless `loop` loop.
133 /// A `while` loop, with the given expression as condition.
139 #[deriving(PartialEq)]
140 struct Variable(uint);
141 #[deriving(PartialEq)]
142 struct LiveNode(uint);
145 fn get(&self) -> uint { let Variable(v) = *self; v }
149 fn get(&self) -> uint { let LiveNode(v) = *self; v }
152 impl Clone for LiveNode {
153 fn clone(&self) -> LiveNode {
158 #[deriving(PartialEq)]
166 fn live_node_kind_to_string(lnk: LiveNodeKind, cx: &ty::ctxt) -> String {
167 let cm = cx.sess.codemap();
170 format!("Free var node [{}]", cm.span_to_string(s))
173 format!("Expr node [{}]", cm.span_to_string(s))
176 format!("Var def node [{}]", cm.span_to_string(s))
178 ExitNode => "Exit node".to_string(),
182 impl<'a, 'tcx> Visitor<()> for IrMaps<'a, 'tcx> {
183 fn visit_fn(&mut self, fk: &FnKind, fd: &FnDecl, b: &Block, s: Span, n: NodeId, _: ()) {
184 visit_fn(self, fk, fd, b, s, n);
186 fn visit_local(&mut self, l: &Local, _: ()) { visit_local(self, l); }
187 fn visit_expr(&mut self, ex: &Expr, _: ()) { visit_expr(self, ex); }
188 fn visit_arm(&mut self, a: &Arm, _: ()) { visit_arm(self, a); }
191 pub fn check_crate(tcx: &ty::ctxt,
193 visit::walk_crate(&mut IrMaps::new(tcx), krate, ());
194 tcx.sess.abort_if_errors();
197 impl fmt::Show for LiveNode {
198 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
199 write!(f, "ln({})", self.get())
203 impl fmt::Show for Variable {
204 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
205 write!(f, "v({})", self.get())
209 // ______________________________________________________________________
212 // This is the first pass and the one that drives the main
213 // computation. It walks up and down the IR once. On the way down,
214 // we count for each function the number of variables as well as
215 // liveness nodes. A liveness node is basically an expression or
216 // capture clause that does something of interest: either it has
217 // interesting control flow or it uses/defines a local variable.
219 // On the way back up, at each function node we create liveness sets
220 // (we now know precisely how big to make our various vectors and so
221 // forth) and then do the data-flow propagation to compute the set
222 // of live variables at each program point.
224 // Finally, we run back over the IR one last time and, using the
225 // computed liveness, check various safety conditions. For example,
226 // there must be no live nodes at the definition site for a variable
227 // unless it has an initializer. Similarly, each non-mutable local
228 // variable must not be assigned if there is some successor
229 // assignment. And so forth.
232 fn is_valid(&self) -> bool {
233 self.get() != uint::MAX
237 fn invalid_node() -> LiveNode { LiveNode(uint::MAX) }
255 struct IrMaps<'a, 'tcx: 'a> {
256 tcx: &'a ty::ctxt<'tcx>,
258 num_live_nodes: uint,
260 live_node_map: NodeMap<LiveNode>,
261 variable_map: NodeMap<Variable>,
262 capture_info_map: NodeMap<Rc<Vec<CaptureInfo>>>,
263 var_kinds: Vec<VarKind>,
264 lnks: Vec<LiveNodeKind>,
267 impl<'a, 'tcx> IrMaps<'a, 'tcx> {
268 fn new(tcx: &'a ty::ctxt<'tcx>) -> IrMaps<'a, 'tcx> {
273 live_node_map: NodeMap::new(),
274 variable_map: NodeMap::new(),
275 capture_info_map: NodeMap::new(),
276 var_kinds: Vec::new(),
281 fn add_live_node(&mut self, lnk: LiveNodeKind) -> LiveNode {
282 let ln = LiveNode(self.num_live_nodes);
284 self.num_live_nodes += 1;
286 debug!("{} is of kind {}", ln.to_string(),
287 live_node_kind_to_string(lnk, self.tcx));
292 fn add_live_node_for_node(&mut self, node_id: NodeId, lnk: LiveNodeKind) {
293 let ln = self.add_live_node(lnk);
294 self.live_node_map.insert(node_id, ln);
296 debug!("{} is node {}", ln.to_string(), node_id);
299 fn add_variable(&mut self, vk: VarKind) -> Variable {
300 let v = Variable(self.num_vars);
301 self.var_kinds.push(vk);
305 Local(LocalInfo { id: node_id, .. }) | Arg(node_id, _) => {
306 self.variable_map.insert(node_id, v);
311 debug!("{} is {:?}", v.to_string(), vk);
316 fn variable(&self, node_id: NodeId, span: Span) -> Variable {
317 match self.variable_map.find(&node_id) {
322 .span_bug(span, format!("no variable registered for id {}",
323 node_id).as_slice());
328 fn variable_name(&self, var: Variable) -> String {
329 match self.var_kinds.get(var.get()) {
330 &Local(LocalInfo { ident: nm, .. }) | &Arg(_, nm) => {
331 token::get_ident(nm).get().to_string()
333 &ImplicitRet => "<implicit-ret>".to_string()
337 fn set_captures(&mut self, node_id: NodeId, cs: Vec<CaptureInfo>) {
338 self.capture_info_map.insert(node_id, Rc::new(cs));
341 fn lnk(&self, ln: LiveNode) -> LiveNodeKind {
342 *self.lnks.get(ln.get())
346 impl<'a, 'tcx> Visitor<()> for Liveness<'a, 'tcx> {
347 fn visit_fn(&mut self, fk: &FnKind, fd: &FnDecl, b: &Block, s: Span, n: NodeId, _: ()) {
348 check_fn(self, fk, fd, b, s, n);
350 fn visit_local(&mut self, l: &Local, _: ()) {
351 check_local(self, l);
353 fn visit_expr(&mut self, ex: &Expr, _: ()) {
354 check_expr(self, ex);
356 fn visit_arm(&mut self, a: &Arm, _: ()) {
361 fn visit_fn(ir: &mut IrMaps,
367 debug!("visit_fn: id={}", id);
368 let _i = ::util::common::indenter();
370 // swap in a new set of IR maps for this function body:
371 let mut fn_maps = IrMaps::new(ir.tcx);
374 debug!("creating fn_maps: {}",
375 transmute::<&IrMaps, *const IrMaps>(&fn_maps));
378 for arg in decl.inputs.iter() {
379 pat_util::pat_bindings(&ir.tcx.def_map,
381 |_bm, arg_id, _x, path1| {
382 debug!("adding argument {}", arg_id);
383 let ident = path1.node;
384 fn_maps.add_variable(Arg(arg_id, ident));
388 // gather up the various local variables, significant expressions,
390 visit::walk_fn(&mut fn_maps, fk, decl, body, sp, ());
392 // Special nodes and variables:
393 // - exit_ln represents the end of the fn, either by return or fail
394 // - implicit_ret_var is a pseudo-variable that represents
395 // an implicit return
396 let specials = Specials {
397 exit_ln: fn_maps.add_live_node(ExitNode),
398 fallthrough_ln: fn_maps.add_live_node(ExitNode),
399 no_ret_var: fn_maps.add_variable(ImplicitRet)
403 let mut lsets = Liveness::new(&mut fn_maps, specials);
404 let entry_ln = lsets.compute(decl, body);
406 // check for various error conditions
407 lsets.visit_block(body, ());
408 lsets.check_ret(id, sp, fk, entry_ln, body);
409 lsets.warn_about_unused_args(decl, entry_ln);
412 fn visit_local(ir: &mut IrMaps, local: &Local) {
413 pat_util::pat_bindings(&ir.tcx.def_map, &*local.pat, |_, p_id, sp, path1| {
414 debug!("adding local variable {}", p_id);
415 let name = path1.node;
416 ir.add_live_node_for_node(p_id, VarDefNode(sp));
417 ir.add_variable(Local(LocalInfo {
422 visit::walk_local(ir, local, ());
425 fn visit_arm(ir: &mut IrMaps, arm: &Arm) {
426 for pat in arm.pats.iter() {
427 pat_util::pat_bindings(&ir.tcx.def_map, &**pat, |bm, p_id, sp, path1| {
428 debug!("adding local variable {} from match with bm {:?}",
430 let name = path1.node;
431 ir.add_live_node_for_node(p_id, VarDefNode(sp));
432 ir.add_variable(Local(LocalInfo {
438 visit::walk_arm(ir, arm, ());
441 fn moved_variable_node_id_from_def(def: Def) -> Option<NodeId> {
445 DefLocal(nid, _) => Some(nid),
451 fn visit_expr(ir: &mut IrMaps, expr: &Expr) {
453 // live nodes required for uses or definitions of variables:
455 let def = ir.tcx.def_map.borrow().get_copy(&expr.id);
456 debug!("expr {}: path that leads to {:?}", expr.id, def);
457 if moved_variable_node_id_from_def(def).is_some() {
458 ir.add_live_node_for_node(expr.id, ExprNode(expr.span));
460 visit::walk_expr(ir, expr, ());
462 ExprFnBlock(..) | ExprProc(..) | ExprUnboxedFn(..) => {
463 // Interesting control flow (for loops can contain labeled
464 // breaks or continues)
465 ir.add_live_node_for_node(expr.id, ExprNode(expr.span));
467 // Make a live_node for each captured variable, with the span
468 // being the location that the variable is used. This results
469 // in better error messages than just pointing at the closure
470 // construction site.
471 let mut call_caps = Vec::new();
472 freevars::with_freevars(ir.tcx, expr.id, |freevars| {
473 for fv in freevars.iter() {
474 match moved_variable_node_id_from_def(fv.def) {
476 let fv_ln = ir.add_live_node(FreeVarNode(fv.span));
477 call_caps.push(CaptureInfo {ln: fv_ln,
484 ir.set_captures(expr.id, call_caps);
486 visit::walk_expr(ir, expr, ());
489 // live nodes required for interesting control flow:
490 ExprIf(..) | ExprMatch(..) | ExprWhile(..) | ExprLoop(..) => {
491 ir.add_live_node_for_node(expr.id, ExprNode(expr.span));
492 visit::walk_expr(ir, expr, ());
494 ExprForLoop(ref pat, _, _, _) => {
495 pat_util::pat_bindings(&ir.tcx.def_map, &**pat, |bm, p_id, sp, path1| {
496 debug!("adding local variable {} from for loop with bm {:?}",
498 let name = path1.node;
499 ir.add_live_node_for_node(p_id, VarDefNode(sp));
500 ir.add_variable(Local(LocalInfo {
505 ir.add_live_node_for_node(expr.id, ExprNode(expr.span));
506 visit::walk_expr(ir, expr, ());
508 ExprBinary(op, _, _) if ast_util::lazy_binop(op) => {
509 ir.add_live_node_for_node(expr.id, ExprNode(expr.span));
510 visit::walk_expr(ir, expr, ());
513 // otherwise, live nodes are not required:
514 ExprIndex(..) | ExprField(..) | ExprVec(..) |
515 ExprCall(..) | ExprMethodCall(..) | ExprTup(..) |
516 ExprBinary(..) | ExprAddrOf(..) |
517 ExprCast(..) | ExprUnary(..) | ExprBreak(_) |
518 ExprAgain(_) | ExprLit(_) | ExprRet(..) | ExprBlock(..) |
519 ExprAssign(..) | ExprAssignOp(..) | ExprMac(..) |
520 ExprStruct(..) | ExprRepeat(..) | ExprParen(..) |
521 ExprInlineAsm(..) | ExprBox(..) => {
522 visit::walk_expr(ir, expr, ());
527 // ______________________________________________________________________
528 // Computing liveness sets
530 // Actually we compute just a bit more than just liveness, but we use
531 // the same basic propagation framework in all cases.
540 fn invalid_users() -> Users {
542 reader: invalid_node(),
543 writer: invalid_node(),
550 fallthrough_ln: LiveNode,
554 static ACC_READ: uint = 1u;
555 static ACC_WRITE: uint = 2u;
556 static ACC_USE: uint = 4u;
558 struct Liveness<'a, 'tcx: 'a> {
559 ir: &'a mut IrMaps<'a, 'tcx>,
561 successors: Vec<LiveNode>,
563 // The list of node IDs for the nested loop scopes
565 loop_scope: Vec<NodeId>,
566 // mappings from loop node ID to LiveNode
567 // ("break" label should map to loop node ID,
568 // it probably doesn't now)
569 break_ln: NodeMap<LiveNode>,
570 cont_ln: NodeMap<LiveNode>
573 impl<'a, 'tcx> Liveness<'a, 'tcx> {
574 fn new(ir: &'a mut IrMaps<'a, 'tcx>, specials: Specials) -> Liveness<'a, 'tcx> {
575 let num_live_nodes = ir.num_live_nodes;
576 let num_vars = ir.num_vars;
580 successors: Vec::from_elem(num_live_nodes, invalid_node()),
581 users: Vec::from_elem(num_live_nodes * num_vars, invalid_users()),
582 loop_scope: Vec::new(),
583 break_ln: NodeMap::new(),
584 cont_ln: NodeMap::new(),
588 fn live_node(&self, node_id: NodeId, span: Span) -> LiveNode {
589 match self.ir.live_node_map.find(&node_id) {
592 // This must be a mismatch between the ir_map construction
593 // above and the propagation code below; the two sets of
594 // code have to agree about which AST nodes are worth
595 // creating liveness nodes for.
596 self.ir.tcx.sess.span_bug(
598 format!("no live node registered for node {}",
599 node_id).as_slice());
604 fn variable(&self, node_id: NodeId, span: Span) -> Variable {
605 self.ir.variable(node_id, span)
608 fn pat_bindings(&mut self,
610 f: |&mut Liveness<'a, 'tcx>, LiveNode, Variable, Span, NodeId|) {
611 pat_util::pat_bindings(&self.ir.tcx.def_map, pat, |_bm, p_id, sp, _n| {
612 let ln = self.live_node(p_id, sp);
613 let var = self.variable(p_id, sp);
614 f(self, ln, var, sp, p_id);
618 fn arm_pats_bindings(&mut self,
620 f: |&mut Liveness<'a, 'tcx>, LiveNode, Variable, Span, NodeId|) {
621 // only consider the first pattern; any later patterns must have
622 // the same bindings, and we also consider the first pattern to be
623 // the "authoritative" set of ids
624 if !pats.is_empty() {
625 self.pat_bindings(&*pats[0], f)
629 fn define_bindings_in_pat(&mut self, pat: Gc<Pat>, succ: LiveNode)
631 self.define_bindings_in_arm_pats([pat], succ)
634 fn define_bindings_in_arm_pats(&mut self, pats: &[Gc<Pat>], succ: LiveNode)
637 self.arm_pats_bindings(pats, |this, ln, var, _sp, _id| {
638 this.init_from_succ(ln, succ);
639 this.define(ln, var);
645 fn idx(&self, ln: LiveNode, var: Variable) -> uint {
646 ln.get() * self.ir.num_vars + var.get()
649 fn live_on_entry(&self, ln: LiveNode, var: Variable)
650 -> Option<LiveNodeKind> {
651 assert!(ln.is_valid());
652 let reader = self.users.get(self.idx(ln, var)).reader;
653 if reader.is_valid() {Some(self.ir.lnk(reader))} else {None}
657 Is this variable live on entry to any of its successor nodes?
659 fn live_on_exit(&self, ln: LiveNode, var: Variable)
660 -> Option<LiveNodeKind> {
661 let successor = *self.successors.get(ln.get());
662 self.live_on_entry(successor, var)
665 fn used_on_entry(&self, ln: LiveNode, var: Variable) -> bool {
666 assert!(ln.is_valid());
667 self.users.get(self.idx(ln, var)).used
670 fn assigned_on_entry(&self, ln: LiveNode, var: Variable)
671 -> Option<LiveNodeKind> {
672 assert!(ln.is_valid());
673 let writer = self.users.get(self.idx(ln, var)).writer;
674 if writer.is_valid() {Some(self.ir.lnk(writer))} else {None}
677 fn assigned_on_exit(&self, ln: LiveNode, var: Variable)
678 -> Option<LiveNodeKind> {
679 let successor = *self.successors.get(ln.get());
680 self.assigned_on_entry(successor, var)
683 fn indices2(&mut self,
686 op: |&mut Liveness<'a, 'tcx>, uint, uint|) {
687 let node_base_idx = self.idx(ln, Variable(0u));
688 let succ_base_idx = self.idx(succ_ln, Variable(0u));
689 for var_idx in range(0u, self.ir.num_vars) {
690 op(self, node_base_idx + var_idx, succ_base_idx + var_idx);
697 test: |uint| -> LiveNode) -> io::IoResult<()> {
698 let node_base_idx = self.idx(ln, Variable(0));
699 for var_idx in range(0u, self.ir.num_vars) {
700 let idx = node_base_idx + var_idx;
701 if test(idx).is_valid() {
702 try!(write!(wr, " {}", Variable(var_idx).to_string()));
708 fn find_loop_scope(&self,
709 opt_label: Option<Ident>,
715 // Refers to a labeled loop. Use the results of resolve
717 match self.ir.tcx.def_map.borrow().find(&id) {
718 Some(&DefLabel(loop_id)) => loop_id,
719 _ => self.ir.tcx.sess.span_bug(sp, "label on break/loop \
720 doesn't refer to a loop")
724 // Vanilla 'break' or 'loop', so use the enclosing
726 if self.loop_scope.len() == 0 {
727 self.ir.tcx.sess.span_bug(sp, "break outside loop");
729 *self.loop_scope.last().unwrap()
735 #[allow(unused_must_use)]
736 fn ln_str(&self, ln: LiveNode) -> String {
737 let mut wr = io::MemWriter::new();
739 let wr = &mut wr as &mut io::Writer;
740 write!(wr, "[ln({}) of kind {:?} reads", ln.get(), self.ir.lnk(ln));
741 self.write_vars(wr, ln, |idx| self.users.get(idx).reader);
742 write!(wr, " writes");
743 self.write_vars(wr, ln, |idx| self.users.get(idx).writer);
744 write!(wr, " precedes {}]", self.successors.get(ln.get()).to_string());
746 str::from_utf8(wr.unwrap().as_slice()).unwrap().to_string()
749 fn init_empty(&mut self, ln: LiveNode, succ_ln: LiveNode) {
750 *self.successors.get_mut(ln.get()) = succ_ln;
752 // It is not necessary to initialize the
753 // values to empty because this is the value
754 // they have when they are created, and the sets
755 // only grow during iterations.
757 // self.indices(ln) { |idx|
758 // self.users[idx] = invalid_users();
762 fn init_from_succ(&mut self, ln: LiveNode, succ_ln: LiveNode) {
763 // more efficient version of init_empty() / merge_from_succ()
764 *self.successors.get_mut(ln.get()) = succ_ln;
766 self.indices2(ln, succ_ln, |this, idx, succ_idx| {
767 *this.users.get_mut(idx) = *this.users.get(succ_idx)
769 debug!("init_from_succ(ln={}, succ={})",
770 self.ln_str(ln), self.ln_str(succ_ln));
773 fn merge_from_succ(&mut self,
778 if ln == succ_ln { return false; }
780 let mut changed = false;
781 self.indices2(ln, succ_ln, |this, idx, succ_idx| {
782 changed |= copy_if_invalid(this.users.get(succ_idx).reader,
783 &mut this.users.get_mut(idx).reader);
784 changed |= copy_if_invalid(this.users.get(succ_idx).writer,
785 &mut this.users.get_mut(idx).writer);
786 if this.users.get(succ_idx).used && !this.users.get(idx).used {
787 this.users.get_mut(idx).used = true;
792 debug!("merge_from_succ(ln={}, succ={}, first_merge={}, changed={})",
793 ln.to_string(), self.ln_str(succ_ln), first_merge, changed);
796 fn copy_if_invalid(src: LiveNode, dst: &mut LiveNode) -> bool {
797 if src.is_valid() && !dst.is_valid() {
806 // Indicates that a local variable was *defined*; we know that no
807 // uses of the variable can precede the definition (resolve checks
808 // this) so we just clear out all the data.
809 fn define(&mut self, writer: LiveNode, var: Variable) {
810 let idx = self.idx(writer, var);
811 self.users.get_mut(idx).reader = invalid_node();
812 self.users.get_mut(idx).writer = invalid_node();
814 debug!("{} defines {} (idx={}): {}", writer.to_string(), var.to_string(),
815 idx, self.ln_str(writer));
818 // Either read, write, or both depending on the acc bitset
819 fn acc(&mut self, ln: LiveNode, var: Variable, acc: uint) {
820 debug!("{} accesses[{:x}] {}: {}",
821 ln.to_string(), acc, var.to_string(), self.ln_str(ln));
823 let idx = self.idx(ln, var);
824 let user = self.users.get_mut(idx);
826 if (acc & ACC_WRITE) != 0 {
827 user.reader = invalid_node();
831 // Important: if we both read/write, must do read second
832 // or else the write will override.
833 if (acc & ACC_READ) != 0 {
837 if (acc & ACC_USE) != 0 {
842 // _______________________________________________________________________
844 fn compute(&mut self, decl: &FnDecl, body: &Block) -> LiveNode {
845 // if there is a `break` or `again` at the top level, then it's
846 // effectively a return---this only occurs in `for` loops,
847 // where the body is really a closure.
849 debug!("compute: using id for block, {}", block_to_string(body));
851 let exit_ln = self.s.exit_ln;
852 let entry_ln: LiveNode =
853 self.with_loop_nodes(body.id, exit_ln, exit_ln,
854 |this| this.propagate_through_fn_block(decl, body));
856 // hack to skip the loop unless debug! is enabled:
857 debug!("^^ liveness computation results for body {} (entry={})",
859 for ln_idx in range(0u, self.ir.num_live_nodes) {
860 debug!("{}", self.ln_str(LiveNode(ln_idx)));
864 entry_ln.to_string());
869 fn propagate_through_fn_block(&mut self, _: &FnDecl, blk: &Block)
871 // the fallthrough exit is only for those cases where we do not
872 // explicitly return:
874 self.init_from_succ(s.fallthrough_ln, s.exit_ln);
875 if blk.expr.is_none() {
876 self.acc(s.fallthrough_ln, s.no_ret_var, ACC_READ)
879 self.propagate_through_block(blk, s.fallthrough_ln)
882 fn propagate_through_block(&mut self, blk: &Block, succ: LiveNode)
884 let succ = self.propagate_through_opt_expr(blk.expr, succ);
885 blk.stmts.iter().rev().fold(succ, |succ, stmt| {
886 self.propagate_through_stmt(&**stmt, succ)
890 fn propagate_through_stmt(&mut self, stmt: &Stmt, succ: LiveNode)
893 StmtDecl(ref decl, _) => {
894 self.propagate_through_decl(&**decl, succ)
897 StmtExpr(ref expr, _) | StmtSemi(ref expr, _) => {
898 self.propagate_through_expr(&**expr, succ)
902 self.ir.tcx.sess.span_bug(stmt.span, "unexpanded macro");
907 fn propagate_through_decl(&mut self, decl: &Decl, succ: LiveNode)
910 DeclLocal(ref local) => {
911 self.propagate_through_local(&**local, succ)
917 fn propagate_through_local(&mut self, local: &Local, succ: LiveNode)
919 // Note: we mark the variable as defined regardless of whether
920 // there is an initializer. Initially I had thought to only mark
921 // the live variable as defined if it was initialized, and then we
922 // could check for uninit variables just by scanning what is live
923 // at the start of the function. But that doesn't work so well for
924 // immutable variables defined in a loop:
925 // loop { let x; x = 5; }
926 // because the "assignment" loops back around and generates an error.
928 // So now we just check that variables defined w/o an
929 // initializer are not live at the point of their
930 // initialization, which is mildly more complex than checking
931 // once at the func header but otherwise equivalent.
933 let succ = self.propagate_through_opt_expr(local.init, succ);
934 self.define_bindings_in_pat(local.pat, succ)
937 fn propagate_through_exprs(&mut self, exprs: &[Gc<Expr>], succ: LiveNode)
939 exprs.iter().rev().fold(succ, |succ, expr| {
940 self.propagate_through_expr(&**expr, succ)
944 fn propagate_through_opt_expr(&mut self,
945 opt_expr: Option<Gc<Expr>>,
948 opt_expr.iter().fold(succ, |succ, expr| {
949 self.propagate_through_expr(&**expr, succ)
953 fn propagate_through_expr(&mut self, expr: &Expr, succ: LiveNode)
955 debug!("propagate_through_expr: {}", expr_to_string(expr));
958 // Interesting cases with control flow or which gen/kill
961 self.access_path(expr, succ, ACC_READ | ACC_USE)
964 ExprField(ref e, _, _) => {
965 self.propagate_through_expr(&**e, succ)
968 ExprFnBlock(_, _, ref blk) |
969 ExprProc(_, ref blk) |
970 ExprUnboxedFn(_, _, _, ref blk) => {
971 debug!("{} is an ExprFnBlock, ExprProc, or ExprUnboxedFn",
972 expr_to_string(expr));
975 The next-node for a break is the successor of the entire
976 loop. The next-node for a continue is the top of this loop.
978 let node = self.live_node(expr.id, expr.span);
979 self.with_loop_nodes(blk.id, succ, node, |this| {
981 // the construction of a closure itself is not important,
982 // but we have to consider the closed over variables.
983 let caps = match this.ir.capture_info_map.find(&expr.id) {
984 Some(caps) => caps.clone(),
986 this.ir.tcx.sess.span_bug(expr.span, "no registered caps");
989 caps.iter().rev().fold(succ, |succ, cap| {
990 this.init_from_succ(cap.ln, succ);
991 let var = this.variable(cap.var_nid, expr.span);
992 this.acc(cap.ln, var, ACC_READ | ACC_USE);
998 ExprIf(ref cond, ref then, ref els) => {
1012 let else_ln = self.propagate_through_opt_expr(els.clone(), succ);
1013 let then_ln = self.propagate_through_block(&**then, succ);
1014 let ln = self.live_node(expr.id, expr.span);
1015 self.init_from_succ(ln, else_ln);
1016 self.merge_from_succ(ln, then_ln, false);
1017 self.propagate_through_expr(&**cond, ln)
1020 ExprWhile(ref cond, ref blk, _) => {
1021 self.propagate_through_loop(expr,
1022 WhileLoop(cond.clone()),
1027 ExprForLoop(_, ref head, ref blk, _) => {
1028 let ln = self.propagate_through_loop(expr, ForLoop, &**blk, succ);
1029 self.propagate_through_expr(&**head, ln)
1032 // Note that labels have been resolved, so we don't need to look
1033 // at the label ident
1034 ExprLoop(ref blk, _) => {
1035 self.propagate_through_loop(expr, LoopLoop, &**blk, succ)
1038 ExprMatch(ref e, ref arms) => {
1053 let ln = self.live_node(expr.id, expr.span);
1054 self.init_empty(ln, succ);
1055 let mut first_merge = true;
1056 for arm in arms.iter() {
1058 self.propagate_through_expr(&*arm.body, succ);
1060 self.propagate_through_opt_expr(arm.guard, body_succ);
1062 self.define_bindings_in_arm_pats(arm.pats.as_slice(),
1064 self.merge_from_succ(ln, arm_succ, first_merge);
1065 first_merge = false;
1067 self.propagate_through_expr(&**e, ln)
1071 // ignore succ and subst exit_ln:
1072 let exit_ln = self.s.exit_ln;
1073 self.propagate_through_opt_expr(o_e, exit_ln)
1076 ExprBreak(opt_label) => {
1077 // Find which label this break jumps to
1078 let sc = self.find_loop_scope(opt_label, expr.id, expr.span);
1080 // Now that we know the label we're going to,
1081 // look it up in the break loop nodes table
1083 match self.break_ln.find(&sc) {
1085 None => self.ir.tcx.sess.span_bug(expr.span,
1086 "break to unknown label")
1090 ExprAgain(opt_label) => {
1091 // Find which label this expr continues to
1092 let sc = self.find_loop_scope(opt_label, expr.id, expr.span);
1094 // Now that we know the label we're going to,
1095 // look it up in the continue loop nodes table
1097 match self.cont_ln.find(&sc) {
1099 None => self.ir.tcx.sess.span_bug(expr.span,
1100 "loop to unknown label")
1104 ExprAssign(ref l, ref r) => {
1105 // see comment on lvalues in
1106 // propagate_through_lvalue_components()
1107 let succ = self.write_lvalue(&**l, succ, ACC_WRITE);
1108 let succ = self.propagate_through_lvalue_components(&**l, succ);
1109 self.propagate_through_expr(&**r, succ)
1112 ExprAssignOp(_, ref l, ref r) => {
1113 // see comment on lvalues in
1114 // propagate_through_lvalue_components()
1115 let succ = self.write_lvalue(&**l, succ, ACC_WRITE|ACC_READ);
1116 let succ = self.propagate_through_expr(&**r, succ);
1117 self.propagate_through_lvalue_components(&**l, succ)
1120 // Uninteresting cases: just propagate in rev exec order
1122 ExprVec(ref exprs) => {
1123 self.propagate_through_exprs(exprs.as_slice(), succ)
1126 ExprRepeat(ref element, ref count) => {
1127 let succ = self.propagate_through_expr(&**count, succ);
1128 self.propagate_through_expr(&**element, succ)
1131 ExprStruct(_, ref fields, ref with_expr) => {
1132 let succ = self.propagate_through_opt_expr(with_expr.clone(), succ);
1133 fields.iter().rev().fold(succ, |succ, field| {
1134 self.propagate_through_expr(&*field.expr, succ)
1138 ExprCall(ref f, ref args) => {
1139 // calling a fn with bot return type means that the fn
1140 // will fail, and hence the successors can be ignored
1141 let is_bot = !self.ir.tcx.is_method_call(expr.id) && {
1142 let t_ret = ty::ty_fn_ret(ty::expr_ty(self.ir.tcx, &**f));
1143 ty::type_is_bot(t_ret)
1145 let succ = if is_bot {
1150 let succ = self.propagate_through_exprs(args.as_slice(), succ);
1151 self.propagate_through_expr(&**f, succ)
1154 ExprMethodCall(_, _, ref args) => {
1155 // calling a method with bot return type means that the method
1156 // will fail, and hence the successors can be ignored
1157 let t_ret = ty::node_id_to_type(self.ir.tcx, expr.id);
1158 let succ = if ty::type_is_bot(t_ret) {self.s.exit_ln}
1160 self.propagate_through_exprs(args.as_slice(), succ)
1163 ExprTup(ref exprs) => {
1164 self.propagate_through_exprs(exprs.as_slice(), succ)
1167 ExprBinary(op, ref l, ref r) if ast_util::lazy_binop(op) => {
1168 let r_succ = self.propagate_through_expr(&**r, succ);
1170 let ln = self.live_node(expr.id, expr.span);
1171 self.init_from_succ(ln, succ);
1172 self.merge_from_succ(ln, r_succ, false);
1174 self.propagate_through_expr(&**l, ln)
1177 ExprIndex(ref l, ref r) |
1178 ExprBinary(_, ref l, ref r) |
1179 ExprBox(ref l, ref r) => {
1180 self.propagate_through_exprs([l.clone(), r.clone()], succ)
1183 ExprAddrOf(_, ref e) |
1184 ExprCast(ref e, _) |
1185 ExprUnary(_, ref e) |
1186 ExprParen(ref e) => {
1187 self.propagate_through_expr(&**e, succ)
1190 ExprInlineAsm(ref ia) => {
1192 let succ = ia.outputs.iter().rev().fold(succ, |succ, &(_, ref expr, _)| {
1193 // see comment on lvalues
1194 // in propagate_through_lvalue_components()
1195 let succ = self.write_lvalue(&**expr, succ, ACC_WRITE);
1196 self.propagate_through_lvalue_components(&**expr, succ)
1198 // Inputs are executed first. Propagate last because of rev order
1199 ia.inputs.iter().rev().fold(succ, |succ, &(_, ref expr)| {
1200 self.propagate_through_expr(&**expr, succ)
1208 ExprBlock(ref blk) => {
1209 self.propagate_through_block(&**blk, succ)
1213 self.ir.tcx.sess.span_bug(expr.span, "unexpanded macro");
1218 fn propagate_through_lvalue_components(&mut self,
1224 // In general, the full flow graph structure for an
1225 // assignment/move/etc can be handled in one of two ways,
1226 // depending on whether what is being assigned is a "tracked
1227 // value" or not. A tracked value is basically a local
1228 // variable or argument.
1230 // The two kinds of graphs are:
1232 // Tracked lvalue Untracked lvalue
1233 // ----------------------++-----------------------
1237 // (rvalue) || (rvalue)
1240 // (write of lvalue) || (lvalue components)
1245 // ----------------------++-----------------------
1247 // I will cover the two cases in turn:
1249 // # Tracked lvalues
1251 // A tracked lvalue is a local variable/argument `x`. In
1252 // these cases, the link_node where the write occurs is linked
1253 // to node id of `x`. The `write_lvalue()` routine generates
1254 // the contents of this node. There are no subcomponents to
1257 // # Non-tracked lvalues
1259 // These are lvalues like `x[5]` or `x.f`. In that case, we
1260 // basically ignore the value which is written to but generate
1261 // reads for the components---`x` in these two examples. The
1262 // components reads are generated by
1263 // `propagate_through_lvalue_components()` (this fn).
1265 // # Illegal lvalues
1267 // It is still possible to observe assignments to non-lvalues;
1268 // these errors are detected in the later pass borrowck. We
1269 // just ignore such cases and treat them as reads.
1272 ExprPath(_) => succ,
1273 ExprField(ref e, _, _) => self.propagate_through_expr(&**e, succ),
1274 _ => self.propagate_through_expr(expr, succ)
1278 // see comment on propagate_through_lvalue()
1279 fn write_lvalue(&mut self, expr: &Expr, succ: LiveNode, acc: uint)
1282 ExprPath(_) => self.access_path(expr, succ, acc),
1284 // We do not track other lvalues, so just propagate through
1285 // to their subcomponents. Also, it may happen that
1286 // non-lvalues occur here, because those are detected in the
1287 // later pass borrowck.
1292 fn access_path(&mut self, expr: &Expr, succ: LiveNode, acc: uint)
1294 let def = self.ir.tcx.def_map.borrow().get_copy(&expr.id);
1295 match moved_variable_node_id_from_def(def) {
1297 let ln = self.live_node(expr.id, expr.span);
1299 self.init_from_succ(ln, succ);
1300 let var = self.variable(nid, expr.span);
1301 self.acc(ln, var, acc);
1309 fn propagate_through_loop(&mut self,
1318 We model control flow like this:
1336 let mut first_merge = true;
1337 let ln = self.live_node(expr.id, expr.span);
1338 self.init_empty(ln, succ);
1339 if kind != LoopLoop {
1340 // If this is not a `loop` loop, then it's possible we bypass
1341 // the body altogether. Otherwise, the only way is via a `break`
1342 // in the loop body.
1343 self.merge_from_succ(ln, succ, first_merge);
1344 first_merge = false;
1346 debug!("propagate_through_loop: using id for loop body {} {}",
1347 expr.id, block_to_string(body));
1349 let cond_ln = match kind {
1350 LoopLoop | ForLoop => ln,
1351 WhileLoop(ref cond) => self.propagate_through_expr(&**cond, ln),
1353 let body_ln = self.with_loop_nodes(expr.id, succ, ln, |this| {
1354 this.propagate_through_block(body, cond_ln)
1357 // repeat until fixed point is reached:
1358 while self.merge_from_succ(ln, body_ln, first_merge) {
1359 first_merge = false;
1361 let new_cond_ln = match kind {
1362 LoopLoop | ForLoop => ln,
1363 WhileLoop(ref cond) => {
1364 self.propagate_through_expr(&**cond, ln)
1367 assert!(cond_ln == new_cond_ln);
1368 assert!(body_ln == self.with_loop_nodes(expr.id, succ, ln,
1369 |this| this.propagate_through_block(body, cond_ln)));
1375 fn with_loop_nodes<R>(&mut self,
1376 loop_node_id: NodeId,
1379 f: |&mut Liveness<'a, 'tcx>| -> R)
1381 debug!("with_loop_nodes: {} {}", loop_node_id, break_ln.get());
1382 self.loop_scope.push(loop_node_id);
1383 self.break_ln.insert(loop_node_id, break_ln);
1384 self.cont_ln.insert(loop_node_id, cont_ln);
1386 self.loop_scope.pop();
1391 // _______________________________________________________________________
1392 // Checking for error conditions
1394 fn check_local(this: &mut Liveness, local: &Local) {
1397 this.warn_about_unused_or_dead_vars_in_pat(&*local.pat);
1400 this.pat_bindings(&*local.pat, |this, ln, var, sp, id| {
1401 this.warn_about_unused(sp, id, ln, var);
1406 visit::walk_local(this, local, ());
1409 fn check_arm(this: &mut Liveness, arm: &Arm) {
1410 this.arm_pats_bindings(arm.pats.as_slice(), |this, ln, var, sp, id| {
1411 this.warn_about_unused(sp, id, ln, var);
1413 visit::walk_arm(this, arm, ());
1416 fn check_expr(this: &mut Liveness, expr: &Expr) {
1418 ExprAssign(ref l, ref r) => {
1419 this.check_lvalue(&**l);
1420 this.visit_expr(&**r, ());
1422 visit::walk_expr(this, expr, ());
1425 ExprAssignOp(_, ref l, _) => {
1426 this.check_lvalue(&**l);
1428 visit::walk_expr(this, expr, ());
1431 ExprInlineAsm(ref ia) => {
1432 for &(_, ref input) in ia.inputs.iter() {
1433 this.visit_expr(&**input, ());
1436 // Output operands must be lvalues
1437 for &(_, ref out, _) in ia.outputs.iter() {
1438 this.check_lvalue(&**out);
1439 this.visit_expr(&**out, ());
1442 visit::walk_expr(this, expr, ());
1445 // no correctness conditions related to liveness
1446 ExprCall(..) | ExprMethodCall(..) | ExprIf(..) | ExprMatch(..) |
1447 ExprWhile(..) | ExprLoop(..) | ExprIndex(..) | ExprField(..) |
1448 ExprVec(..) | ExprTup(..) | ExprBinary(..) |
1449 ExprCast(..) | ExprUnary(..) | ExprRet(..) | ExprBreak(..) |
1450 ExprAgain(..) | ExprLit(_) | ExprBlock(..) |
1451 ExprMac(..) | ExprAddrOf(..) | ExprStruct(..) | ExprRepeat(..) |
1452 ExprParen(..) | ExprFnBlock(..) | ExprProc(..) | ExprUnboxedFn(..) |
1453 ExprPath(..) | ExprBox(..) | ExprForLoop(..) => {
1454 visit::walk_expr(this, expr, ());
1459 fn check_fn(_v: &Liveness,
1465 // do not check contents of nested fns
1468 impl<'a, 'tcx> Liveness<'a, 'tcx> {
1475 if self.live_on_entry(entry_ln, self.s.no_ret_var).is_some() {
1476 // if no_ret_var is live, then we fall off the end of the
1477 // function without any kind of return expression:
1479 let t_ret = ty::ty_fn_ret(ty::node_id_to_type(self.ir.tcx, id));
1480 if ty::type_is_nil(t_ret) {
1481 // for nil return types, it is ok to not return a value expl.
1482 } else if ty::type_is_bot(t_ret) {
1483 // for bot return types, not ok. Function should fail.
1484 self.ir.tcx.sess.span_err(
1485 sp, "some control paths may return");
1487 let ends_with_stmt = match body.expr {
1488 None if body.stmts.len() > 0 =>
1489 match body.stmts.last().unwrap().node {
1490 StmtSemi(ref e, _) => {
1491 let t_stmt = ty::expr_ty(self.ir.tcx, &**e);
1492 ty::get(t_stmt).sty == ty::get(t_ret).sty
1498 self.ir.tcx.sess.span_err(
1499 sp, "not all control paths return a value");
1501 let last_stmt = body.stmts.last().unwrap();
1502 let original_span = original_sp(last_stmt.span, sp);
1503 let span_semicolon = Span {
1504 lo: original_span.hi - BytePos(1),
1505 hi: original_span.hi,
1506 expn_info: original_span.expn_info
1508 self.ir.tcx.sess.span_note(
1509 span_semicolon, "consider removing this semicolon:");
1515 fn check_lvalue(&mut self, expr: &Expr) {
1518 match self.ir.tcx.def_map.borrow().get_copy(&expr.id) {
1519 DefLocal(nid, _) => {
1520 // Assignment to an immutable variable or argument: only legal
1521 // if there is no later assignment. If this local is actually
1522 // mutable, then check for a reassignment to flag the mutability
1524 let ln = self.live_node(expr.id, expr.span);
1525 let var = self.variable(nid, expr.span);
1526 self.warn_about_dead_assign(expr.span, expr.id, ln, var);
1529 match moved_variable_node_id_from_def(def) {
1531 let ln = self.live_node(expr.id, expr.span);
1532 let var = self.variable(nid, expr.span);
1533 self.warn_about_dead_assign(expr.span, expr.id, ln, var);
1542 // For other kinds of lvalues, no checks are required,
1543 // and any embedded expressions are actually rvalues
1544 visit::walk_expr(self, expr, ());
1549 fn should_warn(&self, var: Variable) -> Option<String> {
1550 let name = self.ir.variable_name(var);
1551 if name.len() == 0 || name.as_bytes()[0] == ('_' as u8) {
1558 fn warn_about_unused_args(&self, decl: &FnDecl, entry_ln: LiveNode) {
1559 for arg in decl.inputs.iter() {
1560 pat_util::pat_bindings(&self.ir.tcx.def_map,
1562 |_bm, p_id, sp, path1| {
1563 let var = self.variable(p_id, sp);
1564 // Ignore unused self.
1565 let ident = path1.node;
1566 if ident.name != special_idents::self_.name {
1567 self.warn_about_unused(sp, p_id, entry_ln, var);
1573 fn warn_about_unused_or_dead_vars_in_pat(&mut self, pat: &Pat) {
1574 self.pat_bindings(pat, |this, ln, var, sp, id| {
1575 if !this.warn_about_unused(sp, id, ln, var) {
1576 this.warn_about_dead_assign(sp, id, ln, var);
1581 fn warn_about_unused(&self,
1587 if !self.used_on_entry(ln, var) {
1588 let r = self.should_warn(var);
1589 for name in r.iter() {
1591 // annoying: for parameters in funcs like `fn(x: int)
1592 // {ret}`, there is only one node, so asking about
1593 // assigned_on_exit() is not meaningful.
1594 let is_assigned = if ln == self.s.exit_ln {
1597 self.assigned_on_exit(ln, var).is_some()
1601 self.ir.tcx.sess.add_lint(lint::builtin::UNUSED_VARIABLE, id, sp,
1602 format!("variable `{}` is assigned to, but never used",
1605 self.ir.tcx.sess.add_lint(lint::builtin::UNUSED_VARIABLE, id, sp,
1606 format!("unused variable: `{}`", *name));
1615 fn warn_about_dead_assign(&self,
1620 if self.live_on_exit(ln, var).is_none() {
1621 let r = self.should_warn(var);
1622 for name in r.iter() {
1623 self.ir.tcx.sess.add_lint(lint::builtin::DEAD_ASSIGNMENT, id, sp,
1624 format!("value assigned to `{}` is never read", *name));