]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/liveness.rs
core: Use raw pointers to avoid aliasing in str::split_at_mut
[rust.git] / src / librustc / middle / liveness.rs
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.
4 //
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.
10
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
14 //! id.
15 //!
16 //! # Basic idea
17 //!
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.
22 //!
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.
30 //!
31 //! ## Checking initialization
32 //!
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.
37 //!
38 //! ## Checking moves
39 //!
40 //! After each explicit move, the variable must be dead.
41 //!
42 //! ## Computing last uses
43 //!
44 //! Any use of the variable where the variable is dead afterwards is a
45 //! last use.
46 //!
47 //! # Implementation details
48 //!
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).
56 //!
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.
62 //!
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.
66 //!
67 //! ## The `Users` struct
68 //!
69 //! At each live node `N`, we track three pieces of information for each
70 //! variable `V` (these are encapsulated in the `Users` struct):
71 //!
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).
77 //!
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`.
83 //!
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.
88 //!
89 //! ## Special Variables
90 //!
91 //! We generate various special variables for various, well, special purposes.
92 //! These are described in the `specials` struct:
93 //!
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.
96 //!
97 //! - `fallthrough_ln`: a live node that represents a fallthrough
98 //!
99 //! - `no_ret_var`: a synthetic variable that is only 'read' from, the
100 //!   fallthrough node.  This allows us to detect functions where we fail
101 //!   to return explicitly.
102 //! - `clean_exit_var`: a synthetic variable that is only 'read' from the
103 //!   fallthrough node.  It is only live if the function could converge
104 //!   via means other than an explicit `return` expression. That is, it is
105 //!   only dead if the end of the function's block can never be reached.
106 //!   It is the responsibility of typeck to ensure that there are no
107 //!   `return` expressions in a function declared as diverging.
108 use self::LoopKind::*;
109 use self::LiveNodeKind::*;
110 use self::VarKind::*;
111
112 use middle::def::*;
113 use middle::pat_util;
114 use middle::ty;
115 use lint;
116 use util::nodemap::NodeMap;
117
118 use std::{fmt, usize};
119 use std::io::prelude::*;
120 use std::io;
121 use std::rc::Rc;
122 use syntax::ast::{self, NodeId};
123 use syntax::codemap::{BytePos, original_sp, Span};
124 use syntax::parse::token::special_idents;
125 use syntax::ptr::P;
126
127 use rustc_front::hir::Expr;
128 use rustc_front::hir;
129 use rustc_front::print::pprust::{expr_to_string, block_to_string};
130 use rustc_front::intravisit::{self, Visitor, FnKind};
131
132 /// For use with `propagate_through_loop`.
133 enum LoopKind<'a> {
134     /// An endless `loop` loop.
135     LoopLoop,
136     /// A `while` loop, with the given expression as condition.
137     WhileLoop(&'a Expr),
138 }
139
140 #[derive(Copy, Clone, PartialEq)]
141 struct Variable(usize);
142
143 #[derive(Copy, PartialEq)]
144 struct LiveNode(usize);
145
146 impl Variable {
147     fn get(&self) -> usize { let Variable(v) = *self; v }
148 }
149
150 impl LiveNode {
151     fn get(&self) -> usize { let LiveNode(v) = *self; v }
152 }
153
154 impl Clone for LiveNode {
155     fn clone(&self) -> LiveNode {
156         LiveNode(self.get())
157     }
158 }
159
160 #[derive(Copy, Clone, PartialEq, Debug)]
161 enum LiveNodeKind {
162     FreeVarNode(Span),
163     ExprNode(Span),
164     VarDefNode(Span),
165     ExitNode
166 }
167
168 fn live_node_kind_to_string(lnk: LiveNodeKind, cx: &ty::ctxt) -> String {
169     let cm = cx.sess.codemap();
170     match lnk {
171         FreeVarNode(s) => {
172             format!("Free var node [{}]", cm.span_to_string(s))
173         }
174         ExprNode(s) => {
175             format!("Expr node [{}]", cm.span_to_string(s))
176         }
177         VarDefNode(s) => {
178             format!("Var def node [{}]", cm.span_to_string(s))
179         }
180         ExitNode => "Exit node".to_string(),
181     }
182 }
183
184 impl<'a, 'tcx, 'v> Visitor<'v> for IrMaps<'a, 'tcx> {
185     fn visit_fn(&mut self, fk: FnKind<'v>, fd: &'v hir::FnDecl,
186                 b: &'v hir::Block, s: Span, id: NodeId) {
187         visit_fn(self, fk, fd, b, s, id);
188     }
189     fn visit_local(&mut self, l: &hir::Local) { visit_local(self, l); }
190     fn visit_expr(&mut self, ex: &Expr) { visit_expr(self, ex); }
191     fn visit_arm(&mut self, a: &hir::Arm) { visit_arm(self, a); }
192 }
193
194 pub fn check_crate(tcx: &ty::ctxt) {
195     tcx.map.krate().visit_all_items(&mut IrMaps::new(tcx));
196     tcx.sess.abort_if_errors();
197 }
198
199 impl fmt::Debug for LiveNode {
200     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
201         write!(f, "ln({})", self.get())
202     }
203 }
204
205 impl fmt::Debug for Variable {
206     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
207         write!(f, "v({})", self.get())
208     }
209 }
210
211 // ______________________________________________________________________
212 // Creating ir_maps
213 //
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.
220 //
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.
225 //
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.
232
233 impl LiveNode {
234     fn is_valid(&self) -> bool {
235         self.get() != usize::MAX
236     }
237 }
238
239 fn invalid_node() -> LiveNode { LiveNode(usize::MAX) }
240
241 struct CaptureInfo {
242     ln: LiveNode,
243     var_nid: NodeId
244 }
245
246 #[derive(Copy, Clone, Debug)]
247 struct LocalInfo {
248     id: NodeId,
249     name: ast::Name
250 }
251
252 #[derive(Copy, Clone, Debug)]
253 enum VarKind {
254     Arg(NodeId, ast::Name),
255     Local(LocalInfo),
256     ImplicitRet,
257     CleanExit
258 }
259
260 struct IrMaps<'a, 'tcx: 'a> {
261     tcx: &'a ty::ctxt<'tcx>,
262
263     num_live_nodes: usize,
264     num_vars: 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>,
270 }
271
272 impl<'a, 'tcx> IrMaps<'a, 'tcx> {
273     fn new(tcx: &'a ty::ctxt<'tcx>) -> IrMaps<'a, 'tcx> {
274         IrMaps {
275             tcx: tcx,
276             num_live_nodes: 0,
277             num_vars: 0,
278             live_node_map: NodeMap(),
279             variable_map: NodeMap(),
280             capture_info_map: NodeMap(),
281             var_kinds: Vec::new(),
282             lnks: Vec::new(),
283         }
284     }
285
286     fn add_live_node(&mut self, lnk: LiveNodeKind) -> LiveNode {
287         let ln = LiveNode(self.num_live_nodes);
288         self.lnks.push(lnk);
289         self.num_live_nodes += 1;
290
291         debug!("{:?} is of kind {}", ln,
292                live_node_kind_to_string(lnk, self.tcx));
293
294         ln
295     }
296
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);
300
301         debug!("{:?} is node {}", ln, node_id);
302     }
303
304     fn add_variable(&mut self, vk: VarKind) -> Variable {
305         let v = Variable(self.num_vars);
306         self.var_kinds.push(vk);
307         self.num_vars += 1;
308
309         match vk {
310             Local(LocalInfo { id: node_id, .. }) | Arg(node_id, _) => {
311                 self.variable_map.insert(node_id, v);
312             },
313             ImplicitRet | CleanExit => {}
314         }
315
316         debug!("{:?} is {:?}", v, vk);
317
318         v
319     }
320
321     fn variable(&self, node_id: NodeId, span: Span) -> Variable {
322         match self.variable_map.get(&node_id) {
323           Some(&var) => var,
324           None => {
325             self.tcx
326                 .sess
327                 .span_bug(span, &format!("no variable registered for id {}",
328                                         node_id));
329           }
330         }
331     }
332
333     fn variable_name(&self, var: Variable) -> String {
334         match self.var_kinds[var.get()] {
335             Local(LocalInfo { name, .. }) | Arg(_, name) => {
336                 name.to_string()
337             },
338             ImplicitRet => "<implicit-ret>".to_string(),
339             CleanExit => "<clean-exit>".to_string()
340         }
341     }
342
343     fn set_captures(&mut self, node_id: NodeId, cs: Vec<CaptureInfo>) {
344         self.capture_info_map.insert(node_id, Rc::new(cs));
345     }
346
347     fn lnk(&self, ln: LiveNode) -> LiveNodeKind {
348         self.lnks[ln.get()]
349     }
350 }
351
352 impl<'a, 'tcx, 'v> Visitor<'v> for Liveness<'a, 'tcx> {
353     fn visit_fn(&mut self, fk: FnKind<'v>, fd: &'v hir::FnDecl,
354                 b: &'v hir::Block, s: Span, n: NodeId) {
355         check_fn(self, fk, fd, b, s, n);
356     }
357     fn visit_local(&mut self, l: &hir::Local) {
358         check_local(self, l);
359     }
360     fn visit_expr(&mut self, ex: &Expr) {
361         check_expr(self, ex);
362     }
363     fn visit_arm(&mut self, a: &hir::Arm) {
364         check_arm(self, a);
365     }
366 }
367
368 fn visit_fn(ir: &mut IrMaps,
369             fk: FnKind,
370             decl: &hir::FnDecl,
371             body: &hir::Block,
372             sp: Span,
373             id: ast::NodeId) {
374     debug!("visit_fn");
375
376     // swap in a new set of IR maps for this function body:
377     let mut fn_maps = IrMaps::new(ir.tcx);
378
379     debug!("creating fn_maps: {:?}", &fn_maps as *const IrMaps);
380
381     for arg in &decl.inputs {
382         pat_util::pat_bindings(&ir.tcx.def_map,
383                                &*arg.pat,
384                                |_bm, arg_id, _x, path1| {
385             debug!("adding argument {}", arg_id);
386             let name = path1.node;
387             fn_maps.add_variable(Arg(arg_id, name));
388         })
389     };
390
391     // gather up the various local variables, significant expressions,
392     // and so forth:
393     intravisit::walk_fn(&mut fn_maps, fk, decl, body, sp);
394
395     // Special nodes and variables:
396     // - exit_ln represents the end of the fn, either by return or panic
397     // - implicit_ret_var is a pseudo-variable that represents
398     //   an implicit return
399     let specials = Specials {
400         exit_ln: fn_maps.add_live_node(ExitNode),
401         fallthrough_ln: fn_maps.add_live_node(ExitNode),
402         no_ret_var: fn_maps.add_variable(ImplicitRet),
403         clean_exit_var: fn_maps.add_variable(CleanExit)
404     };
405
406     // compute liveness
407     let mut lsets = Liveness::new(&mut fn_maps, specials);
408     let entry_ln = lsets.compute(decl, body);
409
410     // check for various error conditions
411     lsets.visit_block(body);
412     lsets.check_ret(id, sp, fk, entry_ln, body);
413     lsets.warn_about_unused_args(decl, entry_ln);
414 }
415
416 fn visit_local(ir: &mut IrMaps, local: &hir::Local) {
417     pat_util::pat_bindings(&ir.tcx.def_map, &*local.pat, |_, p_id, sp, path1| {
418         debug!("adding local variable {}", p_id);
419         let name = path1.node;
420         ir.add_live_node_for_node(p_id, VarDefNode(sp));
421         ir.add_variable(Local(LocalInfo {
422           id: p_id,
423           name: name
424         }));
425     });
426     intravisit::walk_local(ir, local);
427 }
428
429 fn visit_arm(ir: &mut IrMaps, arm: &hir::Arm) {
430     for pat in &arm.pats {
431         pat_util::pat_bindings(&ir.tcx.def_map, &**pat, |bm, p_id, sp, path1| {
432             debug!("adding local variable {} from match with bm {:?}",
433                    p_id, bm);
434             let name = path1.node;
435             ir.add_live_node_for_node(p_id, VarDefNode(sp));
436             ir.add_variable(Local(LocalInfo {
437                 id: p_id,
438                 name: name
439             }));
440         })
441     }
442     intravisit::walk_arm(ir, arm);
443 }
444
445 fn visit_expr(ir: &mut IrMaps, expr: &Expr) {
446     match expr.node {
447       // live nodes required for uses or definitions of variables:
448       hir::ExprPath(..) => {
449         let def = ir.tcx.def_map.borrow().get(&expr.id).unwrap().full_def();
450         debug!("expr {}: path that leads to {:?}", expr.id, def);
451         if let DefLocal(..) = def {
452             ir.add_live_node_for_node(expr.id, ExprNode(expr.span));
453         }
454         intravisit::walk_expr(ir, expr);
455       }
456       hir::ExprClosure(..) => {
457         // Interesting control flow (for loops can contain labeled
458         // breaks or continues)
459         ir.add_live_node_for_node(expr.id, ExprNode(expr.span));
460
461         // Make a live_node for each captured variable, with the span
462         // being the location that the variable is used.  This results
463         // in better error messages than just pointing at the closure
464         // construction site.
465         let mut call_caps = Vec::new();
466         ir.tcx.with_freevars(expr.id, |freevars| {
467             for fv in freevars {
468                 if let DefLocal(_, rv) = fv.def {
469                     let fv_ln = ir.add_live_node(FreeVarNode(fv.span));
470                     call_caps.push(CaptureInfo {ln: fv_ln,
471                                                 var_nid: rv});
472                 }
473             }
474         });
475         ir.set_captures(expr.id, call_caps);
476
477         intravisit::walk_expr(ir, expr);
478       }
479
480       // live nodes required for interesting control flow:
481       hir::ExprIf(..) | hir::ExprMatch(..) | hir::ExprWhile(..) | hir::ExprLoop(..) => {
482         ir.add_live_node_for_node(expr.id, ExprNode(expr.span));
483         intravisit::walk_expr(ir, expr);
484       }
485       hir::ExprBinary(op, _, _) if ::rustc_front::util::lazy_binop(op.node) => {
486         ir.add_live_node_for_node(expr.id, ExprNode(expr.span));
487         intravisit::walk_expr(ir, expr);
488       }
489
490       // otherwise, live nodes are not required:
491       hir::ExprIndex(..) | hir::ExprField(..) | hir::ExprTupField(..) |
492       hir::ExprVec(..) | hir::ExprCall(..) | hir::ExprMethodCall(..) |
493       hir::ExprTup(..) | hir::ExprBinary(..) | hir::ExprAddrOf(..) |
494       hir::ExprCast(..) | hir::ExprUnary(..) | hir::ExprBreak(_) |
495       hir::ExprAgain(_) | hir::ExprLit(_) | hir::ExprRet(..) |
496       hir::ExprBlock(..) | hir::ExprAssign(..) | hir::ExprAssignOp(..) |
497       hir::ExprStruct(..) | hir::ExprRepeat(..) |
498       hir::ExprInlineAsm(..) | hir::ExprBox(..) |
499       hir::ExprRange(..) | hir::ExprType(..) => {
500           intravisit::walk_expr(ir, expr);
501       }
502     }
503 }
504
505 // ______________________________________________________________________
506 // Computing liveness sets
507 //
508 // Actually we compute just a bit more than just liveness, but we use
509 // the same basic propagation framework in all cases.
510
511 #[derive(Clone, Copy)]
512 struct Users {
513     reader: LiveNode,
514     writer: LiveNode,
515     used: bool
516 }
517
518 fn invalid_users() -> Users {
519     Users {
520         reader: invalid_node(),
521         writer: invalid_node(),
522         used: false
523     }
524 }
525
526 #[derive(Copy, Clone)]
527 struct Specials {
528     exit_ln: LiveNode,
529     fallthrough_ln: LiveNode,
530     no_ret_var: Variable,
531     clean_exit_var: Variable
532 }
533
534 const ACC_READ: u32 = 1;
535 const ACC_WRITE: u32 = 2;
536 const ACC_USE: u32 = 4;
537
538 struct Liveness<'a, 'tcx: 'a> {
539     ir: &'a mut IrMaps<'a, 'tcx>,
540     s: Specials,
541     successors: Vec<LiveNode>,
542     users: Vec<Users>,
543     // The list of node IDs for the nested loop scopes
544     // we're in.
545     loop_scope: Vec<NodeId>,
546     // mappings from loop node ID to LiveNode
547     // ("break" label should map to loop node ID,
548     // it probably doesn't now)
549     break_ln: NodeMap<LiveNode>,
550     cont_ln: NodeMap<LiveNode>
551 }
552
553 impl<'a, 'tcx> Liveness<'a, 'tcx> {
554     fn new(ir: &'a mut IrMaps<'a, 'tcx>, specials: Specials) -> Liveness<'a, 'tcx> {
555         let num_live_nodes = ir.num_live_nodes;
556         let num_vars = ir.num_vars;
557         Liveness {
558             ir: ir,
559             s: specials,
560             successors: vec![invalid_node(); num_live_nodes],
561             users: vec![invalid_users(); num_live_nodes * num_vars],
562             loop_scope: Vec::new(),
563             break_ln: NodeMap(),
564             cont_ln: NodeMap(),
565         }
566     }
567
568     fn live_node(&self, node_id: NodeId, span: Span) -> LiveNode {
569         match self.ir.live_node_map.get(&node_id) {
570           Some(&ln) => ln,
571           None => {
572             // This must be a mismatch between the ir_map construction
573             // above and the propagation code below; the two sets of
574             // code have to agree about which AST nodes are worth
575             // creating liveness nodes for.
576             self.ir.tcx.sess.span_bug(
577                 span,
578                 &format!("no live node registered for node {}",
579                         node_id));
580           }
581         }
582     }
583
584     fn variable(&self, node_id: NodeId, span: Span) -> Variable {
585         self.ir.variable(node_id, span)
586     }
587
588     fn pat_bindings<F>(&mut self, pat: &hir::Pat, mut f: F) where
589         F: FnMut(&mut Liveness<'a, 'tcx>, LiveNode, Variable, Span, NodeId),
590     {
591         pat_util::pat_bindings(&self.ir.tcx.def_map, pat, |_bm, p_id, sp, _n| {
592             let ln = self.live_node(p_id, sp);
593             let var = self.variable(p_id, sp);
594             f(self, ln, var, sp, p_id);
595         })
596     }
597
598     fn arm_pats_bindings<F>(&mut self, pat: Option<&hir::Pat>, f: F) where
599         F: FnMut(&mut Liveness<'a, 'tcx>, LiveNode, Variable, Span, NodeId),
600     {
601         match pat {
602             Some(pat) => {
603                 self.pat_bindings(pat, f);
604             }
605             None => {}
606         }
607     }
608
609     fn define_bindings_in_pat(&mut self, pat: &hir::Pat, succ: LiveNode)
610                               -> LiveNode {
611         self.define_bindings_in_arm_pats(Some(pat), succ)
612     }
613
614     fn define_bindings_in_arm_pats(&mut self, pat: Option<&hir::Pat>, succ: LiveNode)
615                                    -> LiveNode {
616         let mut succ = succ;
617         self.arm_pats_bindings(pat, |this, ln, var, _sp, _id| {
618             this.init_from_succ(ln, succ);
619             this.define(ln, var);
620             succ = ln;
621         });
622         succ
623     }
624
625     fn idx(&self, ln: LiveNode, var: Variable) -> usize {
626         ln.get() * self.ir.num_vars + var.get()
627     }
628
629     fn live_on_entry(&self, ln: LiveNode, var: Variable)
630                       -> Option<LiveNodeKind> {
631         assert!(ln.is_valid());
632         let reader = self.users[self.idx(ln, var)].reader;
633         if reader.is_valid() {Some(self.ir.lnk(reader))} else {None}
634     }
635
636     /*
637     Is this variable live on entry to any of its successor nodes?
638     */
639     fn live_on_exit(&self, ln: LiveNode, var: Variable)
640                     -> Option<LiveNodeKind> {
641         let successor = self.successors[ln.get()];
642         self.live_on_entry(successor, var)
643     }
644
645     fn used_on_entry(&self, ln: LiveNode, var: Variable) -> bool {
646         assert!(ln.is_valid());
647         self.users[self.idx(ln, var)].used
648     }
649
650     fn assigned_on_entry(&self, ln: LiveNode, var: Variable)
651                          -> Option<LiveNodeKind> {
652         assert!(ln.is_valid());
653         let writer = self.users[self.idx(ln, var)].writer;
654         if writer.is_valid() {Some(self.ir.lnk(writer))} else {None}
655     }
656
657     fn assigned_on_exit(&self, ln: LiveNode, var: Variable)
658                         -> Option<LiveNodeKind> {
659         let successor = self.successors[ln.get()];
660         self.assigned_on_entry(successor, var)
661     }
662
663     fn indices2<F>(&mut self, ln: LiveNode, succ_ln: LiveNode, mut op: F) where
664         F: FnMut(&mut Liveness<'a, 'tcx>, usize, usize),
665     {
666         let node_base_idx = self.idx(ln, Variable(0));
667         let succ_base_idx = self.idx(succ_ln, Variable(0));
668         for var_idx in 0..self.ir.num_vars {
669             op(self, node_base_idx + var_idx, succ_base_idx + var_idx);
670         }
671     }
672
673     fn write_vars<F>(&self,
674                      wr: &mut Write,
675                      ln: LiveNode,
676                      mut test: F)
677                      -> io::Result<()> where
678         F: FnMut(usize) -> LiveNode,
679     {
680         let node_base_idx = self.idx(ln, Variable(0));
681         for var_idx in 0..self.ir.num_vars {
682             let idx = node_base_idx + var_idx;
683             if test(idx).is_valid() {
684                 try!(write!(wr, " {:?}", Variable(var_idx)));
685             }
686         }
687         Ok(())
688     }
689
690     fn find_loop_scope(&self,
691                        opt_label: Option<ast::Name>,
692                        id: NodeId,
693                        sp: Span)
694                        -> NodeId {
695         match opt_label {
696             Some(_) => {
697                 // Refers to a labeled loop. Use the results of resolve
698                 // to find with one
699                 match self.ir.tcx.def_map.borrow().get(&id).map(|d| d.full_def()) {
700                     Some(DefLabel(loop_id)) => loop_id,
701                     _ => self.ir.tcx.sess.span_bug(sp, "label on break/loop \
702                                                         doesn't refer to a loop")
703                 }
704             }
705             None => {
706                 // Vanilla 'break' or 'loop', so use the enclosing
707                 // loop scope
708                 if self.loop_scope.is_empty() {
709                     self.ir.tcx.sess.span_bug(sp, "break outside loop");
710                 } else {
711                     *self.loop_scope.last().unwrap()
712                 }
713             }
714         }
715     }
716
717     #[allow(unused_must_use)]
718     fn ln_str(&self, ln: LiveNode) -> String {
719         let mut wr = Vec::new();
720         {
721             let wr = &mut wr as &mut Write;
722             write!(wr, "[ln({:?}) of kind {:?} reads", ln.get(), self.ir.lnk(ln));
723             self.write_vars(wr, ln, |idx| self.users[idx].reader);
724             write!(wr, "  writes");
725             self.write_vars(wr, ln, |idx| self.users[idx].writer);
726             write!(wr, "  precedes {:?}]", self.successors[ln.get()]);
727         }
728         String::from_utf8(wr).unwrap()
729     }
730
731     fn init_empty(&mut self, ln: LiveNode, succ_ln: LiveNode) {
732         self.successors[ln.get()] = succ_ln;
733
734         // It is not necessary to initialize the
735         // values to empty because this is the value
736         // they have when they are created, and the sets
737         // only grow during iterations.
738         //
739         // self.indices(ln) { |idx|
740         //     self.users[idx] = invalid_users();
741         // }
742     }
743
744     fn init_from_succ(&mut self, ln: LiveNode, succ_ln: LiveNode) {
745         // more efficient version of init_empty() / merge_from_succ()
746         self.successors[ln.get()] = succ_ln;
747
748         self.indices2(ln, succ_ln, |this, idx, succ_idx| {
749             this.users[idx] = this.users[succ_idx]
750         });
751         debug!("init_from_succ(ln={}, succ={})",
752                self.ln_str(ln), self.ln_str(succ_ln));
753     }
754
755     fn merge_from_succ(&mut self,
756                        ln: LiveNode,
757                        succ_ln: LiveNode,
758                        first_merge: bool)
759                        -> bool {
760         if ln == succ_ln { return false; }
761
762         let mut changed = false;
763         self.indices2(ln, succ_ln, |this, idx, succ_idx| {
764             changed |= copy_if_invalid(this.users[succ_idx].reader,
765                                        &mut this.users[idx].reader);
766             changed |= copy_if_invalid(this.users[succ_idx].writer,
767                                        &mut this.users[idx].writer);
768             if this.users[succ_idx].used && !this.users[idx].used {
769                 this.users[idx].used = true;
770                 changed = true;
771             }
772         });
773
774         debug!("merge_from_succ(ln={:?}, succ={}, first_merge={}, changed={})",
775                ln, self.ln_str(succ_ln), first_merge, changed);
776         return changed;
777
778         fn copy_if_invalid(src: LiveNode, dst: &mut LiveNode) -> bool {
779             if src.is_valid() && !dst.is_valid() {
780                 *dst = src;
781                 true
782             } else {
783                 false
784             }
785         }
786     }
787
788     // Indicates that a local variable was *defined*; we know that no
789     // uses of the variable can precede the definition (resolve checks
790     // this) so we just clear out all the data.
791     fn define(&mut self, writer: LiveNode, var: Variable) {
792         let idx = self.idx(writer, var);
793         self.users[idx].reader = invalid_node();
794         self.users[idx].writer = invalid_node();
795
796         debug!("{:?} defines {:?} (idx={}): {}", writer, var,
797                idx, self.ln_str(writer));
798     }
799
800     // Either read, write, or both depending on the acc bitset
801     fn acc(&mut self, ln: LiveNode, var: Variable, acc: u32) {
802         debug!("{:?} accesses[{:x}] {:?}: {}",
803                ln, acc, var, self.ln_str(ln));
804
805         let idx = self.idx(ln, var);
806         let user = &mut self.users[idx];
807
808         if (acc & ACC_WRITE) != 0 {
809             user.reader = invalid_node();
810             user.writer = ln;
811         }
812
813         // Important: if we both read/write, must do read second
814         // or else the write will override.
815         if (acc & ACC_READ) != 0 {
816             user.reader = ln;
817         }
818
819         if (acc & ACC_USE) != 0 {
820             user.used = true;
821         }
822     }
823
824     // _______________________________________________________________________
825
826     fn compute(&mut self, decl: &hir::FnDecl, body: &hir::Block) -> LiveNode {
827         // if there is a `break` or `again` at the top level, then it's
828         // effectively a return---this only occurs in `for` loops,
829         // where the body is really a closure.
830
831         debug!("compute: using id for block, {}", block_to_string(body));
832
833         let exit_ln = self.s.exit_ln;
834         let entry_ln: LiveNode =
835             self.with_loop_nodes(body.id, exit_ln, exit_ln,
836               |this| this.propagate_through_fn_block(decl, body));
837
838         // hack to skip the loop unless debug! is enabled:
839         debug!("^^ liveness computation results for body {} (entry={:?})",
840                {
841                    for ln_idx in 0..self.ir.num_live_nodes {
842                        debug!("{:?}", self.ln_str(LiveNode(ln_idx)));
843                    }
844                    body.id
845                },
846                entry_ln);
847
848         entry_ln
849     }
850
851     fn propagate_through_fn_block(&mut self, _: &hir::FnDecl, blk: &hir::Block)
852                                   -> LiveNode {
853         // the fallthrough exit is only for those cases where we do not
854         // explicitly return:
855         let s = self.s;
856         self.init_from_succ(s.fallthrough_ln, s.exit_ln);
857         if blk.expr.is_none() {
858             self.acc(s.fallthrough_ln, s.no_ret_var, ACC_READ)
859         }
860         self.acc(s.fallthrough_ln, s.clean_exit_var, ACC_READ);
861
862         self.propagate_through_block(blk, s.fallthrough_ln)
863     }
864
865     fn propagate_through_block(&mut self, blk: &hir::Block, succ: LiveNode)
866                                -> LiveNode {
867         let succ = self.propagate_through_opt_expr(blk.expr.as_ref().map(|e| &**e), succ);
868         blk.stmts.iter().rev().fold(succ, |succ, stmt| {
869             self.propagate_through_stmt(stmt, succ)
870         })
871     }
872
873     fn propagate_through_stmt(&mut self, stmt: &hir::Stmt, succ: LiveNode)
874                               -> LiveNode {
875         match stmt.node {
876             hir::StmtDecl(ref decl, _) => {
877                 self.propagate_through_decl(&**decl, succ)
878             }
879
880             hir::StmtExpr(ref expr, _) | hir::StmtSemi(ref expr, _) => {
881                 self.propagate_through_expr(&**expr, succ)
882             }
883         }
884     }
885
886     fn propagate_through_decl(&mut self, decl: &hir::Decl, succ: LiveNode)
887                               -> LiveNode {
888         match decl.node {
889             hir::DeclLocal(ref local) => {
890                 self.propagate_through_local(&**local, succ)
891             }
892             hir::DeclItem(_) => succ,
893         }
894     }
895
896     fn propagate_through_local(&mut self, local: &hir::Local, succ: LiveNode)
897                                -> LiveNode {
898         // Note: we mark the variable as defined regardless of whether
899         // there is an initializer.  Initially I had thought to only mark
900         // the live variable as defined if it was initialized, and then we
901         // could check for uninit variables just by scanning what is live
902         // at the start of the function. But that doesn't work so well for
903         // immutable variables defined in a loop:
904         //     loop { let x; x = 5; }
905         // because the "assignment" loops back around and generates an error.
906         //
907         // So now we just check that variables defined w/o an
908         // initializer are not live at the point of their
909         // initialization, which is mildly more complex than checking
910         // once at the func header but otherwise equivalent.
911
912         let succ = self.propagate_through_opt_expr(local.init.as_ref().map(|e| &**e), succ);
913         self.define_bindings_in_pat(&*local.pat, succ)
914     }
915
916     fn propagate_through_exprs(&mut self, exprs: &[P<Expr>], succ: LiveNode)
917                                -> LiveNode {
918         exprs.iter().rev().fold(succ, |succ, expr| {
919             self.propagate_through_expr(&**expr, succ)
920         })
921     }
922
923     fn propagate_through_opt_expr(&mut self,
924                                   opt_expr: Option<&Expr>,
925                                   succ: LiveNode)
926                                   -> LiveNode {
927         opt_expr.map_or(succ, |expr| self.propagate_through_expr(expr, succ))
928     }
929
930     fn propagate_through_expr(&mut self, expr: &Expr, succ: LiveNode)
931                               -> LiveNode {
932         debug!("propagate_through_expr: {}", expr_to_string(expr));
933
934         match expr.node {
935           // Interesting cases with control flow or which gen/kill
936
937           hir::ExprPath(..) => {
938               self.access_path(expr, succ, ACC_READ | ACC_USE)
939           }
940
941           hir::ExprField(ref e, _) => {
942               self.propagate_through_expr(&**e, succ)
943           }
944
945           hir::ExprTupField(ref e, _) => {
946               self.propagate_through_expr(&**e, succ)
947           }
948
949           hir::ExprClosure(_, _, ref blk) => {
950               debug!("{} is an ExprClosure",
951                      expr_to_string(expr));
952
953               /*
954               The next-node for a break is the successor of the entire
955               loop. The next-node for a continue is the top of this loop.
956               */
957               let node = self.live_node(expr.id, expr.span);
958               self.with_loop_nodes(blk.id, succ, node, |this| {
959
960                  // the construction of a closure itself is not important,
961                  // but we have to consider the closed over variables.
962                  let caps = match this.ir.capture_info_map.get(&expr.id) {
963                     Some(caps) => caps.clone(),
964                     None => {
965                         this.ir.tcx.sess.span_bug(expr.span, "no registered caps");
966                      }
967                  };
968                  caps.iter().rev().fold(succ, |succ, cap| {
969                      this.init_from_succ(cap.ln, succ);
970                      let var = this.variable(cap.var_nid, expr.span);
971                      this.acc(cap.ln, var, ACC_READ | ACC_USE);
972                      cap.ln
973                  })
974               })
975           }
976
977           hir::ExprIf(ref cond, ref then, ref els) => {
978             //
979             //     (cond)
980             //       |
981             //       v
982             //     (expr)
983             //     /   \
984             //    |     |
985             //    v     v
986             //  (then)(els)
987             //    |     |
988             //    v     v
989             //   (  succ  )
990             //
991             let else_ln = self.propagate_through_opt_expr(els.as_ref().map(|e| &**e), succ);
992             let then_ln = self.propagate_through_block(&**then, succ);
993             let ln = self.live_node(expr.id, expr.span);
994             self.init_from_succ(ln, else_ln);
995             self.merge_from_succ(ln, then_ln, false);
996             self.propagate_through_expr(&**cond, ln)
997           }
998
999           hir::ExprWhile(ref cond, ref blk, _) => {
1000             self.propagate_through_loop(expr, WhileLoop(&**cond), &**blk, succ)
1001           }
1002
1003           // Note that labels have been resolved, so we don't need to look
1004           // at the label ident
1005           hir::ExprLoop(ref blk, _) => {
1006             self.propagate_through_loop(expr, LoopLoop, &**blk, succ)
1007           }
1008
1009           hir::ExprMatch(ref e, ref arms, _) => {
1010             //
1011             //      (e)
1012             //       |
1013             //       v
1014             //     (expr)
1015             //     / | \
1016             //    |  |  |
1017             //    v  v  v
1018             //   (..arms..)
1019             //    |  |  |
1020             //    v  v  v
1021             //   (  succ  )
1022             //
1023             //
1024             let ln = self.live_node(expr.id, expr.span);
1025             self.init_empty(ln, succ);
1026             let mut first_merge = true;
1027             for arm in arms {
1028                 let body_succ =
1029                     self.propagate_through_expr(&*arm.body, succ);
1030                 let guard_succ =
1031                     self.propagate_through_opt_expr(arm.guard.as_ref().map(|e| &**e), body_succ);
1032                 // only consider the first pattern; any later patterns must have
1033                 // the same bindings, and we also consider the first pattern to be
1034                 // the "authoritative" set of ids
1035                 let arm_succ =
1036                     self.define_bindings_in_arm_pats(arm.pats.first().map(|p| &**p),
1037                                                      guard_succ);
1038                 self.merge_from_succ(ln, arm_succ, first_merge);
1039                 first_merge = false;
1040             };
1041             self.propagate_through_expr(&**e, ln)
1042           }
1043
1044           hir::ExprRet(ref o_e) => {
1045             // ignore succ and subst exit_ln:
1046             let exit_ln = self.s.exit_ln;
1047             self.propagate_through_opt_expr(o_e.as_ref().map(|e| &**e), exit_ln)
1048           }
1049
1050           hir::ExprBreak(opt_label) => {
1051               // Find which label this break jumps to
1052               let sc = self.find_loop_scope(opt_label.map(|l| l.node.name), expr.id, expr.span);
1053
1054               // Now that we know the label we're going to,
1055               // look it up in the break loop nodes table
1056
1057               match self.break_ln.get(&sc) {
1058                   Some(&b) => b,
1059                   None => self.ir.tcx.sess.span_bug(expr.span,
1060                                                     "break to unknown label")
1061               }
1062           }
1063
1064           hir::ExprAgain(opt_label) => {
1065               // Find which label this expr continues to
1066               let sc = self.find_loop_scope(opt_label.map(|l| l.node.name), expr.id, expr.span);
1067
1068               // Now that we know the label we're going to,
1069               // look it up in the continue loop nodes table
1070
1071               match self.cont_ln.get(&sc) {
1072                   Some(&b) => b,
1073                   None => self.ir.tcx.sess.span_bug(expr.span,
1074                                                     "loop to unknown label")
1075               }
1076           }
1077
1078           hir::ExprAssign(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);
1082             let succ = self.propagate_through_lvalue_components(&**l, succ);
1083             self.propagate_through_expr(&**r, succ)
1084           }
1085
1086           hir::ExprAssignOp(_, ref l, ref r) => {
1087             // see comment on lvalues in
1088             // propagate_through_lvalue_components()
1089             let succ = self.write_lvalue(&**l, succ, ACC_WRITE|ACC_READ);
1090             let succ = self.propagate_through_expr(&**r, succ);
1091             self.propagate_through_lvalue_components(&**l, succ)
1092           }
1093
1094           // Uninteresting cases: just propagate in rev exec order
1095
1096           hir::ExprVec(ref exprs) => {
1097             self.propagate_through_exprs(&exprs[..], succ)
1098           }
1099
1100           hir::ExprRepeat(ref element, ref count) => {
1101             let succ = self.propagate_through_expr(&**count, succ);
1102             self.propagate_through_expr(&**element, succ)
1103           }
1104
1105           hir::ExprStruct(_, ref fields, ref with_expr) => {
1106             let succ = self.propagate_through_opt_expr(with_expr.as_ref().map(|e| &**e), succ);
1107             fields.iter().rev().fold(succ, |succ, field| {
1108                 self.propagate_through_expr(&*field.expr, succ)
1109             })
1110           }
1111
1112           hir::ExprCall(ref f, ref args) => {
1113             let diverges = !self.ir.tcx.is_method_call(expr.id) &&
1114                 self.ir.tcx.expr_ty_adjusted(&**f).fn_ret().diverges();
1115             let succ = if diverges {
1116                 self.s.exit_ln
1117             } else {
1118                 succ
1119             };
1120             let succ = self.propagate_through_exprs(&args[..], succ);
1121             self.propagate_through_expr(&**f, succ)
1122           }
1123
1124           hir::ExprMethodCall(_, _, ref args) => {
1125             let method_call = ty::MethodCall::expr(expr.id);
1126             let method_ty = self.ir.tcx.tables.borrow().method_map[&method_call].ty;
1127             let succ = if method_ty.fn_ret().diverges() {
1128                 self.s.exit_ln
1129             } else {
1130                 succ
1131             };
1132             self.propagate_through_exprs(&args[..], succ)
1133           }
1134
1135           hir::ExprTup(ref exprs) => {
1136             self.propagate_through_exprs(&exprs[..], succ)
1137           }
1138
1139           hir::ExprBinary(op, ref l, ref r) if ::rustc_front::util::lazy_binop(op.node) => {
1140             let r_succ = self.propagate_through_expr(&**r, succ);
1141
1142             let ln = self.live_node(expr.id, expr.span);
1143             self.init_from_succ(ln, succ);
1144             self.merge_from_succ(ln, r_succ, false);
1145
1146             self.propagate_through_expr(&**l, ln)
1147           }
1148
1149           hir::ExprIndex(ref l, ref r) |
1150           hir::ExprBinary(_, ref l, ref r) => {
1151             let r_succ = self.propagate_through_expr(&**r, succ);
1152             self.propagate_through_expr(&**l, r_succ)
1153           }
1154
1155           hir::ExprRange(ref e1, ref e2) => {
1156             let succ = e2.as_ref().map_or(succ, |e| self.propagate_through_expr(&**e, succ));
1157             e1.as_ref().map_or(succ, |e| self.propagate_through_expr(&**e, succ))
1158           }
1159
1160           hir::ExprBox(ref e) |
1161           hir::ExprAddrOf(_, ref e) |
1162           hir::ExprCast(ref e, _) |
1163           hir::ExprType(ref e, _) |
1164           hir::ExprUnary(_, ref e) => {
1165             self.propagate_through_expr(&**e, succ)
1166           }
1167
1168           hir::ExprInlineAsm(ref ia) => {
1169
1170             let succ = ia.outputs.iter().rev().fold(succ,
1171                 |succ, out| {
1172                     // see comment on lvalues
1173                     // in propagate_through_lvalue_components()
1174                     if out.is_indirect {
1175                         self.propagate_through_expr(&*out.expr, succ)
1176                     } else {
1177                         let acc = if out.is_rw { ACC_WRITE|ACC_READ } else { ACC_WRITE };
1178                         let succ = self.write_lvalue(&*out.expr, succ, acc);
1179                         self.propagate_through_lvalue_components(&*out.expr, succ)
1180                     }
1181                 }
1182             );
1183             // Inputs are executed first. Propagate last because of rev order
1184             ia.inputs.iter().rev().fold(succ, |succ, &(_, ref expr)| {
1185                 self.propagate_through_expr(&**expr, succ)
1186             })
1187           }
1188
1189           hir::ExprLit(..) => {
1190             succ
1191           }
1192
1193           hir::ExprBlock(ref blk) => {
1194             self.propagate_through_block(&**blk, succ)
1195           }
1196         }
1197     }
1198
1199     fn propagate_through_lvalue_components(&mut self,
1200                                            expr: &Expr,
1201                                            succ: LiveNode)
1202                                            -> LiveNode {
1203         // # Lvalues
1204         //
1205         // In general, the full flow graph structure for an
1206         // assignment/move/etc can be handled in one of two ways,
1207         // depending on whether what is being assigned is a "tracked
1208         // value" or not. A tracked value is basically a local
1209         // variable or argument.
1210         //
1211         // The two kinds of graphs are:
1212         //
1213         //    Tracked lvalue          Untracked lvalue
1214         // ----------------------++-----------------------
1215         //                       ||
1216         //         |             ||           |
1217         //         v             ||           v
1218         //     (rvalue)          ||       (rvalue)
1219         //         |             ||           |
1220         //         v             ||           v
1221         // (write of lvalue)     ||   (lvalue components)
1222         //         |             ||           |
1223         //         v             ||           v
1224         //      (succ)           ||        (succ)
1225         //                       ||
1226         // ----------------------++-----------------------
1227         //
1228         // I will cover the two cases in turn:
1229         //
1230         // # Tracked lvalues
1231         //
1232         // A tracked lvalue is a local variable/argument `x`.  In
1233         // these cases, the link_node where the write occurs is linked
1234         // to node id of `x`.  The `write_lvalue()` routine generates
1235         // the contents of this node.  There are no subcomponents to
1236         // consider.
1237         //
1238         // # Non-tracked lvalues
1239         //
1240         // These are lvalues like `x[5]` or `x.f`.  In that case, we
1241         // basically ignore the value which is written to but generate
1242         // reads for the components---`x` in these two examples.  The
1243         // components reads are generated by
1244         // `propagate_through_lvalue_components()` (this fn).
1245         //
1246         // # Illegal lvalues
1247         //
1248         // It is still possible to observe assignments to non-lvalues;
1249         // these errors are detected in the later pass borrowck.  We
1250         // just ignore such cases and treat them as reads.
1251
1252         match expr.node {
1253             hir::ExprPath(..) => succ,
1254             hir::ExprField(ref e, _) => self.propagate_through_expr(&**e, succ),
1255             hir::ExprTupField(ref e, _) => self.propagate_through_expr(&**e, succ),
1256             _ => self.propagate_through_expr(expr, succ)
1257         }
1258     }
1259
1260     // see comment on propagate_through_lvalue()
1261     fn write_lvalue(&mut self, expr: &Expr, succ: LiveNode, acc: u32)
1262                     -> LiveNode {
1263         match expr.node {
1264           hir::ExprPath(..) => {
1265               self.access_path(expr, succ, acc)
1266           }
1267
1268           // We do not track other lvalues, so just propagate through
1269           // to their subcomponents.  Also, it may happen that
1270           // non-lvalues occur here, because those are detected in the
1271           // later pass borrowck.
1272           _ => succ
1273         }
1274     }
1275
1276     fn access_path(&mut self, expr: &Expr, succ: LiveNode, acc: u32)
1277                    -> LiveNode {
1278         match self.ir.tcx.def_map.borrow().get(&expr.id).unwrap().full_def() {
1279           DefLocal(_, nid) => {
1280             let ln = self.live_node(expr.id, expr.span);
1281             if acc != 0 {
1282                 self.init_from_succ(ln, succ);
1283                 let var = self.variable(nid, expr.span);
1284                 self.acc(ln, var, acc);
1285             }
1286             ln
1287           }
1288           _ => succ
1289         }
1290     }
1291
1292     fn propagate_through_loop(&mut self,
1293                               expr: &Expr,
1294                               kind: LoopKind,
1295                               body: &hir::Block,
1296                               succ: LiveNode)
1297                               -> LiveNode {
1298
1299         /*
1300
1301         We model control flow like this:
1302
1303               (cond) <--+
1304                 |       |
1305                 v       |
1306           +-- (expr)    |
1307           |     |       |
1308           |     v       |
1309           |   (body) ---+
1310           |
1311           |
1312           v
1313         (succ)
1314
1315         */
1316
1317
1318         // first iteration:
1319         let mut first_merge = true;
1320         let ln = self.live_node(expr.id, expr.span);
1321         self.init_empty(ln, succ);
1322         match kind {
1323             LoopLoop => {}
1324             _ => {
1325                 // If this is not a `loop` loop, then it's possible we bypass
1326                 // the body altogether. Otherwise, the only way is via a `break`
1327                 // in the loop body.
1328                 self.merge_from_succ(ln, succ, first_merge);
1329                 first_merge = false;
1330             }
1331         }
1332         debug!("propagate_through_loop: using id for loop body {} {}",
1333                expr.id, block_to_string(body));
1334
1335         let cond_ln = match kind {
1336             LoopLoop => ln,
1337             WhileLoop(ref cond) => self.propagate_through_expr(&**cond, ln),
1338         };
1339         let body_ln = self.with_loop_nodes(expr.id, succ, ln, |this| {
1340             this.propagate_through_block(body, cond_ln)
1341         });
1342
1343         // repeat until fixed point is reached:
1344         while self.merge_from_succ(ln, body_ln, first_merge) {
1345             first_merge = false;
1346
1347             let new_cond_ln = match kind {
1348                 LoopLoop => ln,
1349                 WhileLoop(ref cond) => {
1350                     self.propagate_through_expr(&**cond, ln)
1351                 }
1352             };
1353             assert!(cond_ln == new_cond_ln);
1354             assert!(body_ln == self.with_loop_nodes(expr.id, succ, ln,
1355             |this| this.propagate_through_block(body, cond_ln)));
1356         }
1357
1358         cond_ln
1359     }
1360
1361     fn with_loop_nodes<R, F>(&mut self,
1362                              loop_node_id: NodeId,
1363                              break_ln: LiveNode,
1364                              cont_ln: LiveNode,
1365                              f: F)
1366                              -> R where
1367         F: FnOnce(&mut Liveness<'a, 'tcx>) -> R,
1368     {
1369         debug!("with_loop_nodes: {} {}", loop_node_id, break_ln.get());
1370         self.loop_scope.push(loop_node_id);
1371         self.break_ln.insert(loop_node_id, break_ln);
1372         self.cont_ln.insert(loop_node_id, cont_ln);
1373         let r = f(self);
1374         self.loop_scope.pop();
1375         r
1376     }
1377 }
1378
1379 // _______________________________________________________________________
1380 // Checking for error conditions
1381
1382 fn check_local(this: &mut Liveness, local: &hir::Local) {
1383     match local.init {
1384         Some(_) => {
1385             this.warn_about_unused_or_dead_vars_in_pat(&*local.pat);
1386         },
1387         None => {
1388             this.pat_bindings(&*local.pat, |this, ln, var, sp, id| {
1389                 this.warn_about_unused(sp, id, ln, var);
1390             })
1391         }
1392     }
1393
1394     intravisit::walk_local(this, local);
1395 }
1396
1397 fn check_arm(this: &mut Liveness, arm: &hir::Arm) {
1398     // only consider the first pattern; any later patterns must have
1399     // the same bindings, and we also consider the first pattern to be
1400     // the "authoritative" set of ids
1401     this.arm_pats_bindings(arm.pats.first().map(|p| &**p), |this, ln, var, sp, id| {
1402         this.warn_about_unused(sp, id, ln, var);
1403     });
1404     intravisit::walk_arm(this, arm);
1405 }
1406
1407 fn check_expr(this: &mut Liveness, expr: &Expr) {
1408     match expr.node {
1409       hir::ExprAssign(ref l, _) => {
1410         this.check_lvalue(&**l);
1411
1412         intravisit::walk_expr(this, expr);
1413       }
1414
1415       hir::ExprAssignOp(_, ref l, _) => {
1416         this.check_lvalue(&**l);
1417
1418         intravisit::walk_expr(this, expr);
1419       }
1420
1421       hir::ExprInlineAsm(ref ia) => {
1422         for &(_, ref input) in &ia.inputs {
1423           this.visit_expr(&**input);
1424         }
1425
1426         // Output operands must be lvalues
1427         for out in &ia.outputs {
1428           if !out.is_indirect {
1429             this.check_lvalue(&*out.expr);
1430           }
1431           this.visit_expr(&*out.expr);
1432         }
1433
1434         intravisit::walk_expr(this, expr);
1435       }
1436
1437       // no correctness conditions related to liveness
1438       hir::ExprCall(..) | hir::ExprMethodCall(..) | hir::ExprIf(..) |
1439       hir::ExprMatch(..) | hir::ExprWhile(..) | hir::ExprLoop(..) |
1440       hir::ExprIndex(..) | hir::ExprField(..) | hir::ExprTupField(..) |
1441       hir::ExprVec(..) | hir::ExprTup(..) | hir::ExprBinary(..) |
1442       hir::ExprCast(..) | hir::ExprUnary(..) | hir::ExprRet(..) |
1443       hir::ExprBreak(..) | hir::ExprAgain(..) | hir::ExprLit(_) |
1444       hir::ExprBlock(..) | hir::ExprAddrOf(..) |
1445       hir::ExprStruct(..) | hir::ExprRepeat(..) |
1446       hir::ExprClosure(..) | hir::ExprPath(..) | hir::ExprBox(..) |
1447       hir::ExprRange(..) | hir::ExprType(..) => {
1448         intravisit::walk_expr(this, expr);
1449       }
1450     }
1451 }
1452
1453 fn check_fn(_v: &Liveness,
1454             _fk: FnKind,
1455             _decl: &hir::FnDecl,
1456             _body: &hir::Block,
1457             _sp: Span,
1458             _id: NodeId) {
1459     // do not check contents of nested fns
1460 }
1461
1462 impl<'a, 'tcx> Liveness<'a, 'tcx> {
1463     fn fn_ret(&self, id: NodeId) -> ty::PolyFnOutput<'tcx> {
1464         let fn_ty = self.ir.tcx.node_id_to_type(id);
1465         match fn_ty.sty {
1466             ty::TyClosure(closure_def_id, ref substs) =>
1467                 self.ir.tcx.closure_type(closure_def_id, substs).sig.output(),
1468             _ => fn_ty.fn_ret()
1469         }
1470     }
1471
1472     fn check_ret(&self,
1473                  id: NodeId,
1474                  sp: Span,
1475                  _fk: FnKind,
1476                  entry_ln: LiveNode,
1477                  body: &hir::Block)
1478     {
1479         // within the fn body, late-bound regions are liberated
1480         // and must outlive the *call-site* of the function.
1481         let fn_ret =
1482             self.ir.tcx.liberate_late_bound_regions(
1483                 self.ir.tcx.region_maps.call_site_extent(id, body.id),
1484                 &self.fn_ret(id));
1485
1486         match fn_ret {
1487             ty::FnConverging(t_ret)
1488                 if self.live_on_entry(entry_ln, self.s.no_ret_var).is_some() => {
1489
1490                 if t_ret.is_nil() {
1491                     // for nil return types, it is ok to not return a value expl.
1492                 } else {
1493                     let ends_with_stmt = match body.expr {
1494                         None if !body.stmts.is_empty() =>
1495                             match body.stmts.first().unwrap().node {
1496                                 hir::StmtSemi(ref e, _) => {
1497                                     self.ir.tcx.expr_ty(&**e) == t_ret
1498                                 },
1499                                 _ => false
1500                             },
1501                         _ => false
1502                     };
1503                     let mut err = struct_span_err!(self.ir.tcx.sess,
1504                                                    sp,
1505                                                    E0269,
1506                                                    "not all control paths return a value");
1507                     if ends_with_stmt {
1508                         let last_stmt = body.stmts.first().unwrap();
1509                         let original_span = original_sp(self.ir.tcx.sess.codemap(),
1510                                                         last_stmt.span, sp);
1511                         let span_semicolon = Span {
1512                             lo: original_span.hi - BytePos(1),
1513                             hi: original_span.hi,
1514                             expn_id: original_span.expn_id
1515                         };
1516                         err.span_help(span_semicolon, "consider removing this semicolon:");
1517                     }
1518                     err.emit();
1519                 }
1520             }
1521             ty::FnDiverging
1522                 if self.live_on_entry(entry_ln, self.s.clean_exit_var).is_some() => {
1523                     span_err!(self.ir.tcx.sess, sp, E0270,
1524                         "computation may converge in a function marked as diverging");
1525                 }
1526
1527             _ => {}
1528         }
1529     }
1530
1531     fn check_lvalue(&mut self, expr: &Expr) {
1532         match expr.node {
1533             hir::ExprPath(..) => {
1534                 if let DefLocal(_, nid) = self.ir.tcx.def_map.borrow().get(&expr.id)
1535                                                                       .unwrap()
1536                                                                       .full_def() {
1537                     // Assignment to an immutable variable or argument: only legal
1538                     // if there is no later assignment. If this local is actually
1539                     // mutable, then check for a reassignment to flag the mutability
1540                     // as being used.
1541                     let ln = self.live_node(expr.id, expr.span);
1542                     let var = self.variable(nid, expr.span);
1543                     self.warn_about_dead_assign(expr.span, expr.id, ln, var);
1544                 }
1545             }
1546             _ => {
1547                 // For other kinds of lvalues, no checks are required,
1548                 // and any embedded expressions are actually rvalues
1549                 intravisit::walk_expr(self, expr);
1550             }
1551         }
1552     }
1553
1554     fn should_warn(&self, var: Variable) -> Option<String> {
1555         let name = self.ir.variable_name(var);
1556         if name.is_empty() || name.as_bytes()[0] == ('_' as u8) {
1557             None
1558         } else {
1559             Some(name)
1560         }
1561     }
1562
1563     fn warn_about_unused_args(&self, decl: &hir::FnDecl, entry_ln: LiveNode) {
1564         for arg in &decl.inputs {
1565             pat_util::pat_bindings(&self.ir.tcx.def_map,
1566                                    &*arg.pat,
1567                                    |_bm, p_id, sp, path1| {
1568                 let var = self.variable(p_id, sp);
1569                 // Ignore unused self.
1570                 let name = path1.node;
1571                 if name != special_idents::self_.name {
1572                     if !self.warn_about_unused(sp, p_id, entry_ln, var) {
1573                         if self.live_on_entry(entry_ln, var).is_none() {
1574                             self.report_dead_assign(p_id, sp, var, true);
1575                         }
1576                     }
1577                 }
1578             })
1579         }
1580     }
1581
1582     fn warn_about_unused_or_dead_vars_in_pat(&mut self, pat: &hir::Pat) {
1583         self.pat_bindings(pat, |this, ln, var, sp, id| {
1584             if !this.warn_about_unused(sp, id, ln, var) {
1585                 this.warn_about_dead_assign(sp, id, ln, var);
1586             }
1587         })
1588     }
1589
1590     fn warn_about_unused(&self,
1591                          sp: Span,
1592                          id: NodeId,
1593                          ln: LiveNode,
1594                          var: Variable)
1595                          -> bool {
1596         if !self.used_on_entry(ln, var) {
1597             let r = self.should_warn(var);
1598             if let Some(name) = r {
1599
1600                 // annoying: for parameters in funcs like `fn(x: i32)
1601                 // {ret}`, there is only one node, so asking about
1602                 // assigned_on_exit() is not meaningful.
1603                 let is_assigned = if ln == self.s.exit_ln {
1604                     false
1605                 } else {
1606                     self.assigned_on_exit(ln, var).is_some()
1607                 };
1608
1609                 if is_assigned {
1610                     self.ir.tcx.sess.add_lint(lint::builtin::UNUSED_VARIABLES, id, sp,
1611                         format!("variable `{}` is assigned to, but never used",
1612                                 name));
1613                 } else if name != "self" {
1614                     self.ir.tcx.sess.add_lint(lint::builtin::UNUSED_VARIABLES, id, sp,
1615                         format!("unused variable: `{}`", name));
1616                 }
1617             }
1618             true
1619         } else {
1620             false
1621         }
1622     }
1623
1624     fn warn_about_dead_assign(&self,
1625                               sp: Span,
1626                               id: NodeId,
1627                               ln: LiveNode,
1628                               var: Variable) {
1629         if self.live_on_exit(ln, var).is_none() {
1630             self.report_dead_assign(id, sp, var, false);
1631         }
1632     }
1633
1634     fn report_dead_assign(&self, id: NodeId, sp: Span, var: Variable, is_argument: bool) {
1635         if let Some(name) = self.should_warn(var) {
1636             if is_argument {
1637                 self.ir.tcx.sess.add_lint(lint::builtin::UNUSED_ASSIGNMENTS, id, sp,
1638                     format!("value passed to `{}` is never read", name));
1639             } else {
1640                 self.ir.tcx.sess.add_lint(lint::builtin::UNUSED_ASSIGNMENTS, id, sp,
1641                     format!("value assigned to `{}` is never read", name));
1642             }
1643         }
1644     }
1645 }