]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/dataflow.rs
e81e6b0f96d2d0c6a8e89de12c823621778e9a15
[rust.git] / src / librustc / middle / dataflow.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
12 /*!
13  * A module for propagating forward dataflow information. The analysis
14  * assumes that the items to be propagated can be represented as bits
15  * and thus uses bitvectors. Your job is simply to specify the so-called
16  * GEN and KILL bits for each expression.
17  */
18
19
20 use std::io;
21 use std::uint;
22 use std::vec;
23 use collections::HashMap;
24 use syntax::ast;
25 use syntax::ast_util;
26 use syntax::ast_util::IdRange;
27 use syntax::print::{pp, pprust};
28 use middle::ty;
29 use middle::typeck;
30 use util::ppaux::Repr;
31
32 #[deriving(Clone)]
33 pub struct DataFlowContext<O> {
34     priv tcx: ty::ctxt,
35     priv method_map: typeck::MethodMap,
36
37     /// the data flow operator
38     priv oper: O,
39
40     /// number of bits to propagate per id
41     priv bits_per_id: uint,
42
43     /// number of words we will use to store bits_per_id.
44     /// equal to bits_per_id/uint::BITS rounded up.
45     priv words_per_id: uint,
46
47     // mapping from node to bitset index.
48     priv nodeid_to_bitset: HashMap<ast::NodeId,uint>,
49
50     // Bit sets per id.  The following three fields (`gens`, `kills`,
51     // and `on_entry`) all have the same structure. For each id in
52     // `id_range`, there is a range of words equal to `words_per_id`.
53     // So, to access the bits for any given id, you take a slice of
54     // the full vector (see the method `compute_id_range()`).
55
56     /// bits generated as we exit the scope `id`. Updated by `add_gen()`.
57     priv gens: ~[uint],
58
59     /// bits killed as we exit the scope `id`. Updated by `add_kill()`.
60     priv kills: ~[uint],
61
62     /// bits that are valid on entry to the scope `id`. Updated by
63     /// `propagate()`.
64     priv on_entry: ~[uint]
65 }
66
67 /// Parameterization for the precise form of data flow that is used.
68 pub trait DataFlowOperator {
69     /// Specifies the initial value for each bit in the `on_entry` set
70     fn initial_value(&self) -> bool;
71
72     /// Joins two predecessor bits together, typically either `|` or `&`
73     fn join(&self, succ: uint, pred: uint) -> uint;
74 }
75
76 struct PropagationContext<'a, O> {
77     dfcx: &'a mut DataFlowContext<O>,
78     changed: bool
79 }
80
81 struct LoopScope<'a> {
82     loop_id: ast::NodeId,
83     break_bits: ~[uint]
84 }
85
86 impl<O:DataFlowOperator> pprust::PpAnn for DataFlowContext<O> {
87     fn pre(&self, node: pprust::AnnNode) -> io::IoResult<()> {
88         let (ps, id) = match node {
89             pprust::NodeExpr(ps, expr) => (ps, expr.id),
90             pprust::NodeBlock(ps, blk) => (ps, blk.id),
91             pprust::NodeItem(ps, _) => (ps, 0),
92             pprust::NodePat(ps, pat) => (ps, pat.id)
93         };
94
95         if self.nodeid_to_bitset.contains_key(&id) {
96             let (start, end) = self.compute_id_range_frozen(id);
97             let on_entry = self.on_entry.slice(start, end);
98             let entry_str = bits_to_str(on_entry);
99
100             let gens = self.gens.slice(start, end);
101             let gens_str = if gens.iter().any(|&u| u != 0) {
102                 format!(" gen: {}", bits_to_str(gens))
103             } else {
104                 ~""
105             };
106
107             let kills = self.kills.slice(start, end);
108             let kills_str = if kills.iter().any(|&u| u != 0) {
109                 format!(" kill: {}", bits_to_str(kills))
110             } else {
111                 ~""
112             };
113
114             let comment_str = format!("id {}: {}{}{}",
115                                       id, entry_str, gens_str, kills_str);
116             try!(pprust::synth_comment(ps, comment_str));
117             try!(pp::space(&mut ps.s));
118         }
119         Ok(())
120     }
121 }
122
123 impl<O:DataFlowOperator> DataFlowContext<O> {
124     pub fn new(tcx: ty::ctxt,
125                method_map: typeck::MethodMap,
126                oper: O,
127                id_range: IdRange,
128                bits_per_id: uint) -> DataFlowContext<O> {
129         let words_per_id = (bits_per_id + uint::BITS - 1) / uint::BITS;
130
131         debug!("DataFlowContext::new(id_range={:?}, bits_per_id={:?}, words_per_id={:?})",
132                id_range, bits_per_id, words_per_id);
133
134         let gens = ~[];
135         let kills = ~[];
136         let on_entry = ~[];
137
138         DataFlowContext {
139             tcx: tcx,
140             method_map: method_map,
141             words_per_id: words_per_id,
142             nodeid_to_bitset: HashMap::new(),
143             bits_per_id: bits_per_id,
144             oper: oper,
145             gens: gens,
146             kills: kills,
147             on_entry: on_entry
148         }
149     }
150
151     pub fn add_gen(&mut self, id: ast::NodeId, bit: uint) {
152         //! Indicates that `id` generates `bit`
153
154         debug!("add_gen(id={:?}, bit={:?})", id, bit);
155         let (start, end) = self.compute_id_range(id);
156         {
157             let gens = self.gens.mut_slice(start, end);
158             set_bit(gens, bit);
159         }
160     }
161
162     pub fn add_kill(&mut self, id: ast::NodeId, bit: uint) {
163         //! Indicates that `id` kills `bit`
164
165         debug!("add_kill(id={:?}, bit={:?})", id, bit);
166         let (start, end) = self.compute_id_range(id);
167         {
168             let kills = self.kills.mut_slice(start, end);
169             set_bit(kills, bit);
170         }
171     }
172
173     fn apply_gen_kill(&mut self, id: ast::NodeId, bits: &mut [uint]) {
174         //! Applies the gen and kill sets for `id` to `bits`
175
176         debug!("apply_gen_kill(id={:?}, bits={}) [before]",
177                id, mut_bits_to_str(bits));
178         let (start, end) = self.compute_id_range(id);
179         let gens = self.gens.slice(start, end);
180         bitwise(bits, gens, |a, b| a | b);
181         let kills = self.kills.slice(start, end);
182         bitwise(bits, kills, |a, b| a & !b);
183
184         debug!("apply_gen_kill(id={:?}, bits={}) [after]",
185                id, mut_bits_to_str(bits));
186     }
187
188     fn apply_kill(&mut self, id: ast::NodeId, bits: &mut [uint]) {
189         debug!("apply_kill(id={:?}, bits={}) [before]",
190                id, mut_bits_to_str(bits));
191         let (start, end) = self.compute_id_range(id);
192         let kills = self.kills.slice(start, end);
193         bitwise(bits, kills, |a, b| a & !b);
194         debug!("apply_kill(id={:?}, bits={}) [after]",
195                id, mut_bits_to_str(bits));
196     }
197
198     fn compute_id_range_frozen(&self, id: ast::NodeId) -> (uint, uint) {
199         let n = *self.nodeid_to_bitset.get(&id);
200         let start = n * self.words_per_id;
201         let end = start + self.words_per_id;
202         (start, end)
203     }
204
205     fn compute_id_range(&mut self, id: ast::NodeId) -> (uint, uint) {
206         let mut expanded = false;
207         let len = self.nodeid_to_bitset.len();
208         let n = self.nodeid_to_bitset.find_or_insert_with(id, |_| {
209             expanded = true;
210             len
211         });
212         if expanded {
213             let entry = if self.oper.initial_value() { uint::MAX } else {0};
214             for _ in range(0, self.words_per_id) {
215                 self.gens.push(0);
216                 self.kills.push(0);
217                 self.on_entry.push(entry);
218             }
219         }
220         let start = *n * self.words_per_id;
221         let end = start + self.words_per_id;
222
223         assert!(start < self.gens.len());
224         assert!(end <= self.gens.len());
225         assert!(self.gens.len() == self.kills.len());
226         assert!(self.gens.len() == self.on_entry.len());
227
228         (start, end)
229     }
230
231
232     pub fn each_bit_on_entry_frozen(&self,
233                                     id: ast::NodeId,
234                                     f: |uint| -> bool)
235                                     -> bool {
236         //! Iterates through each bit that is set on entry to `id`.
237         //! Only useful after `propagate()` has been called.
238         if !self.nodeid_to_bitset.contains_key(&id) {
239             return true;
240         }
241         let (start, end) = self.compute_id_range_frozen(id);
242         let on_entry = self.on_entry.slice(start, end);
243         debug!("each_bit_on_entry_frozen(id={:?}, on_entry={})",
244                id, bits_to_str(on_entry));
245         self.each_bit(on_entry, f)
246     }
247
248     pub fn each_bit_on_entry(&mut self,
249                              id: ast::NodeId,
250                              f: |uint| -> bool)
251                              -> bool {
252         //! Iterates through each bit that is set on entry to `id`.
253         //! Only useful after `propagate()` has been called.
254
255         let (start, end) = self.compute_id_range(id);
256         let on_entry = self.on_entry.slice(start, end);
257         debug!("each_bit_on_entry(id={:?}, on_entry={})",
258                id, bits_to_str(on_entry));
259         self.each_bit(on_entry, f)
260     }
261
262     pub fn each_gen_bit(&mut self, id: ast::NodeId, f: |uint| -> bool)
263                         -> bool {
264         //! Iterates through each bit in the gen set for `id`.
265
266         let (start, end) = self.compute_id_range(id);
267         let gens = self.gens.slice(start, end);
268         debug!("each_gen_bit(id={:?}, gens={})",
269                id, bits_to_str(gens));
270         self.each_bit(gens, f)
271     }
272
273     pub fn each_gen_bit_frozen(&self, id: ast::NodeId, f: |uint| -> bool)
274                                -> bool {
275         //! Iterates through each bit in the gen set for `id`.
276         if !self.nodeid_to_bitset.contains_key(&id) {
277             return true;
278         }
279         let (start, end) = self.compute_id_range_frozen(id);
280         let gens = self.gens.slice(start, end);
281         debug!("each_gen_bit(id={:?}, gens={})",
282                id, bits_to_str(gens));
283         self.each_bit(gens, f)
284     }
285
286     fn each_bit(&self, words: &[uint], f: |uint| -> bool) -> bool {
287         //! Helper for iterating over the bits in a bit set.
288
289         for (word_index, &word) in words.iter().enumerate() {
290             if word != 0 {
291                 let base_index = word_index * uint::BITS;
292                 for offset in range(0u, uint::BITS) {
293                     let bit = 1 << offset;
294                     if (word & bit) != 0 {
295                         // NB: we round up the total number of bits
296                         // that we store in any given bit set so that
297                         // it is an even multiple of uint::BITS.  This
298                         // means that there may be some stray bits at
299                         // the end that do not correspond to any
300                         // actual value.  So before we callback, check
301                         // whether the bit_index is greater than the
302                         // actual value the user specified and stop
303                         // iterating if so.
304                         let bit_index = base_index + offset;
305                         if bit_index >= self.bits_per_id {
306                             return true;
307                         } else if !f(bit_index) {
308                             return false;
309                         }
310                     }
311                 }
312             }
313         }
314         return true;
315     }
316 }
317
318 impl<O:DataFlowOperator+Clone+'static> DataFlowContext<O> {
319 //                      ^^^^^^^^^^^^^ only needed for pretty printing
320     pub fn propagate(&mut self, blk: &ast::Block) {
321         //! Performs the data flow analysis.
322
323         if self.bits_per_id == 0 {
324             // Optimize the surprisingly common degenerate case.
325             return;
326         }
327
328         {
329             let mut propcx = PropagationContext {
330                 dfcx: self,
331                 changed: true
332             };
333
334             let mut temp = vec::from_elem(self.words_per_id, 0u);
335             let mut loop_scopes = ~[];
336
337             while propcx.changed {
338                 propcx.changed = false;
339                 propcx.reset(temp);
340                 propcx.walk_block(blk, temp, &mut loop_scopes);
341             }
342         }
343
344         debug!("Dataflow result:");
345         debug!("{}", {
346             self.pretty_print_to(~io::stderr(), blk).unwrap();
347             ""
348         });
349     }
350
351     fn pretty_print_to(&self, wr: ~io::Writer,
352                        blk: &ast::Block) -> io::IoResult<()> {
353         let mut ps = pprust::rust_printer_annotated(wr, self);
354         try!(pprust::cbox(&mut ps, pprust::indent_unit));
355         try!(pprust::ibox(&mut ps, 0u));
356         try!(pprust::print_block(&mut ps, blk));
357         try!(pp::eof(&mut ps.s));
358         Ok(())
359     }
360 }
361
362 impl<'a, O:DataFlowOperator> PropagationContext<'a, O> {
363     fn tcx(&self) -> ty::ctxt {
364         self.dfcx.tcx
365     }
366
367     fn walk_block(&mut self,
368                   blk: &ast::Block,
369                   in_out: &mut [uint],
370                   loop_scopes: &mut ~[LoopScope]) {
371         debug!("DataFlowContext::walk_block(blk.id={}, in_out={})",
372                blk.id, bits_to_str(in_out));
373
374         self.merge_with_entry_set(blk.id, in_out);
375
376         for &stmt in blk.stmts.iter() {
377             self.walk_stmt(stmt, in_out, loop_scopes);
378         }
379
380         self.walk_opt_expr(blk.expr, in_out, loop_scopes);
381
382         self.dfcx.apply_gen_kill(blk.id, in_out);
383     }
384
385     fn walk_stmt(&mut self,
386                  stmt: @ast::Stmt,
387                  in_out: &mut [uint],
388                  loop_scopes: &mut ~[LoopScope]) {
389         match stmt.node {
390             ast::StmtDecl(decl, _) => {
391                 self.walk_decl(decl, in_out, loop_scopes);
392             }
393
394             ast::StmtExpr(expr, _) | ast::StmtSemi(expr, _) => {
395                 self.walk_expr(expr, in_out, loop_scopes);
396             }
397
398             ast::StmtMac(..) => {
399                 self.tcx().sess.span_bug(stmt.span, "unexpanded macro");
400             }
401         }
402     }
403
404     fn walk_decl(&mut self,
405                  decl: @ast::Decl,
406                  in_out: &mut [uint],
407                  loop_scopes: &mut ~[LoopScope]) {
408         match decl.node {
409             ast::DeclLocal(local) => {
410                 self.walk_opt_expr(local.init, in_out, loop_scopes);
411                 self.walk_pat(local.pat, in_out, loop_scopes);
412             }
413
414             ast::DeclItem(_) => {}
415         }
416     }
417
418     fn walk_expr(&mut self,
419                  expr: &ast::Expr,
420                  in_out: &mut [uint],
421                  loop_scopes: &mut ~[LoopScope]) {
422         debug!("DataFlowContext::walk_expr(expr={}, in_out={})",
423                expr.repr(self.dfcx.tcx), bits_to_str(in_out));
424
425         self.merge_with_entry_set(expr.id, in_out);
426
427         match expr.node {
428             ast::ExprFnBlock(..) | ast::ExprProc(..) => {
429             }
430
431             ast::ExprIf(cond, then, els) => {
432                 //
433                 //     (cond)
434                 //       |
435                 //       v
436                 //      ( )
437                 //     /   \
438                 //    |     |
439                 //    v     v
440                 //  (then)(els)
441                 //    |     |
442                 //    v     v
443                 //   (  succ  )
444                 //
445                 self.walk_expr(cond, in_out, loop_scopes);
446
447                 let mut then_bits = in_out.to_owned();
448                 self.walk_block(then, then_bits, loop_scopes);
449
450                 self.walk_opt_expr(els, in_out, loop_scopes);
451                 join_bits(&self.dfcx.oper, then_bits, in_out);
452             }
453
454             ast::ExprWhile(cond, blk) => {
455                 //
456                 //     (expr) <--+
457                 //       |       |
458                 //       v       |
459                 //  +--(cond)    |
460                 //  |    |       |
461                 //  |    v       |
462                 //  v  (blk) ----+
463                 //       |
464                 //    <--+ (break)
465                 //
466
467                 self.walk_expr(cond, in_out, loop_scopes);
468
469                 let mut body_bits = in_out.to_owned();
470                 loop_scopes.push(LoopScope {
471                     loop_id: expr.id,
472                     break_bits: in_out.to_owned()
473                 });
474                 self.walk_block(blk, body_bits, loop_scopes);
475                 self.add_to_entry_set(expr.id, body_bits);
476                 let new_loop_scope = loop_scopes.pop().unwrap();
477                 copy_bits(new_loop_scope.break_bits, in_out);
478             }
479
480             ast::ExprForLoop(..) => fail!("non-desugared expr_for_loop"),
481
482             ast::ExprLoop(blk, _) => {
483                 //
484                 //     (expr) <--+
485                 //       |       |
486                 //       v       |
487                 //     (blk) ----+
488                 //       |
489                 //    <--+ (break)
490                 //
491
492                 let mut body_bits = in_out.to_owned();
493                 self.reset(in_out);
494                 loop_scopes.push(LoopScope {
495                     loop_id: expr.id,
496                     break_bits: in_out.to_owned()
497                 });
498                 self.walk_block(blk, body_bits, loop_scopes);
499                 self.add_to_entry_set(expr.id, body_bits);
500
501                 let new_loop_scope = loop_scopes.pop().unwrap();
502                 assert_eq!(new_loop_scope.loop_id, expr.id);
503                 copy_bits(new_loop_scope.break_bits, in_out);
504             }
505
506             ast::ExprMatch(discr, ref arms) => {
507                 //
508                 //    (discr)
509                 //     / | \
510                 //    |  |  |
511                 //    v  v  v
512                 //   (..arms..)
513                 //    |  |  |
514                 //    v  v  v
515                 //   (  succ  )
516                 //
517                 //
518                 self.walk_expr(discr, in_out, loop_scopes);
519
520                 let mut guards = in_out.to_owned();
521
522                 // We know that exactly one arm will be taken, so we
523                 // can start out with a blank slate and just union
524                 // together the bits from each arm:
525                 self.reset(in_out);
526
527                 for arm in arms.iter() {
528                     // in_out reflects the discr and all guards to date
529                     self.walk_opt_expr(arm.guard, guards, loop_scopes);
530
531                     // determine the bits for the body and then union
532                     // them into `in_out`, which reflects all bodies to date
533                     let mut body = guards.to_owned();
534                     self.walk_pat_alternatives(arm.pats, body, loop_scopes);
535                     self.walk_block(arm.body, body, loop_scopes);
536                     join_bits(&self.dfcx.oper, body, in_out);
537                 }
538             }
539
540             ast::ExprRet(o_e) => {
541                 self.walk_opt_expr(o_e, in_out, loop_scopes);
542                 self.reset(in_out);
543             }
544
545             ast::ExprBreak(label) => {
546                 let scope = self.find_scope(expr, label, loop_scopes);
547                 self.break_from_to(expr, scope, in_out);
548                 self.reset(in_out);
549             }
550
551             ast::ExprAgain(label) => {
552                 let scope = self.find_scope(expr, label, loop_scopes);
553                 self.pop_scopes(expr, scope, in_out);
554                 self.add_to_entry_set(scope.loop_id, in_out);
555                 self.reset(in_out);
556             }
557
558             ast::ExprAssign(l, r) |
559             ast::ExprAssignOp(_, l, r) => {
560                 self.walk_expr(r, in_out, loop_scopes);
561                 self.walk_expr(l, in_out, loop_scopes);
562             }
563
564             ast::ExprVec(ref exprs, _) => {
565                 self.walk_exprs(*exprs, in_out, loop_scopes)
566             }
567
568             ast::ExprRepeat(l, r, _) => {
569                 self.walk_expr(l, in_out, loop_scopes);
570                 self.walk_expr(r, in_out, loop_scopes);
571             }
572
573             ast::ExprStruct(_, ref fields, with_expr) => {
574                 for field in fields.iter() {
575                     self.walk_expr(field.expr, in_out, loop_scopes);
576                 }
577                 self.walk_opt_expr(with_expr, in_out, loop_scopes);
578             }
579
580             ast::ExprCall(f, ref args) => {
581                 self.walk_expr(f, in_out, loop_scopes);
582                 self.walk_call(expr.id, *args, in_out, loop_scopes);
583             }
584
585             ast::ExprMethodCall(_, _, ref args) => {
586                 self.walk_call(expr.id, *args, in_out, loop_scopes);
587             }
588
589             ast::ExprIndex(l, r) |
590             ast::ExprBinary(_, l, r) if self.is_method_call(expr) => {
591                 self.walk_call(expr.id, [l, r], in_out, loop_scopes);
592             }
593
594             ast::ExprUnary(_, e) if self.is_method_call(expr) => {
595                 self.walk_call(expr.id, [e], in_out, loop_scopes);
596             }
597
598             ast::ExprTup(ref exprs) => {
599                 self.walk_exprs(*exprs, in_out, loop_scopes);
600             }
601
602             ast::ExprBinary(op, l, r) if ast_util::lazy_binop(op) => {
603                 self.walk_expr(l, in_out, loop_scopes);
604                 let temp = in_out.to_owned();
605                 self.walk_expr(r, in_out, loop_scopes);
606                 join_bits(&self.dfcx.oper, temp, in_out);
607             }
608
609             ast::ExprIndex(l, r) |
610             ast::ExprBinary(_, l, r) => {
611                 self.walk_exprs([l, r], in_out, loop_scopes);
612             }
613
614             ast::ExprLogLevel |
615             ast::ExprLit(..) |
616             ast::ExprPath(..) => {}
617
618             ast::ExprAddrOf(_, e) |
619             ast::ExprCast(e, _) |
620             ast::ExprUnary(_, e) |
621             ast::ExprParen(e) |
622             ast::ExprVstore(e, _) |
623             ast::ExprField(e, _, _) => {
624                 self.walk_expr(e, in_out, loop_scopes);
625             }
626
627             ast::ExprBox(s, e) => {
628                 self.walk_expr(s, in_out, loop_scopes);
629                 self.walk_expr(e, in_out, loop_scopes);
630             }
631
632             ast::ExprInlineAsm(ref inline_asm) => {
633                 for &(_, expr) in inline_asm.inputs.iter() {
634                     self.walk_expr(expr, in_out, loop_scopes);
635                 }
636                 for &(_, expr) in inline_asm.outputs.iter() {
637                     self.walk_expr(expr, in_out, loop_scopes);
638                 }
639             }
640
641             ast::ExprBlock(blk) => {
642                 self.walk_block(blk, in_out, loop_scopes);
643             }
644
645             ast::ExprMac(..) => {
646                 self.tcx().sess.span_bug(expr.span, "unexpanded macro");
647             }
648         }
649
650         self.dfcx.apply_gen_kill(expr.id, in_out);
651     }
652
653     fn pop_scopes(&mut self,
654                   from_expr: &ast::Expr,
655                   to_scope: &mut LoopScope,
656                   in_out: &mut [uint]) {
657         //! Whenever you have a `break` or a `loop` statement, flow
658         //! exits through any number of enclosing scopes on its
659         //! way to the new destination. This function applies the kill
660         //! sets of those enclosing scopes to `in_out` (those kill sets
661         //! concern items that are going out of scope).
662
663         let tcx = self.tcx();
664
665         debug!("pop_scopes(from_expr={}, to_scope={:?}, in_out={})",
666                from_expr.repr(tcx), to_scope.loop_id,
667                bits_to_str(in_out));
668
669         let mut id = from_expr.id;
670         while id != to_scope.loop_id {
671             self.dfcx.apply_kill(id, in_out);
672
673             match tcx.region_maps.opt_encl_scope(id) {
674                 Some(i) => { id = i; }
675                 None => {
676                     tcx.sess.span_bug(
677                         from_expr.span,
678                         format!("pop_scopes(from_expr={}, to_scope={:?}) \
679                               to_scope does not enclose from_expr",
680                              from_expr.repr(tcx), to_scope.loop_id));
681                 }
682             }
683         }
684     }
685
686     fn break_from_to(&mut self,
687                      from_expr: &ast::Expr,
688                      to_scope: &mut LoopScope,
689                      in_out: &mut [uint]) {
690         self.pop_scopes(from_expr, to_scope, in_out);
691         self.dfcx.apply_kill(from_expr.id, in_out);
692         join_bits(&self.dfcx.oper, in_out, to_scope.break_bits);
693         debug!("break_from_to(from_expr={}, to_scope={}) final break_bits={}",
694                from_expr.repr(self.tcx()),
695                to_scope.loop_id,
696                bits_to_str(in_out));
697     }
698
699     fn walk_exprs(&mut self,
700                   exprs: &[@ast::Expr],
701                   in_out: &mut [uint],
702                   loop_scopes: &mut ~[LoopScope]) {
703         for &expr in exprs.iter() {
704             self.walk_expr(expr, in_out, loop_scopes);
705         }
706     }
707
708     fn walk_opt_expr(&mut self,
709                      opt_expr: Option<@ast::Expr>,
710                      in_out: &mut [uint],
711                      loop_scopes: &mut ~[LoopScope]) {
712         for &expr in opt_expr.iter() {
713             self.walk_expr(expr, in_out, loop_scopes);
714         }
715     }
716
717     fn walk_call(&mut self,
718                  call_id: ast::NodeId,
719                  args: &[@ast::Expr],
720                  in_out: &mut [uint],
721                  loop_scopes: &mut ~[LoopScope]) {
722         self.walk_exprs(args, in_out, loop_scopes);
723
724         // FIXME(#6268) nested method calls
725         // self.merge_with_entry_set(in_out);
726         // self.dfcx.apply_gen_kill(in_out);
727
728         let return_ty = ty::node_id_to_type(self.tcx(), call_id);
729         let fails = ty::type_is_bot(return_ty);
730         if fails {
731             self.reset(in_out);
732         }
733     }
734
735     fn walk_pat(&mut self,
736                 pat: @ast::Pat,
737                 in_out: &mut [uint],
738                 _loop_scopes: &mut ~[LoopScope]) {
739         debug!("DataFlowContext::walk_pat(pat={}, in_out={})",
740                pat.repr(self.dfcx.tcx), bits_to_str(in_out));
741
742         ast_util::walk_pat(pat, |p| {
743             debug!("  p.id={} in_out={}", p.id, bits_to_str(in_out));
744             self.merge_with_entry_set(p.id, in_out);
745             self.dfcx.apply_gen_kill(p.id, in_out);
746             true
747         });
748     }
749
750     fn walk_pat_alternatives(&mut self,
751                              pats: &[@ast::Pat],
752                              in_out: &mut [uint],
753                              loop_scopes: &mut ~[LoopScope]) {
754         if pats.len() == 1 {
755             // Common special case:
756             return self.walk_pat(pats[0], in_out, loop_scopes);
757         }
758
759         // In the general case, the patterns in `pats` are
760         // alternatives, so we must treat this like an N-way select
761         // statement.
762         let initial_state = in_out.to_owned();
763         for &pat in pats.iter() {
764             let mut temp = initial_state.clone();
765             self.walk_pat(pat, temp, loop_scopes);
766             join_bits(&self.dfcx.oper, temp, in_out);
767         }
768     }
769
770     fn find_scope<'a>(&self,
771                       expr: &ast::Expr,
772                       label: Option<ast::Ident>,
773                       loop_scopes: &'a mut ~[LoopScope]) -> &'a mut LoopScope {
774         let index = match label {
775             None => {
776                 let len = loop_scopes.len();
777                 len - 1
778             }
779
780             Some(_) => {
781                 let def_map = self.tcx().def_map.borrow();
782                 match def_map.get().find(&expr.id) {
783                     Some(&ast::DefLabel(loop_id)) => {
784                         match loop_scopes.iter().position(|l| l.loop_id == loop_id) {
785                             Some(i) => i,
786                             None => {
787                                 self.tcx().sess.span_bug(
788                                     expr.span,
789                                     format!("no loop scope for id {:?}", loop_id));
790                             }
791                         }
792                     }
793
794                     r => {
795                         self.tcx().sess.span_bug(
796                             expr.span,
797                             format!("bad entry `{:?}` in def_map for label", r));
798                     }
799                 }
800             }
801         };
802
803         &mut loop_scopes[index]
804     }
805
806     fn is_method_call(&self, expr: &ast::Expr) -> bool {
807         let method_map = self.dfcx.method_map.borrow();
808         method_map.get().contains_key(&expr.id)
809     }
810
811     fn reset(&mut self, bits: &mut [uint]) {
812         let e = if self.dfcx.oper.initial_value() {uint::MAX} else {0};
813         for b in bits.mut_iter() { *b = e; }
814     }
815
816     fn add_to_entry_set(&mut self, id: ast::NodeId, pred_bits: &[uint]) {
817         debug!("add_to_entry_set(id={:?}, pred_bits={})",
818                id, bits_to_str(pred_bits));
819         let (start, end) = self.dfcx.compute_id_range(id);
820         let changed = { // FIXME(#5074) awkward construction
821             let on_entry = self.dfcx.on_entry.mut_slice(start, end);
822             join_bits(&self.dfcx.oper, pred_bits, on_entry)
823         };
824         if changed {
825             debug!("changed entry set for {:?} to {}",
826                    id, bits_to_str(self.dfcx.on_entry.slice(start, end)));
827             self.changed = true;
828         }
829     }
830
831     fn merge_with_entry_set(&mut self,
832                             id: ast::NodeId,
833                             pred_bits: &mut [uint]) {
834         debug!("merge_with_entry_set(id={:?}, pred_bits={})",
835                id, mut_bits_to_str(pred_bits));
836         let (start, end) = self.dfcx.compute_id_range(id);
837         let changed = { // FIXME(#5074) awkward construction
838             let on_entry = self.dfcx.on_entry.mut_slice(start, end);
839             let changed = join_bits(&self.dfcx.oper, pred_bits, on_entry);
840             copy_bits(on_entry, pred_bits);
841             changed
842         };
843         if changed {
844             debug!("changed entry set for {:?} to {}",
845                    id, bits_to_str(self.dfcx.on_entry.slice(start, end)));
846             self.changed = true;
847         }
848     }
849 }
850
851 fn mut_bits_to_str(words: &mut [uint]) -> ~str {
852     bits_to_str(words)
853 }
854
855 fn bits_to_str(words: &[uint]) -> ~str {
856     let mut result = ~"";
857     let mut sep = '[';
858
859     // Note: this is a little endian printout of bytes.
860
861     for &word in words.iter() {
862         let mut v = word;
863         for _ in range(0u, uint::BYTES) {
864             result.push_char(sep);
865             result.push_str(format!("{:02x}", v & 0xFF));
866             v >>= 8;
867             sep = '-';
868         }
869     }
870     result.push_char(']');
871     return result;
872 }
873
874 fn copy_bits(in_vec: &[uint], out_vec: &mut [uint]) -> bool {
875     bitwise(out_vec, in_vec, |_, b| b)
876 }
877
878 fn join_bits<O:DataFlowOperator>(oper: &O,
879                                  in_vec: &[uint],
880                                  out_vec: &mut [uint]) -> bool {
881     bitwise(out_vec, in_vec, |a, b| oper.join(a, b))
882 }
883
884 #[inline]
885 fn bitwise(out_vec: &mut [uint], in_vec: &[uint], op: |uint, uint| -> uint)
886            -> bool {
887     assert_eq!(out_vec.len(), in_vec.len());
888     let mut changed = false;
889     for (out_elt, in_elt) in out_vec.mut_iter().zip(in_vec.iter()) {
890         let old_val = *out_elt;
891         let new_val = op(old_val, *in_elt);
892         *out_elt = new_val;
893         changed |= old_val != new_val;
894     }
895     changed
896 }
897
898 fn set_bit(words: &mut [uint], bit: uint) -> bool {
899     debug!("set_bit: words={} bit={}",
900            mut_bits_to_str(words), bit_str(bit));
901     let word = bit / uint::BITS;
902     let bit_in_word = bit % uint::BITS;
903     let bit_mask = 1 << bit_in_word;
904     debug!("word={} bit_in_word={} bit_mask={}", word, bit_in_word, word);
905     let oldv = words[word];
906     let newv = oldv | bit_mask;
907     words[word] = newv;
908     oldv != newv
909 }
910
911 fn bit_str(bit: uint) -> ~str {
912     let byte = bit >> 8;
913     let lobits = 1 << (bit & 0xFF);
914     format!("[{}:{}-{:02x}]", bit, byte, lobits)
915 }
916