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_str, block_to_str};
125 use syntax::{visit, ast_util};
126 use syntax::visit::{Visitor, FnKind};
128 #[deriving(PartialEq)]
129 struct Variable(uint);
130 #[deriving(PartialEq)]
131 struct LiveNode(uint);
134 fn get(&self) -> uint { let Variable(v) = *self; v }
138 fn get(&self) -> uint { let LiveNode(v) = *self; v }
141 impl Clone for LiveNode {
142 fn clone(&self) -> LiveNode {
147 #[deriving(PartialEq)]
155 fn live_node_kind_to_str(lnk: LiveNodeKind, cx: &ty::ctxt) -> String {
156 let cm = cx.sess.codemap();
159 format!("Free var node [{}]", cm.span_to_str(s))
162 format!("Expr node [{}]", cm.span_to_str(s))
165 format!("Var def node [{}]", cm.span_to_str(s))
167 ExitNode => "Exit node".to_string(),
171 impl<'a> Visitor<()> for IrMaps<'a> {
172 fn visit_fn(&mut self, fk: &FnKind, fd: &FnDecl, b: &Block, s: Span, n: NodeId, _: ()) {
173 visit_fn(self, fk, fd, b, s, n);
175 fn visit_local(&mut self, l: &Local, _: ()) { visit_local(self, l); }
176 fn visit_expr(&mut self, ex: &Expr, _: ()) { visit_expr(self, ex); }
177 fn visit_arm(&mut self, a: &Arm, _: ()) { visit_arm(self, a); }
180 pub fn check_crate(tcx: &ty::ctxt,
182 visit::walk_crate(&mut IrMaps::new(tcx), krate, ());
183 tcx.sess.abort_if_errors();
186 impl fmt::Show for LiveNode {
187 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
188 write!(f, "ln({})", self.get())
192 impl fmt::Show for Variable {
193 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
194 write!(f, "v({})", self.get())
198 // ______________________________________________________________________
201 // This is the first pass and the one that drives the main
202 // computation. It walks up and down the IR once. On the way down,
203 // we count for each function the number of variables as well as
204 // liveness nodes. A liveness node is basically an expression or
205 // capture clause that does something of interest: either it has
206 // interesting control flow or it uses/defines a local variable.
208 // On the way back up, at each function node we create liveness sets
209 // (we now know precisely how big to make our various vectors and so
210 // forth) and then do the data-flow propagation to compute the set
211 // of live variables at each program point.
213 // Finally, we run back over the IR one last time and, using the
214 // computed liveness, check various safety conditions. For example,
215 // there must be no live nodes at the definition site for a variable
216 // unless it has an initializer. Similarly, each non-mutable local
217 // variable must not be assigned if there is some successor
218 // assignment. And so forth.
221 fn is_valid(&self) -> bool {
222 self.get() != uint::MAX
226 fn invalid_node() -> LiveNode { LiveNode(uint::MAX) }
247 num_live_nodes: uint,
249 live_node_map: NodeMap<LiveNode>,
250 variable_map: NodeMap<Variable>,
251 capture_info_map: NodeMap<Rc<Vec<CaptureInfo>>>,
252 var_kinds: Vec<VarKind>,
253 lnks: Vec<LiveNodeKind>,
256 impl<'a> IrMaps<'a> {
257 fn new(tcx: &'a ty::ctxt) -> IrMaps<'a> {
262 live_node_map: NodeMap::new(),
263 variable_map: NodeMap::new(),
264 capture_info_map: NodeMap::new(),
265 var_kinds: Vec::new(),
270 fn add_live_node(&mut self, lnk: LiveNodeKind) -> LiveNode {
271 let ln = LiveNode(self.num_live_nodes);
273 self.num_live_nodes += 1;
275 debug!("{} is of kind {}", ln.to_str(),
276 live_node_kind_to_str(lnk, self.tcx));
281 fn add_live_node_for_node(&mut self, node_id: NodeId, lnk: LiveNodeKind) {
282 let ln = self.add_live_node(lnk);
283 self.live_node_map.insert(node_id, ln);
285 debug!("{} is node {}", ln.to_str(), node_id);
288 fn add_variable(&mut self, vk: VarKind) -> Variable {
289 let v = Variable(self.num_vars);
290 self.var_kinds.push(vk);
294 Local(LocalInfo { id: node_id, .. }) | Arg(node_id, _) => {
295 self.variable_map.insert(node_id, v);
300 debug!("{} is {:?}", v.to_str(), vk);
305 fn variable(&self, node_id: NodeId, span: Span) -> Variable {
306 match self.variable_map.find(&node_id) {
311 .span_bug(span, format!("no variable registered for id {}",
312 node_id).as_slice());
317 fn variable_name(&self, var: Variable) -> String {
318 match self.var_kinds.get(var.get()) {
319 &Local(LocalInfo { ident: nm, .. }) | &Arg(_, nm) => {
320 token::get_ident(nm).get().to_str()
322 &ImplicitRet => "<implicit-ret>".to_string()
326 fn set_captures(&mut self, node_id: NodeId, cs: Vec<CaptureInfo>) {
327 self.capture_info_map.insert(node_id, Rc::new(cs));
330 fn lnk(&self, ln: LiveNode) -> LiveNodeKind {
331 *self.lnks.get(ln.get())
335 impl<'a> Visitor<()> for Liveness<'a> {
336 fn visit_fn(&mut self, fk: &FnKind, fd: &FnDecl, b: &Block, s: Span, n: NodeId, _: ()) {
337 check_fn(self, fk, fd, b, s, n);
339 fn visit_local(&mut self, l: &Local, _: ()) {
340 check_local(self, l);
342 fn visit_expr(&mut self, ex: &Expr, _: ()) {
343 check_expr(self, ex);
345 fn visit_arm(&mut self, a: &Arm, _: ()) {
350 fn visit_fn(ir: &mut IrMaps,
356 debug!("visit_fn: id={}", id);
357 let _i = ::util::common::indenter();
359 // swap in a new set of IR maps for this function body:
360 let mut fn_maps = IrMaps::new(ir.tcx);
363 debug!("creating fn_maps: {}", transmute::<&IrMaps, *IrMaps>(&fn_maps));
366 for arg in decl.inputs.iter() {
367 pat_util::pat_bindings(&ir.tcx.def_map,
369 |_bm, arg_id, _x, path| {
370 debug!("adding argument {}", arg_id);
371 let ident = ast_util::path_to_ident(path);
372 fn_maps.add_variable(Arg(arg_id, ident));
376 // gather up the various local variables, significant expressions,
378 visit::walk_fn(&mut fn_maps, fk, decl, body, sp, ());
380 // Special nodes and variables:
381 // - exit_ln represents the end of the fn, either by return or fail
382 // - implicit_ret_var is a pseudo-variable that represents
383 // an implicit return
384 let specials = Specials {
385 exit_ln: fn_maps.add_live_node(ExitNode),
386 fallthrough_ln: fn_maps.add_live_node(ExitNode),
387 no_ret_var: fn_maps.add_variable(ImplicitRet)
391 let mut lsets = Liveness::new(&mut fn_maps, specials);
392 let entry_ln = lsets.compute(decl, body);
394 // check for various error conditions
395 lsets.visit_block(body, ());
396 lsets.check_ret(id, sp, fk, entry_ln, body);
397 lsets.warn_about_unused_args(decl, entry_ln);
400 fn visit_local(ir: &mut IrMaps, local: &Local) {
401 pat_util::pat_bindings(&ir.tcx.def_map, &*local.pat, |_, p_id, sp, path| {
402 debug!("adding local variable {}", p_id);
403 let name = ast_util::path_to_ident(path);
404 ir.add_live_node_for_node(p_id, VarDefNode(sp));
405 ir.add_variable(Local(LocalInfo {
410 visit::walk_local(ir, local, ());
413 fn visit_arm(ir: &mut IrMaps, arm: &Arm) {
414 for pat in arm.pats.iter() {
415 pat_util::pat_bindings(&ir.tcx.def_map, &**pat, |bm, p_id, sp, path| {
416 debug!("adding local variable {} from match with bm {:?}",
418 let name = ast_util::path_to_ident(path);
419 ir.add_live_node_for_node(p_id, VarDefNode(sp));
420 ir.add_variable(Local(LocalInfo {
426 visit::walk_arm(ir, arm, ());
429 fn moved_variable_node_id_from_def(def: Def) -> Option<NodeId> {
433 DefLocal(nid, _) => Some(nid),
439 fn visit_expr(ir: &mut IrMaps, expr: &Expr) {
441 // live nodes required for uses or definitions of variables:
443 let def = ir.tcx.def_map.borrow().get_copy(&expr.id);
444 debug!("expr {}: path that leads to {:?}", expr.id, def);
445 if moved_variable_node_id_from_def(def).is_some() {
446 ir.add_live_node_for_node(expr.id, ExprNode(expr.span));
448 visit::walk_expr(ir, expr, ());
450 ExprFnBlock(..) | ExprProc(..) => {
451 // Interesting control flow (for loops can contain labeled
452 // breaks or continues)
453 ir.add_live_node_for_node(expr.id, ExprNode(expr.span));
455 // Make a live_node for each captured variable, with the span
456 // being the location that the variable is used. This results
457 // in better error messages than just pointing at the closure
458 // construction site.
459 let mut call_caps = Vec::new();
460 freevars::with_freevars(ir.tcx, expr.id, |freevars| {
461 for fv in freevars.iter() {
462 match moved_variable_node_id_from_def(fv.def) {
464 let fv_ln = ir.add_live_node(FreeVarNode(fv.span));
465 call_caps.push(CaptureInfo {ln: fv_ln,
472 ir.set_captures(expr.id, call_caps);
474 visit::walk_expr(ir, expr, ());
477 // live nodes required for interesting control flow:
478 ExprIf(..) | ExprMatch(..) | ExprWhile(..) | ExprLoop(..) => {
479 ir.add_live_node_for_node(expr.id, ExprNode(expr.span));
480 visit::walk_expr(ir, expr, ());
482 ExprForLoop(..) => fail!("non-desugared expr_for_loop"),
483 ExprBinary(op, _, _) if ast_util::lazy_binop(op) => {
484 ir.add_live_node_for_node(expr.id, ExprNode(expr.span));
485 visit::walk_expr(ir, expr, ());
488 // otherwise, live nodes are not required:
489 ExprIndex(..) | ExprField(..) | ExprVstore(..) | ExprVec(..) |
490 ExprCall(..) | ExprMethodCall(..) | ExprTup(..) |
491 ExprBinary(..) | ExprAddrOf(..) |
492 ExprCast(..) | ExprUnary(..) | ExprBreak(_) |
493 ExprAgain(_) | ExprLit(_) | ExprRet(..) | ExprBlock(..) |
494 ExprAssign(..) | ExprAssignOp(..) | ExprMac(..) |
495 ExprStruct(..) | ExprRepeat(..) | ExprParen(..) |
496 ExprInlineAsm(..) | ExprBox(..) => {
497 visit::walk_expr(ir, expr, ());
502 // ______________________________________________________________________
503 // Computing liveness sets
505 // Actually we compute just a bit more than just liveness, but we use
506 // the same basic propagation framework in all cases.
515 fn invalid_users() -> Users {
517 reader: invalid_node(),
518 writer: invalid_node(),
525 fallthrough_ln: LiveNode,
529 static ACC_READ: uint = 1u;
530 static ACC_WRITE: uint = 2u;
531 static ACC_USE: uint = 4u;
533 struct Liveness<'a> {
534 ir: &'a mut IrMaps<'a>,
536 successors: Vec<LiveNode>,
538 // The list of node IDs for the nested loop scopes
540 loop_scope: Vec<NodeId>,
541 // mappings from loop node ID to LiveNode
542 // ("break" label should map to loop node ID,
543 // it probably doesn't now)
544 break_ln: NodeMap<LiveNode>,
545 cont_ln: NodeMap<LiveNode>
548 impl<'a> Liveness<'a> {
549 fn new(ir: &'a mut IrMaps<'a>, specials: Specials) -> Liveness<'a> {
550 let num_live_nodes = ir.num_live_nodes;
551 let num_vars = ir.num_vars;
555 successors: Vec::from_elem(num_live_nodes, invalid_node()),
556 users: Vec::from_elem(num_live_nodes * num_vars, invalid_users()),
557 loop_scope: Vec::new(),
558 break_ln: NodeMap::new(),
559 cont_ln: NodeMap::new(),
563 fn live_node(&self, node_id: NodeId, span: Span) -> LiveNode {
564 match self.ir.live_node_map.find(&node_id) {
567 // This must be a mismatch between the ir_map construction
568 // above and the propagation code below; the two sets of
569 // code have to agree about which AST nodes are worth
570 // creating liveness nodes for.
571 self.ir.tcx.sess.span_bug(
573 format!("no live node registered for node {}",
574 node_id).as_slice());
579 fn variable(&self, node_id: NodeId, span: Span) -> Variable {
580 self.ir.variable(node_id, span)
583 fn pat_bindings(&mut self,
585 f: |&mut Liveness<'a>, LiveNode, Variable, Span, NodeId|) {
586 pat_util::pat_bindings(&self.ir.tcx.def_map, pat, |_bm, p_id, sp, _n| {
587 let ln = self.live_node(p_id, sp);
588 let var = self.variable(p_id, sp);
589 f(self, ln, var, sp, p_id);
593 fn arm_pats_bindings(&mut self,
595 f: |&mut Liveness<'a>, LiveNode, Variable, Span, NodeId|) {
596 // only consider the first pattern; any later patterns must have
597 // the same bindings, and we also consider the first pattern to be
598 // the "authoritative" set of ids
599 if !pats.is_empty() {
600 self.pat_bindings(&*pats[0], f)
604 fn define_bindings_in_pat(&mut self, pat: Gc<Pat>, succ: LiveNode)
606 self.define_bindings_in_arm_pats([pat], succ)
609 fn define_bindings_in_arm_pats(&mut self, pats: &[Gc<Pat>], succ: LiveNode)
612 self.arm_pats_bindings(pats, |this, ln, var, _sp, _id| {
613 this.init_from_succ(ln, succ);
614 this.define(ln, var);
620 fn idx(&self, ln: LiveNode, var: Variable) -> uint {
621 ln.get() * self.ir.num_vars + var.get()
624 fn live_on_entry(&self, ln: LiveNode, var: Variable)
625 -> Option<LiveNodeKind> {
626 assert!(ln.is_valid());
627 let reader = self.users.get(self.idx(ln, var)).reader;
628 if reader.is_valid() {Some(self.ir.lnk(reader))} else {None}
632 Is this variable live on entry to any of its successor nodes?
634 fn live_on_exit(&self, ln: LiveNode, var: Variable)
635 -> Option<LiveNodeKind> {
636 let successor = *self.successors.get(ln.get());
637 self.live_on_entry(successor, var)
640 fn used_on_entry(&self, ln: LiveNode, var: Variable) -> bool {
641 assert!(ln.is_valid());
642 self.users.get(self.idx(ln, var)).used
645 fn assigned_on_entry(&self, ln: LiveNode, var: Variable)
646 -> Option<LiveNodeKind> {
647 assert!(ln.is_valid());
648 let writer = self.users.get(self.idx(ln, var)).writer;
649 if writer.is_valid() {Some(self.ir.lnk(writer))} else {None}
652 fn assigned_on_exit(&self, ln: LiveNode, var: Variable)
653 -> Option<LiveNodeKind> {
654 let successor = *self.successors.get(ln.get());
655 self.assigned_on_entry(successor, var)
658 fn indices2(&mut self,
661 op: |&mut Liveness<'a>, uint, uint|) {
662 let node_base_idx = self.idx(ln, Variable(0u));
663 let succ_base_idx = self.idx(succ_ln, Variable(0u));
664 for var_idx in range(0u, self.ir.num_vars) {
665 op(self, node_base_idx + var_idx, succ_base_idx + var_idx);
672 test: |uint| -> LiveNode) -> io::IoResult<()> {
673 let node_base_idx = self.idx(ln, Variable(0));
674 for var_idx in range(0u, self.ir.num_vars) {
675 let idx = node_base_idx + var_idx;
676 if test(idx).is_valid() {
677 try!(write!(wr, " {}", Variable(var_idx).to_str()));
683 fn find_loop_scope(&self,
684 opt_label: Option<Ident>,
690 // Refers to a labeled loop. Use the results of resolve
692 match self.ir.tcx.def_map.borrow().find(&id) {
693 Some(&DefLabel(loop_id)) => loop_id,
694 _ => self.ir.tcx.sess.span_bug(sp, "label on break/loop \
695 doesn't refer to a loop")
699 // Vanilla 'break' or 'loop', so use the enclosing
701 if self.loop_scope.len() == 0 {
702 self.ir.tcx.sess.span_bug(sp, "break outside loop");
704 *self.loop_scope.last().unwrap()
710 #[allow(unused_must_use)]
711 fn ln_str(&self, ln: LiveNode) -> String {
712 let mut wr = io::MemWriter::new();
714 let wr = &mut wr as &mut io::Writer;
715 write!(wr, "[ln({}) of kind {:?} reads", ln.get(), self.ir.lnk(ln));
716 self.write_vars(wr, ln, |idx| self.users.get(idx).reader);
717 write!(wr, " writes");
718 self.write_vars(wr, ln, |idx| self.users.get(idx).writer);
719 write!(wr, " precedes {}]", self.successors.get(ln.get()).to_str());
721 str::from_utf8(wr.unwrap().as_slice()).unwrap().to_string()
724 fn init_empty(&mut self, ln: LiveNode, succ_ln: LiveNode) {
725 *self.successors.get_mut(ln.get()) = succ_ln;
727 // It is not necessary to initialize the
728 // values to empty because this is the value
729 // they have when they are created, and the sets
730 // only grow during iterations.
732 // self.indices(ln) { |idx|
733 // self.users[idx] = invalid_users();
737 fn init_from_succ(&mut self, ln: LiveNode, succ_ln: LiveNode) {
738 // more efficient version of init_empty() / merge_from_succ()
739 *self.successors.get_mut(ln.get()) = succ_ln;
741 self.indices2(ln, succ_ln, |this, idx, succ_idx| {
742 *this.users.get_mut(idx) = *this.users.get(succ_idx)
744 debug!("init_from_succ(ln={}, succ={})",
745 self.ln_str(ln), self.ln_str(succ_ln));
748 fn merge_from_succ(&mut self,
753 if ln == succ_ln { return false; }
755 let mut changed = false;
756 self.indices2(ln, succ_ln, |this, idx, succ_idx| {
757 changed |= copy_if_invalid(this.users.get(succ_idx).reader,
758 &mut this.users.get_mut(idx).reader);
759 changed |= copy_if_invalid(this.users.get(succ_idx).writer,
760 &mut this.users.get_mut(idx).writer);
761 if this.users.get(succ_idx).used && !this.users.get(idx).used {
762 this.users.get_mut(idx).used = true;
767 debug!("merge_from_succ(ln={}, succ={}, first_merge={}, changed={})",
768 ln.to_str(), self.ln_str(succ_ln), first_merge, changed);
771 fn copy_if_invalid(src: LiveNode, dst: &mut LiveNode) -> bool {
772 if src.is_valid() && !dst.is_valid() {
781 // Indicates that a local variable was *defined*; we know that no
782 // uses of the variable can precede the definition (resolve checks
783 // this) so we just clear out all the data.
784 fn define(&mut self, writer: LiveNode, var: Variable) {
785 let idx = self.idx(writer, var);
786 self.users.get_mut(idx).reader = invalid_node();
787 self.users.get_mut(idx).writer = invalid_node();
789 debug!("{} defines {} (idx={}): {}", writer.to_str(), var.to_str(),
790 idx, self.ln_str(writer));
793 // Either read, write, or both depending on the acc bitset
794 fn acc(&mut self, ln: LiveNode, var: Variable, acc: uint) {
795 debug!("{} accesses[{:x}] {}: {}",
796 ln.to_str(), acc, var.to_str(), self.ln_str(ln));
798 let idx = self.idx(ln, var);
799 let user = self.users.get_mut(idx);
801 if (acc & ACC_WRITE) != 0 {
802 user.reader = invalid_node();
806 // Important: if we both read/write, must do read second
807 // or else the write will override.
808 if (acc & ACC_READ) != 0 {
812 if (acc & ACC_USE) != 0 {
817 // _______________________________________________________________________
819 fn compute(&mut self, decl: &FnDecl, body: &Block) -> LiveNode {
820 // if there is a `break` or `again` at the top level, then it's
821 // effectively a return---this only occurs in `for` loops,
822 // where the body is really a closure.
824 debug!("compute: using id for block, {}", block_to_str(body));
826 let exit_ln = self.s.exit_ln;
827 let entry_ln: LiveNode =
828 self.with_loop_nodes(body.id, exit_ln, exit_ln,
829 |this| this.propagate_through_fn_block(decl, body));
831 // hack to skip the loop unless debug! is enabled:
832 debug!("^^ liveness computation results for body {} (entry={})",
834 for ln_idx in range(0u, self.ir.num_live_nodes) {
835 debug!("{}", self.ln_str(LiveNode(ln_idx)));
844 fn propagate_through_fn_block(&mut self, _: &FnDecl, blk: &Block)
846 // the fallthrough exit is only for those cases where we do not
847 // explicitly return:
849 self.init_from_succ(s.fallthrough_ln, s.exit_ln);
850 if blk.expr.is_none() {
851 self.acc(s.fallthrough_ln, s.no_ret_var, ACC_READ)
854 self.propagate_through_block(blk, s.fallthrough_ln)
857 fn propagate_through_block(&mut self, blk: &Block, succ: LiveNode)
859 let succ = self.propagate_through_opt_expr(blk.expr, succ);
860 blk.stmts.iter().rev().fold(succ, |succ, stmt| {
861 self.propagate_through_stmt(&**stmt, succ)
865 fn propagate_through_stmt(&mut self, stmt: &Stmt, succ: LiveNode)
868 StmtDecl(ref decl, _) => {
869 self.propagate_through_decl(&**decl, succ)
872 StmtExpr(ref expr, _) | StmtSemi(ref expr, _) => {
873 self.propagate_through_expr(&**expr, succ)
877 self.ir.tcx.sess.span_bug(stmt.span, "unexpanded macro");
882 fn propagate_through_decl(&mut self, decl: &Decl, succ: LiveNode)
885 DeclLocal(ref local) => {
886 self.propagate_through_local(&**local, succ)
892 fn propagate_through_local(&mut self, local: &Local, succ: LiveNode)
894 // Note: we mark the variable as defined regardless of whether
895 // there is an initializer. Initially I had thought to only mark
896 // the live variable as defined if it was initialized, and then we
897 // could check for uninit variables just by scanning what is live
898 // at the start of the function. But that doesn't work so well for
899 // immutable variables defined in a loop:
900 // loop { let x; x = 5; }
901 // because the "assignment" loops back around and generates an error.
903 // So now we just check that variables defined w/o an
904 // initializer are not live at the point of their
905 // initialization, which is mildly more complex than checking
906 // once at the func header but otherwise equivalent.
908 let succ = self.propagate_through_opt_expr(local.init, succ);
909 self.define_bindings_in_pat(local.pat, succ)
912 fn propagate_through_exprs(&mut self, exprs: &[Gc<Expr>], succ: LiveNode)
914 exprs.iter().rev().fold(succ, |succ, expr| {
915 self.propagate_through_expr(&**expr, succ)
919 fn propagate_through_opt_expr(&mut self,
920 opt_expr: Option<Gc<Expr>>,
923 opt_expr.iter().fold(succ, |succ, expr| {
924 self.propagate_through_expr(&**expr, succ)
928 fn propagate_through_expr(&mut self, expr: &Expr, succ: LiveNode)
930 debug!("propagate_through_expr: {}", expr_to_str(expr));
933 // Interesting cases with control flow or which gen/kill
936 self.access_path(expr, succ, ACC_READ | ACC_USE)
939 ExprField(ref e, _, _) => {
940 self.propagate_through_expr(&**e, succ)
943 ExprFnBlock(_, ref blk) | ExprProc(_, ref blk) => {
944 debug!("{} is an ExprFnBlock or ExprProc", expr_to_str(expr));
947 The next-node for a break is the successor of the entire
948 loop. The next-node for a continue is the top of this loop.
950 let node = self.live_node(expr.id, expr.span);
951 self.with_loop_nodes(blk.id, succ, node, |this| {
953 // the construction of a closure itself is not important,
954 // but we have to consider the closed over variables.
955 let caps = match this.ir.capture_info_map.find(&expr.id) {
956 Some(caps) => caps.clone(),
958 this.ir.tcx.sess.span_bug(expr.span, "no registered caps");
961 caps.iter().rev().fold(succ, |succ, cap| {
962 this.init_from_succ(cap.ln, succ);
963 let var = this.variable(cap.var_nid, expr.span);
964 this.acc(cap.ln, var, ACC_READ | ACC_USE);
970 ExprIf(ref cond, ref then, ref els) => {
984 let else_ln = self.propagate_through_opt_expr(els.clone(), succ);
985 let then_ln = self.propagate_through_block(&**then, succ);
986 let ln = self.live_node(expr.id, expr.span);
987 self.init_from_succ(ln, else_ln);
988 self.merge_from_succ(ln, then_ln, false);
989 self.propagate_through_expr(&**cond, ln)
992 ExprWhile(ref cond, ref blk) => {
993 self.propagate_through_loop(expr, Some(cond.clone()), &**blk, succ)
996 ExprForLoop(..) => fail!("non-desugared expr_for_loop"),
998 // Note that labels have been resolved, so we don't need to look
999 // at the label ident
1000 ExprLoop(ref blk, _) => {
1001 self.propagate_through_loop(expr, None, &**blk, succ)
1004 ExprMatch(ref e, ref arms) => {
1019 let ln = self.live_node(expr.id, expr.span);
1020 self.init_empty(ln, succ);
1021 let mut first_merge = true;
1022 for arm in arms.iter() {
1024 self.propagate_through_expr(&*arm.body, succ);
1026 self.propagate_through_opt_expr(arm.guard, body_succ);
1028 self.define_bindings_in_arm_pats(arm.pats.as_slice(),
1030 self.merge_from_succ(ln, arm_succ, first_merge);
1031 first_merge = false;
1033 self.propagate_through_expr(&**e, ln)
1037 // ignore succ and subst exit_ln:
1038 let exit_ln = self.s.exit_ln;
1039 self.propagate_through_opt_expr(o_e, exit_ln)
1042 ExprBreak(opt_label) => {
1043 // Find which label this break jumps to
1044 let sc = self.find_loop_scope(opt_label, expr.id, expr.span);
1046 // Now that we know the label we're going to,
1047 // look it up in the break loop nodes table
1049 match self.break_ln.find(&sc) {
1051 None => self.ir.tcx.sess.span_bug(expr.span,
1052 "break to unknown label")
1056 ExprAgain(opt_label) => {
1057 // Find which label this expr continues to
1058 let sc = self.find_loop_scope(opt_label, expr.id, expr.span);
1060 // Now that we know the label we're going to,
1061 // look it up in the continue loop nodes table
1063 match self.cont_ln.find(&sc) {
1065 None => self.ir.tcx.sess.span_bug(expr.span,
1066 "loop to unknown label")
1070 ExprAssign(ref l, ref r) => {
1071 // see comment on lvalues in
1072 // propagate_through_lvalue_components()
1073 let succ = self.write_lvalue(&**l, succ, ACC_WRITE);
1074 let succ = self.propagate_through_lvalue_components(&**l, succ);
1075 self.propagate_through_expr(&**r, succ)
1078 ExprAssignOp(_, ref l, ref r) => {
1079 // see comment on lvalues in
1080 // propagate_through_lvalue_components()
1081 let succ = self.write_lvalue(&**l, succ, ACC_WRITE|ACC_READ);
1082 let succ = self.propagate_through_expr(&**r, succ);
1083 self.propagate_through_lvalue_components(&**l, succ)
1086 // Uninteresting cases: just propagate in rev exec order
1088 ExprVstore(ref expr, _) => {
1089 self.propagate_through_expr(&**expr, succ)
1092 ExprVec(ref exprs) => {
1093 self.propagate_through_exprs(exprs.as_slice(), succ)
1096 ExprRepeat(ref element, ref count) => {
1097 let succ = self.propagate_through_expr(&**count, succ);
1098 self.propagate_through_expr(&**element, succ)
1101 ExprStruct(_, ref fields, ref with_expr) => {
1102 let succ = self.propagate_through_opt_expr(with_expr.clone(), succ);
1103 fields.iter().rev().fold(succ, |succ, field| {
1104 self.propagate_through_expr(&*field.expr, succ)
1108 ExprCall(ref f, ref args) => {
1109 // calling a fn with bot return type means that the fn
1110 // will fail, and hence the successors can be ignored
1111 let is_bot = !self.ir.tcx.is_method_call(expr.id) && {
1112 let t_ret = ty::ty_fn_ret(ty::expr_ty(self.ir.tcx, &**f));
1113 ty::type_is_bot(t_ret)
1115 let succ = if is_bot {
1120 let succ = self.propagate_through_exprs(args.as_slice(), succ);
1121 self.propagate_through_expr(&**f, succ)
1124 ExprMethodCall(_, _, ref args) => {
1125 // calling a method with bot return type means that the method
1126 // will fail, and hence the successors can be ignored
1127 let t_ret = ty::node_id_to_type(self.ir.tcx, expr.id);
1128 let succ = if ty::type_is_bot(t_ret) {self.s.exit_ln}
1130 self.propagate_through_exprs(args.as_slice(), succ)
1133 ExprTup(ref exprs) => {
1134 self.propagate_through_exprs(exprs.as_slice(), succ)
1137 ExprBinary(op, ref l, ref r) if ast_util::lazy_binop(op) => {
1138 let r_succ = self.propagate_through_expr(&**r, succ);
1140 let ln = self.live_node(expr.id, expr.span);
1141 self.init_from_succ(ln, succ);
1142 self.merge_from_succ(ln, r_succ, false);
1144 self.propagate_through_expr(&**l, ln)
1147 ExprIndex(ref l, ref r) |
1148 ExprBinary(_, ref l, ref r) |
1149 ExprBox(ref l, ref r) => {
1150 self.propagate_through_exprs([l.clone(), r.clone()], succ)
1153 ExprAddrOf(_, ref e) |
1154 ExprCast(ref e, _) |
1155 ExprUnary(_, ref e) |
1156 ExprParen(ref e) => {
1157 self.propagate_through_expr(&**e, succ)
1160 ExprInlineAsm(ref ia) => {
1161 let succ = ia.outputs.iter().rev().fold(succ, |succ, &(_, ref expr)| {
1162 // see comment on lvalues in
1163 // propagate_through_lvalue_components()
1164 let succ = self.write_lvalue(&**expr, succ, ACC_WRITE);
1165 self.propagate_through_lvalue_components(&**expr, succ)
1167 // Inputs are executed first. Propagate last because of rev order
1168 ia.inputs.iter().rev().fold(succ, |succ, &(_, ref expr)| {
1169 self.propagate_through_expr(&**expr, succ)
1177 ExprBlock(ref blk) => {
1178 self.propagate_through_block(&**blk, succ)
1182 self.ir.tcx.sess.span_bug(expr.span, "unexpanded macro");
1187 fn propagate_through_lvalue_components(&mut self,
1193 // In general, the full flow graph structure for an
1194 // assignment/move/etc can be handled in one of two ways,
1195 // depending on whether what is being assigned is a "tracked
1196 // value" or not. A tracked value is basically a local
1197 // variable or argument.
1199 // The two kinds of graphs are:
1201 // Tracked lvalue Untracked lvalue
1202 // ----------------------++-----------------------
1206 // (rvalue) || (rvalue)
1209 // (write of lvalue) || (lvalue components)
1214 // ----------------------++-----------------------
1216 // I will cover the two cases in turn:
1218 // # Tracked lvalues
1220 // A tracked lvalue is a local variable/argument `x`. In
1221 // these cases, the link_node where the write occurs is linked
1222 // to node id of `x`. The `write_lvalue()` routine generates
1223 // the contents of this node. There are no subcomponents to
1226 // # Non-tracked lvalues
1228 // These are lvalues like `x[5]` or `x.f`. In that case, we
1229 // basically ignore the value which is written to but generate
1230 // reads for the components---`x` in these two examples. The
1231 // components reads are generated by
1232 // `propagate_through_lvalue_components()` (this fn).
1234 // # Illegal lvalues
1236 // It is still possible to observe assignments to non-lvalues;
1237 // these errors are detected in the later pass borrowck. We
1238 // just ignore such cases and treat them as reads.
1241 ExprPath(_) => succ,
1242 ExprField(ref e, _, _) => self.propagate_through_expr(&**e, succ),
1243 _ => self.propagate_through_expr(expr, succ)
1247 // see comment on propagate_through_lvalue()
1248 fn write_lvalue(&mut self, expr: &Expr, succ: LiveNode, acc: uint)
1251 ExprPath(_) => self.access_path(expr, succ, acc),
1253 // We do not track other lvalues, so just propagate through
1254 // to their subcomponents. Also, it may happen that
1255 // non-lvalues occur here, because those are detected in the
1256 // later pass borrowck.
1261 fn access_path(&mut self, expr: &Expr, succ: LiveNode, acc: uint)
1263 let def = self.ir.tcx.def_map.borrow().get_copy(&expr.id);
1264 match moved_variable_node_id_from_def(def) {
1266 let ln = self.live_node(expr.id, expr.span);
1268 self.init_from_succ(ln, succ);
1269 let var = self.variable(nid, expr.span);
1270 self.acc(ln, var, acc);
1278 fn propagate_through_loop(&mut self,
1280 cond: Option<Gc<Expr>>,
1287 We model control flow like this:
1305 let mut first_merge = true;
1306 let ln = self.live_node(expr.id, expr.span);
1307 self.init_empty(ln, succ);
1309 // if there is a condition, then it's possible we bypass
1310 // the body altogether. otherwise, the only way is via a
1311 // break in the loop body.
1312 self.merge_from_succ(ln, succ, first_merge);
1313 first_merge = false;
1315 debug!("propagate_through_loop: using id for loop body {} {}",
1316 expr.id, block_to_str(body));
1318 let cond_ln = self.propagate_through_opt_expr(cond, ln);
1319 let body_ln = self.with_loop_nodes(expr.id, succ, ln, |this| {
1320 this.propagate_through_block(body, cond_ln)
1323 // repeat until fixed point is reached:
1324 while self.merge_from_succ(ln, body_ln, first_merge) {
1325 first_merge = false;
1326 assert!(cond_ln == self.propagate_through_opt_expr(cond,
1328 assert!(body_ln == self.with_loop_nodes(expr.id, succ, ln,
1329 |this| this.propagate_through_block(body, cond_ln)));
1335 fn with_loop_nodes<R>(&mut self,
1336 loop_node_id: NodeId,
1339 f: |&mut Liveness<'a>| -> R)
1341 debug!("with_loop_nodes: {} {}", loop_node_id, break_ln.get());
1342 self.loop_scope.push(loop_node_id);
1343 self.break_ln.insert(loop_node_id, break_ln);
1344 self.cont_ln.insert(loop_node_id, cont_ln);
1346 self.loop_scope.pop();
1351 // _______________________________________________________________________
1352 // Checking for error conditions
1354 fn check_local(this: &mut Liveness, local: &Local) {
1357 this.warn_about_unused_or_dead_vars_in_pat(&*local.pat);
1360 this.pat_bindings(&*local.pat, |this, ln, var, sp, id| {
1361 this.warn_about_unused(sp, id, ln, var);
1366 visit::walk_local(this, local, ());
1369 fn check_arm(this: &mut Liveness, arm: &Arm) {
1370 this.arm_pats_bindings(arm.pats.as_slice(), |this, ln, var, sp, id| {
1371 this.warn_about_unused(sp, id, ln, var);
1373 visit::walk_arm(this, arm, ());
1376 fn check_expr(this: &mut Liveness, expr: &Expr) {
1378 ExprAssign(ref l, ref r) => {
1379 this.check_lvalue(&**l);
1380 this.visit_expr(&**r, ());
1382 visit::walk_expr(this, expr, ());
1385 ExprAssignOp(_, ref l, _) => {
1386 this.check_lvalue(&**l);
1388 visit::walk_expr(this, expr, ());
1391 ExprInlineAsm(ref ia) => {
1392 for &(_, ref input) in ia.inputs.iter() {
1393 this.visit_expr(&**input, ());
1396 // Output operands must be lvalues
1397 for &(_, ref out) in ia.outputs.iter() {
1398 this.check_lvalue(&**out);
1399 this.visit_expr(&**out, ());
1402 visit::walk_expr(this, expr, ());
1405 // no correctness conditions related to liveness
1406 ExprCall(..) | ExprMethodCall(..) | ExprIf(..) | ExprMatch(..) |
1407 ExprWhile(..) | ExprLoop(..) | ExprIndex(..) | ExprField(..) |
1408 ExprVstore(..) | ExprVec(..) | ExprTup(..) |
1410 ExprCast(..) | ExprUnary(..) | ExprRet(..) | ExprBreak(..) |
1411 ExprAgain(..) | ExprLit(_) | ExprBlock(..) |
1412 ExprMac(..) | ExprAddrOf(..) | ExprStruct(..) | ExprRepeat(..) |
1413 ExprParen(..) | ExprFnBlock(..) | ExprProc(..) | ExprPath(..) |
1415 visit::walk_expr(this, expr, ());
1417 ExprForLoop(..) => fail!("non-desugared expr_for_loop")
1421 fn check_fn(_v: &Liveness,
1427 // do not check contents of nested fns
1430 impl<'a> Liveness<'a> {
1437 if self.live_on_entry(entry_ln, self.s.no_ret_var).is_some() {
1438 // if no_ret_var is live, then we fall off the end of the
1439 // function without any kind of return expression:
1441 let t_ret = ty::ty_fn_ret(ty::node_id_to_type(self.ir.tcx, id));
1442 if ty::type_is_nil(t_ret) {
1443 // for nil return types, it is ok to not return a value expl.
1444 } else if ty::type_is_bot(t_ret) {
1445 // for bot return types, not ok. Function should fail.
1446 self.ir.tcx.sess.span_err(
1447 sp, "some control paths may return");
1449 let ends_with_stmt = match body.expr {
1450 None if body.stmts.len() > 0 =>
1451 match body.stmts.last().unwrap().node {
1452 StmtSemi(ref e, _) => {
1453 let t_stmt = ty::expr_ty(self.ir.tcx, &**e);
1454 ty::get(t_stmt).sty == ty::get(t_ret).sty
1461 let last_stmt = body.stmts.last().unwrap();
1462 let original_span = original_sp(last_stmt.span, sp);
1463 let span_semicolon = Span {
1464 lo: original_span.hi - BytePos(1),
1465 hi: original_span.hi,
1466 expn_info: original_span.expn_info
1468 self.ir.tcx.sess.span_note(
1469 span_semicolon, "consider removing this semicolon:");
1471 self.ir.tcx.sess.span_err(
1472 sp, "not all control paths return a value");
1477 fn check_lvalue(&mut self, expr: &Expr) {
1480 match self.ir.tcx.def_map.borrow().get_copy(&expr.id) {
1481 DefLocal(nid, _) => {
1482 // Assignment to an immutable variable or argument: only legal
1483 // if there is no later assignment. If this local is actually
1484 // mutable, then check for a reassignment to flag the mutability
1486 let ln = self.live_node(expr.id, expr.span);
1487 let var = self.variable(nid, expr.span);
1488 self.warn_about_dead_assign(expr.span, expr.id, ln, var);
1491 match moved_variable_node_id_from_def(def) {
1493 let ln = self.live_node(expr.id, expr.span);
1494 let var = self.variable(nid, expr.span);
1495 self.warn_about_dead_assign(expr.span, expr.id, ln, var);
1504 // For other kinds of lvalues, no checks are required,
1505 // and any embedded expressions are actually rvalues
1506 visit::walk_expr(self, expr, ());
1511 fn should_warn(&self, var: Variable) -> Option<String> {
1512 let name = self.ir.variable_name(var);
1513 if name.len() == 0 || name.as_slice()[0] == ('_' as u8) {
1520 fn warn_about_unused_args(&self, decl: &FnDecl, entry_ln: LiveNode) {
1521 for arg in decl.inputs.iter() {
1522 pat_util::pat_bindings(&self.ir.tcx.def_map,
1524 |_bm, p_id, sp, path| {
1525 let var = self.variable(p_id, sp);
1526 // Ignore unused self.
1527 let ident = ast_util::path_to_ident(path);
1528 if ident.name != special_idents::self_.name {
1529 self.warn_about_unused(sp, p_id, entry_ln, var);
1535 fn warn_about_unused_or_dead_vars_in_pat(&mut self, pat: &Pat) {
1536 self.pat_bindings(pat, |this, ln, var, sp, id| {
1537 if !this.warn_about_unused(sp, id, ln, var) {
1538 this.warn_about_dead_assign(sp, id, ln, var);
1543 fn warn_about_unused(&self,
1549 if !self.used_on_entry(ln, var) {
1550 let r = self.should_warn(var);
1551 for name in r.iter() {
1553 // annoying: for parameters in funcs like `fn(x: int)
1554 // {ret}`, there is only one node, so asking about
1555 // assigned_on_exit() is not meaningful.
1556 let is_assigned = if ln == self.s.exit_ln {
1559 self.assigned_on_exit(ln, var).is_some()
1563 self.ir.tcx.sess.add_lint(lint::builtin::UNUSED_VARIABLE, id, sp,
1564 format!("variable `{}` is assigned to, but never used",
1567 self.ir.tcx.sess.add_lint(lint::builtin::UNUSED_VARIABLE, id, sp,
1568 format!("unused variable: `{}`", *name));
1577 fn warn_about_dead_assign(&self,
1582 if self.live_on_exit(ln, var).is_none() {
1583 let r = self.should_warn(var);
1584 for name in r.iter() {
1585 self.ir.tcx.sess.add_lint(lint::builtin::DEAD_ASSIGNMENT, id, sp,
1586 format!("value assigned to `{}` is never read", *name));