]> git.lizzy.rs Git - rust.git/blob - src/librustc/mir/repr.rs
Move "rust-call" tuple spreading out of ArgDecl
[rust.git] / src / librustc / mir / repr.rs
1 // Copyright 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 use graphviz::IntoCow;
12 use middle::const_val::ConstVal;
13 use rustc_const_math::{ConstUsize, ConstInt, ConstMathErr};
14 use rustc_data_structures::indexed_vec::{IndexVec, Idx};
15 use rustc_data_structures::control_flow_graph::dominators::{Dominators, dominators};
16 use rustc_data_structures::control_flow_graph::{GraphPredecessors, GraphSuccessors};
17 use rustc_data_structures::control_flow_graph::ControlFlowGraph;
18 use hir::def_id::DefId;
19 use ty::subst::Substs;
20 use ty::{self, AdtDef, ClosureSubsts, Region, Ty};
21 use util::ppaux;
22 use rustc_back::slice;
23 use hir::InlineAsm;
24 use std::ascii;
25 use std::borrow::{Cow};
26 use std::cell::Ref;
27 use std::fmt::{self, Debug, Formatter, Write};
28 use std::{iter, u32};
29 use std::ops::{Index, IndexMut};
30 use std::vec::IntoIter;
31 use syntax::ast::{self, Name};
32 use syntax_pos::Span;
33
34 use super::cache::Cache;
35
36 macro_rules! newtype_index {
37     ($name:ident, $debug_name:expr) => (
38         #[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord,
39          RustcEncodable, RustcDecodable)]
40         pub struct $name(u32);
41
42         impl Idx for $name {
43             fn new(value: usize) -> Self {
44                 assert!(value < (u32::MAX) as usize);
45                 $name(value as u32)
46             }
47             fn index(self) -> usize {
48                 self.0 as usize
49             }
50         }
51
52         impl Debug for $name {
53             fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
54                 write!(fmt, "{}{}", $debug_name, self.0)
55             }
56         }
57     )
58 }
59
60 /// Lowered representation of a single function.
61 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
62 pub struct Mir<'tcx> {
63     /// List of basic blocks. References to basic block use a newtyped index type `BasicBlock`
64     /// that indexes into this vector.
65     basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
66
67     /// List of visibility (lexical) scopes; these are referenced by statements
68     /// and used (eventually) for debuginfo. Indexed by a `VisibilityScope`.
69     pub visibility_scopes: IndexVec<VisibilityScope, VisibilityScopeData>,
70
71     /// Rvalues promoted from this function, such as borrows of constants.
72     /// Each of them is the Mir of a constant with the fn's type parameters
73     /// in scope, but no vars or args and a separate set of temps.
74     pub promoted: IndexVec<Promoted, Mir<'tcx>>,
75
76     /// Return type of the function.
77     pub return_ty: Ty<'tcx>,
78
79     /// Variables: these are stack slots corresponding to user variables. They may be
80     /// assigned many times.
81     pub var_decls: IndexVec<Var, VarDecl<'tcx>>,
82
83     /// Args: these are stack slots corresponding to the input arguments.
84     pub arg_decls: IndexVec<Arg, ArgDecl<'tcx>>,
85
86     /// Temp declarations: stack slots that for temporaries created by
87     /// the compiler. These are assigned once, but they are not SSA
88     /// values in that it is possible to borrow them and mutate them
89     /// through the resulting reference.
90     pub temp_decls: IndexVec<Temp, TempDecl<'tcx>>,
91
92     /// Names and capture modes of all the closure upvars, assuming
93     /// the first argument is either the closure or a reference to it.
94     pub upvar_decls: Vec<UpvarDecl>,
95
96     /// A boolean indicating whether the last argument (which must be a tuple)
97     /// is passed as its individual components at the LLVM level.
98     ///
99     /// This is used for the "rust-call" ABI.
100     pub spread_last_arg: bool,
101
102     /// A span representing this MIR, for error reporting
103     pub span: Span,
104
105     /// A cache for various calculations
106     cache: Cache
107 }
108
109 /// where execution begins
110 pub const START_BLOCK: BasicBlock = BasicBlock(0);
111
112 impl<'tcx> Mir<'tcx> {
113     pub fn new(basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
114                visibility_scopes: IndexVec<VisibilityScope, VisibilityScopeData>,
115                promoted: IndexVec<Promoted, Mir<'tcx>>,
116                return_ty: Ty<'tcx>,
117                var_decls: IndexVec<Var, VarDecl<'tcx>>,
118                arg_decls: IndexVec<Arg, ArgDecl<'tcx>>,
119                temp_decls: IndexVec<Temp, TempDecl<'tcx>>,
120                upvar_decls: Vec<UpvarDecl>,
121                span: Span) -> Self
122     {
123         Mir {
124             basic_blocks: basic_blocks,
125             visibility_scopes: visibility_scopes,
126             promoted: promoted,
127             return_ty: return_ty,
128             var_decls: var_decls,
129             arg_decls: arg_decls,
130             temp_decls: temp_decls,
131             upvar_decls: upvar_decls,
132             spread_last_arg: false,
133             span: span,
134             cache: Cache::new()
135         }
136     }
137
138     #[inline]
139     pub fn basic_blocks(&self) -> &IndexVec<BasicBlock, BasicBlockData<'tcx>> {
140         &self.basic_blocks
141     }
142
143     #[inline]
144     pub fn basic_blocks_mut(&mut self) -> &mut IndexVec<BasicBlock, BasicBlockData<'tcx>> {
145         self.cache.invalidate();
146         &mut self.basic_blocks
147     }
148
149     #[inline]
150     pub fn predecessors(&self) -> Ref<IndexVec<BasicBlock, Vec<BasicBlock>>> {
151         self.cache.predecessors(self)
152     }
153
154     #[inline]
155     pub fn predecessors_for(&self, bb: BasicBlock) -> Ref<Vec<BasicBlock>> {
156         Ref::map(self.predecessors(), |p| &p[bb])
157     }
158
159     #[inline]
160     pub fn dominators(&self) -> Dominators<BasicBlock> {
161         dominators(self)
162     }
163
164     /// Maps locals (Arg's, Var's, Temp's and ReturnPointer, in that order)
165     /// to their index in the whole list of locals. This is useful if you
166     /// want to treat all locals the same instead of repeating yourself.
167     pub fn local_index(&self, lvalue: &Lvalue<'tcx>) -> Option<Local> {
168         let idx = match *lvalue {
169             Lvalue::Arg(arg) => arg.index(),
170             Lvalue::Var(var) => {
171                 self.arg_decls.len() +
172                 var.index()
173             }
174             Lvalue::Temp(temp) => {
175                 self.arg_decls.len() +
176                 self.var_decls.len() +
177                 temp.index()
178             }
179             Lvalue::ReturnPointer => {
180                 self.arg_decls.len() +
181                 self.var_decls.len() +
182                 self.temp_decls.len()
183             }
184             Lvalue::Static(_) |
185             Lvalue::Projection(_) => return None
186         };
187         Some(Local::new(idx))
188     }
189
190     /// Counts the number of locals, such that local_index
191     /// will always return an index smaller than this count.
192     pub fn count_locals(&self) -> usize {
193         self.arg_decls.len() +
194         self.var_decls.len() +
195         self.temp_decls.len() + 1
196     }
197
198     pub fn format_local(&self, local: Local) -> String {
199         let mut index = local.index();
200         index = match index.checked_sub(self.arg_decls.len()) {
201             None => return format!("{:?}", Arg::new(index)),
202             Some(index) => index,
203         };
204         index = match index.checked_sub(self.var_decls.len()) {
205             None => return format!("{:?}", Var::new(index)),
206             Some(index) => index,
207         };
208         index = match index.checked_sub(self.temp_decls.len()) {
209             None => return format!("{:?}", Temp::new(index)),
210             Some(index) => index,
211         };
212         debug_assert!(index == 0);
213         return "ReturnPointer".to_string()
214     }
215
216     /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
217     /// invalidating statement indices in `Location`s.
218     pub fn make_statement_nop(&mut self, location: Location) {
219         let block = &mut self[location.block];
220         debug_assert!(location.statement_index < block.statements.len());
221         block.statements[location.statement_index].make_nop()
222     }
223 }
224
225 impl<'tcx> Index<BasicBlock> for Mir<'tcx> {
226     type Output = BasicBlockData<'tcx>;
227
228     #[inline]
229     fn index(&self, index: BasicBlock) -> &BasicBlockData<'tcx> {
230         &self.basic_blocks()[index]
231     }
232 }
233
234 impl<'tcx> IndexMut<BasicBlock> for Mir<'tcx> {
235     #[inline]
236     fn index_mut(&mut self, index: BasicBlock) -> &mut BasicBlockData<'tcx> {
237         &mut self.basic_blocks_mut()[index]
238     }
239 }
240
241 /// Grouped information about the source code origin of a MIR entity.
242 /// Intended to be inspected by diagnostics and debuginfo.
243 /// Most passes can work with it as a whole, within a single function.
244 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
245 pub struct SourceInfo {
246     /// Source span for the AST pertaining to this MIR entity.
247     pub span: Span,
248
249     /// The lexical visibility scope, i.e. which bindings can be seen.
250     pub scope: VisibilityScope
251 }
252
253 ///////////////////////////////////////////////////////////////////////////
254 // Mutability and borrow kinds
255
256 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
257 pub enum Mutability {
258     Mut,
259     Not,
260 }
261
262 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
263 pub enum BorrowKind {
264     /// Data must be immutable and is aliasable.
265     Shared,
266
267     /// Data must be immutable but not aliasable.  This kind of borrow
268     /// cannot currently be expressed by the user and is used only in
269     /// implicit closure bindings. It is needed when you the closure
270     /// is borrowing or mutating a mutable referent, e.g.:
271     ///
272     ///    let x: &mut isize = ...;
273     ///    let y = || *x += 5;
274     ///
275     /// If we were to try to translate this closure into a more explicit
276     /// form, we'd encounter an error with the code as written:
277     ///
278     ///    struct Env { x: & &mut isize }
279     ///    let x: &mut isize = ...;
280     ///    let y = (&mut Env { &x }, fn_ptr);  // Closure is pair of env and fn
281     ///    fn fn_ptr(env: &mut Env) { **env.x += 5; }
282     ///
283     /// This is then illegal because you cannot mutate a `&mut` found
284     /// in an aliasable location. To solve, you'd have to translate with
285     /// an `&mut` borrow:
286     ///
287     ///    struct Env { x: & &mut isize }
288     ///    let x: &mut isize = ...;
289     ///    let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
290     ///    fn fn_ptr(env: &mut Env) { **env.x += 5; }
291     ///
292     /// Now the assignment to `**env.x` is legal, but creating a
293     /// mutable pointer to `x` is not because `x` is not mutable. We
294     /// could fix this by declaring `x` as `let mut x`. This is ok in
295     /// user code, if awkward, but extra weird for closures, since the
296     /// borrow is hidden.
297     ///
298     /// So we introduce a "unique imm" borrow -- the referent is
299     /// immutable, but not aliasable. This solves the problem. For
300     /// simplicity, we don't give users the way to express this
301     /// borrow, it's just used when translating closures.
302     Unique,
303
304     /// Data is mutable and not aliasable.
305     Mut,
306 }
307
308 ///////////////////////////////////////////////////////////////////////////
309 // Variables and temps
310
311 /// A "variable" is a binding declared by the user as part of the fn
312 /// decl, a let, etc.
313 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
314 pub struct VarDecl<'tcx> {
315     /// `let mut x` vs `let x`
316     pub mutability: Mutability,
317
318     /// name that user gave the variable; not that, internally,
319     /// mir references variables by index
320     pub name: Name,
321
322     /// type inferred for this variable (`let x: ty = ...`)
323     pub ty: Ty<'tcx>,
324
325     /// source information (span, scope, etc.) for the declaration
326     pub source_info: SourceInfo,
327 }
328
329 /// A "temp" is a temporary that we place on the stack. They are
330 /// anonymous, always mutable, and have only a type.
331 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
332 pub struct TempDecl<'tcx> {
333     pub ty: Ty<'tcx>,
334 }
335
336 /// A "arg" is one of the function's formal arguments. These are
337 /// anonymous and distinct from the bindings that the user declares.
338 ///
339 /// For example, in this function:
340 ///
341 /// ```
342 /// fn foo((x, y): (i32, u32)) { ... }
343 /// ```
344 ///
345 /// there is only one argument, of type `(i32, u32)`, but two bindings
346 /// (`x` and `y`).
347 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
348 pub struct ArgDecl<'tcx> {
349     pub ty: Ty<'tcx>,
350
351     /// Either keywords::Invalid or the name of a single-binding
352     /// pattern associated with this argument. Useful for debuginfo.
353     pub debug_name: Name
354 }
355
356 /// A closure capture, with its name and mode.
357 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
358 pub struct UpvarDecl {
359     pub debug_name: Name,
360
361     /// If true, the capture is behind a reference.
362     pub by_ref: bool
363 }
364
365 ///////////////////////////////////////////////////////////////////////////
366 // BasicBlock
367
368 newtype_index!(BasicBlock, "bb");
369
370 ///////////////////////////////////////////////////////////////////////////
371 // BasicBlockData and Terminator
372
373 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
374 pub struct BasicBlockData<'tcx> {
375     /// List of statements in this block.
376     pub statements: Vec<Statement<'tcx>>,
377
378     /// Terminator for this block.
379     ///
380     /// NB. This should generally ONLY be `None` during construction.
381     /// Therefore, you should generally access it via the
382     /// `terminator()` or `terminator_mut()` methods. The only
383     /// exception is that certain passes, such as `simplify_cfg`, swap
384     /// out the terminator temporarily with `None` while they continue
385     /// to recurse over the set of basic blocks.
386     pub terminator: Option<Terminator<'tcx>>,
387
388     /// If true, this block lies on an unwind path. This is used
389     /// during trans where distinct kinds of basic blocks may be
390     /// generated (particularly for MSVC cleanup). Unwind blocks must
391     /// only branch to other unwind blocks.
392     pub is_cleanup: bool,
393 }
394
395 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
396 pub struct Terminator<'tcx> {
397     pub source_info: SourceInfo,
398     pub kind: TerminatorKind<'tcx>
399 }
400
401 #[derive(Clone, RustcEncodable, RustcDecodable)]
402 pub enum TerminatorKind<'tcx> {
403     /// block should have one successor in the graph; we jump there
404     Goto {
405         target: BasicBlock,
406     },
407
408     /// jump to branch 0 if this lvalue evaluates to true
409     If {
410         cond: Operand<'tcx>,
411         targets: (BasicBlock, BasicBlock),
412     },
413
414     /// lvalue evaluates to some enum; jump depending on the branch
415     Switch {
416         discr: Lvalue<'tcx>,
417         adt_def: AdtDef<'tcx>,
418         targets: Vec<BasicBlock>,
419     },
420
421     /// operand evaluates to an integer; jump depending on its value
422     /// to one of the targets, and otherwise fallback to `otherwise`
423     SwitchInt {
424         /// discriminant value being tested
425         discr: Lvalue<'tcx>,
426
427         /// type of value being tested
428         switch_ty: Ty<'tcx>,
429
430         /// Possible values. The locations to branch to in each case
431         /// are found in the corresponding indices from the `targets` vector.
432         values: Vec<ConstVal>,
433
434         /// Possible branch sites. The length of this vector should be
435         /// equal to the length of the `values` vector plus 1 -- the
436         /// extra item is the block to branch to if none of the values
437         /// fit.
438         targets: Vec<BasicBlock>,
439     },
440
441     /// Indicates that the landing pad is finished and unwinding should
442     /// continue. Emitted by build::scope::diverge_cleanup.
443     Resume,
444
445     /// Indicates a normal return. The ReturnPointer lvalue should
446     /// have been filled in by now. This should occur at most once.
447     Return,
448
449     /// Indicates a terminator that can never be reached.
450     Unreachable,
451
452     /// Drop the Lvalue
453     Drop {
454         location: Lvalue<'tcx>,
455         target: BasicBlock,
456         unwind: Option<BasicBlock>
457     },
458
459     /// Drop the Lvalue and assign the new value over it
460     DropAndReplace {
461         location: Lvalue<'tcx>,
462         value: Operand<'tcx>,
463         target: BasicBlock,
464         unwind: Option<BasicBlock>,
465     },
466
467     /// Block ends with a call of a converging function
468     Call {
469         /// The function that’s being called
470         func: Operand<'tcx>,
471         /// Arguments the function is called with
472         args: Vec<Operand<'tcx>>,
473         /// Destination for the return value. If some, the call is converging.
474         destination: Option<(Lvalue<'tcx>, BasicBlock)>,
475         /// Cleanups to be done if the call unwinds.
476         cleanup: Option<BasicBlock>
477     },
478
479     /// Jump to the target if the condition has the expected value,
480     /// otherwise panic with a message and a cleanup target.
481     Assert {
482         cond: Operand<'tcx>,
483         expected: bool,
484         msg: AssertMessage<'tcx>,
485         target: BasicBlock,
486         cleanup: Option<BasicBlock>
487     }
488 }
489
490 impl<'tcx> Terminator<'tcx> {
491     pub fn successors(&self) -> Cow<[BasicBlock]> {
492         self.kind.successors()
493     }
494
495     pub fn successors_mut(&mut self) -> Vec<&mut BasicBlock> {
496         self.kind.successors_mut()
497     }
498 }
499
500 impl<'tcx> TerminatorKind<'tcx> {
501     pub fn successors(&self) -> Cow<[BasicBlock]> {
502         use self::TerminatorKind::*;
503         match *self {
504             Goto { target: ref b } => slice::ref_slice(b).into_cow(),
505             If { targets: (b1, b2), .. } => vec![b1, b2].into_cow(),
506             Switch { targets: ref b, .. } => b[..].into_cow(),
507             SwitchInt { targets: ref b, .. } => b[..].into_cow(),
508             Resume => (&[]).into_cow(),
509             Return => (&[]).into_cow(),
510             Unreachable => (&[]).into_cow(),
511             Call { destination: Some((_, t)), cleanup: Some(c), .. } => vec![t, c].into_cow(),
512             Call { destination: Some((_, ref t)), cleanup: None, .. } =>
513                 slice::ref_slice(t).into_cow(),
514             Call { destination: None, cleanup: Some(ref c), .. } => slice::ref_slice(c).into_cow(),
515             Call { destination: None, cleanup: None, .. } => (&[]).into_cow(),
516             DropAndReplace { target, unwind: Some(unwind), .. } |
517             Drop { target, unwind: Some(unwind), .. } => {
518                 vec![target, unwind].into_cow()
519             }
520             DropAndReplace { ref target, unwind: None, .. } |
521             Drop { ref target, unwind: None, .. } => {
522                 slice::ref_slice(target).into_cow()
523             }
524             Assert { target, cleanup: Some(unwind), .. } => vec![target, unwind].into_cow(),
525             Assert { ref target, .. } => slice::ref_slice(target).into_cow(),
526         }
527     }
528
529     // FIXME: no mootable cow. I’m honestly not sure what a “cow” between `&mut [BasicBlock]` and
530     // `Vec<&mut BasicBlock>` would look like in the first place.
531     pub fn successors_mut(&mut self) -> Vec<&mut BasicBlock> {
532         use self::TerminatorKind::*;
533         match *self {
534             Goto { target: ref mut b } => vec![b],
535             If { targets: (ref mut b1, ref mut b2), .. } => vec![b1, b2],
536             Switch { targets: ref mut b, .. } => b.iter_mut().collect(),
537             SwitchInt { targets: ref mut b, .. } => b.iter_mut().collect(),
538             Resume => Vec::new(),
539             Return => Vec::new(),
540             Unreachable => Vec::new(),
541             Call { destination: Some((_, ref mut t)), cleanup: Some(ref mut c), .. } => vec![t, c],
542             Call { destination: Some((_, ref mut t)), cleanup: None, .. } => vec![t],
543             Call { destination: None, cleanup: Some(ref mut c), .. } => vec![c],
544             Call { destination: None, cleanup: None, .. } => vec![],
545             DropAndReplace { ref mut target, unwind: Some(ref mut unwind), .. } |
546             Drop { ref mut target, unwind: Some(ref mut unwind), .. } => vec![target, unwind],
547             DropAndReplace { ref mut target, unwind: None, .. } |
548             Drop { ref mut target, unwind: None, .. } => {
549                 vec![target]
550             }
551             Assert { ref mut target, cleanup: Some(ref mut unwind), .. } => vec![target, unwind],
552             Assert { ref mut target, .. } => vec![target]
553         }
554     }
555 }
556
557 impl<'tcx> BasicBlockData<'tcx> {
558     pub fn new(terminator: Option<Terminator<'tcx>>) -> BasicBlockData<'tcx> {
559         BasicBlockData {
560             statements: vec![],
561             terminator: terminator,
562             is_cleanup: false,
563         }
564     }
565
566     /// Accessor for terminator.
567     ///
568     /// Terminator may not be None after construction of the basic block is complete. This accessor
569     /// provides a convenience way to reach the terminator.
570     pub fn terminator(&self) -> &Terminator<'tcx> {
571         self.terminator.as_ref().expect("invalid terminator state")
572     }
573
574     pub fn terminator_mut(&mut self) -> &mut Terminator<'tcx> {
575         self.terminator.as_mut().expect("invalid terminator state")
576     }
577 }
578
579 impl<'tcx> Debug for TerminatorKind<'tcx> {
580     fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
581         self.fmt_head(fmt)?;
582         let successors = self.successors();
583         let labels = self.fmt_successor_labels();
584         assert_eq!(successors.len(), labels.len());
585
586         match successors.len() {
587             0 => Ok(()),
588
589             1 => write!(fmt, " -> {:?}", successors[0]),
590
591             _ => {
592                 write!(fmt, " -> [")?;
593                 for (i, target) in successors.iter().enumerate() {
594                     if i > 0 {
595                         write!(fmt, ", ")?;
596                     }
597                     write!(fmt, "{}: {:?}", labels[i], target)?;
598                 }
599                 write!(fmt, "]")
600             }
601
602         }
603     }
604 }
605
606 impl<'tcx> TerminatorKind<'tcx> {
607     /// Write the "head" part of the terminator; that is, its name and the data it uses to pick the
608     /// successor basic block, if any. The only information not inlcuded is the list of possible
609     /// successors, which may be rendered differently between the text and the graphviz format.
610     pub fn fmt_head<W: Write>(&self, fmt: &mut W) -> fmt::Result {
611         use self::TerminatorKind::*;
612         match *self {
613             Goto { .. } => write!(fmt, "goto"),
614             If { cond: ref lv, .. } => write!(fmt, "if({:?})", lv),
615             Switch { discr: ref lv, .. } => write!(fmt, "switch({:?})", lv),
616             SwitchInt { discr: ref lv, .. } => write!(fmt, "switchInt({:?})", lv),
617             Return => write!(fmt, "return"),
618             Resume => write!(fmt, "resume"),
619             Unreachable => write!(fmt, "unreachable"),
620             Drop { ref location, .. } => write!(fmt, "drop({:?})", location),
621             DropAndReplace { ref location, ref value, .. } =>
622                 write!(fmt, "replace({:?} <- {:?})", location, value),
623             Call { ref func, ref args, ref destination, .. } => {
624                 if let Some((ref destination, _)) = *destination {
625                     write!(fmt, "{:?} = ", destination)?;
626                 }
627                 write!(fmt, "{:?}(", func)?;
628                 for (index, arg) in args.iter().enumerate() {
629                     if index > 0 {
630                         write!(fmt, ", ")?;
631                     }
632                     write!(fmt, "{:?}", arg)?;
633                 }
634                 write!(fmt, ")")
635             }
636             Assert { ref cond, expected, ref msg, .. } => {
637                 write!(fmt, "assert(")?;
638                 if !expected {
639                     write!(fmt, "!")?;
640                 }
641                 write!(fmt, "{:?}, ", cond)?;
642
643                 match *msg {
644                     AssertMessage::BoundsCheck { ref len, ref index } => {
645                         write!(fmt, "{:?}, {:?}, {:?}",
646                                "index out of bounds: the len is {} but the index is {}",
647                                len, index)?;
648                     }
649                     AssertMessage::Math(ref err) => {
650                         write!(fmt, "{:?}", err.description())?;
651                     }
652                 }
653
654                 write!(fmt, ")")
655             }
656         }
657     }
658
659     /// Return the list of labels for the edges to the successor basic blocks.
660     pub fn fmt_successor_labels(&self) -> Vec<Cow<'static, str>> {
661         use self::TerminatorKind::*;
662         match *self {
663             Return | Resume | Unreachable => vec![],
664             Goto { .. } => vec!["".into()],
665             If { .. } => vec!["true".into(), "false".into()],
666             Switch { ref adt_def, .. } => {
667                 adt_def.variants
668                        .iter()
669                        .map(|variant| variant.name.to_string().into())
670                        .collect()
671             }
672             SwitchInt { ref values, .. } => {
673                 values.iter()
674                       .map(|const_val| {
675                           let mut buf = String::new();
676                           fmt_const_val(&mut buf, const_val).unwrap();
677                           buf.into()
678                       })
679                       .chain(iter::once(String::from("otherwise").into()))
680                       .collect()
681             }
682             Call { destination: Some(_), cleanup: Some(_), .. } =>
683                 vec!["return".into_cow(), "unwind".into_cow()],
684             Call { destination: Some(_), cleanup: None, .. } => vec!["return".into_cow()],
685             Call { destination: None, cleanup: Some(_), .. } => vec!["unwind".into_cow()],
686             Call { destination: None, cleanup: None, .. } => vec![],
687             DropAndReplace { unwind: None, .. } |
688             Drop { unwind: None, .. } => vec!["return".into_cow()],
689             DropAndReplace { unwind: Some(_), .. } |
690             Drop { unwind: Some(_), .. } => {
691                 vec!["return".into_cow(), "unwind".into_cow()]
692             }
693             Assert { cleanup: None, .. } => vec!["".into()],
694             Assert { .. } =>
695                 vec!["success".into_cow(), "unwind".into_cow()]
696         }
697     }
698 }
699
700 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
701 pub enum AssertMessage<'tcx> {
702     BoundsCheck {
703         len: Operand<'tcx>,
704         index: Operand<'tcx>
705     },
706     Math(ConstMathErr)
707 }
708
709 ///////////////////////////////////////////////////////////////////////////
710 // Statements
711
712 #[derive(Clone, RustcEncodable, RustcDecodable)]
713 pub struct Statement<'tcx> {
714     pub source_info: SourceInfo,
715     pub kind: StatementKind<'tcx>,
716 }
717
718 impl<'tcx> Statement<'tcx> {
719     /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
720     /// invalidating statement indices in `Location`s.
721     pub fn make_nop(&mut self) {
722         self.kind = StatementKind::Nop
723     }
724 }
725
726 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
727 pub enum StatementKind<'tcx> {
728     /// Write the RHS Rvalue to the LHS Lvalue.
729     Assign(Lvalue<'tcx>, Rvalue<'tcx>),
730
731     /// Write the discriminant for a variant to the enum Lvalue.
732     SetDiscriminant { lvalue: Lvalue<'tcx>, variant_index: usize },
733
734     /// Start a live range for the storage of the local.
735     StorageLive(Lvalue<'tcx>),
736
737     /// End the current live range for the storage of the local.
738     StorageDead(Lvalue<'tcx>),
739
740     /// No-op. Useful for deleting instructions without affecting statement indices.
741     Nop,
742 }
743
744 impl<'tcx> Debug for Statement<'tcx> {
745     fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
746         use self::StatementKind::*;
747         match self.kind {
748             Assign(ref lv, ref rv) => write!(fmt, "{:?} = {:?}", lv, rv),
749             StorageLive(ref lv) => write!(fmt, "StorageLive({:?})", lv),
750             StorageDead(ref lv) => write!(fmt, "StorageDead({:?})", lv),
751             SetDiscriminant{lvalue: ref lv, variant_index: index} => {
752                 write!(fmt, "discriminant({:?}) = {:?}", lv, index)
753             }
754             Nop => write!(fmt, "nop"),
755         }
756     }
757 }
758
759 ///////////////////////////////////////////////////////////////////////////
760 // Lvalues
761
762 newtype_index!(Var, "var");
763 newtype_index!(Temp, "tmp");
764 newtype_index!(Arg, "arg");
765 newtype_index!(Local, "local");
766
767 /// A path to a value; something that can be evaluated without
768 /// changing or disturbing program state.
769 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable)]
770 pub enum Lvalue<'tcx> {
771     /// local variable declared by the user
772     Var(Var),
773
774     /// temporary introduced during lowering into MIR
775     Temp(Temp),
776
777     /// formal parameter of the function; note that these are NOT the
778     /// bindings that the user declares, which are vars
779     Arg(Arg),
780
781     /// static or static mut variable
782     Static(DefId),
783
784     /// the return pointer of the fn
785     ReturnPointer,
786
787     /// projection out of an lvalue (access a field, deref a pointer, etc)
788     Projection(Box<LvalueProjection<'tcx>>),
789 }
790
791 /// The `Projection` data structure defines things of the form `B.x`
792 /// or `*B` or `B[index]`. Note that it is parameterized because it is
793 /// shared between `Constant` and `Lvalue`. See the aliases
794 /// `LvalueProjection` etc below.
795 #[derive(Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
796 pub struct Projection<'tcx, B, V> {
797     pub base: B,
798     pub elem: ProjectionElem<'tcx, V>,
799 }
800
801 #[derive(Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
802 pub enum ProjectionElem<'tcx, V> {
803     Deref,
804     Field(Field, Ty<'tcx>),
805     Index(V),
806
807     /// These indices are generated by slice patterns. Easiest to explain
808     /// by example:
809     ///
810     /// ```
811     /// [X, _, .._, _, _] => { offset: 0, min_length: 4, from_end: false },
812     /// [_, X, .._, _, _] => { offset: 1, min_length: 4, from_end: false },
813     /// [_, _, .._, X, _] => { offset: 2, min_length: 4, from_end: true },
814     /// [_, _, .._, _, X] => { offset: 1, min_length: 4, from_end: true },
815     /// ```
816     ConstantIndex {
817         /// index or -index (in Python terms), depending on from_end
818         offset: u32,
819         /// thing being indexed must be at least this long
820         min_length: u32,
821         /// counting backwards from end?
822         from_end: bool,
823     },
824
825     /// These indices are generated by slice patterns.
826     ///
827     /// slice[from:-to] in Python terms.
828     Subslice {
829         from: u32,
830         to: u32,
831     },
832
833     /// "Downcast" to a variant of an ADT. Currently, we only introduce
834     /// this for ADTs with more than one variant. It may be better to
835     /// just introduce it always, or always for enums.
836     Downcast(AdtDef<'tcx>, usize),
837 }
838
839 /// Alias for projections as they appear in lvalues, where the base is an lvalue
840 /// and the index is an operand.
841 pub type LvalueProjection<'tcx> = Projection<'tcx, Lvalue<'tcx>, Operand<'tcx>>;
842
843 /// Alias for projections as they appear in lvalues, where the base is an lvalue
844 /// and the index is an operand.
845 pub type LvalueElem<'tcx> = ProjectionElem<'tcx, Operand<'tcx>>;
846
847 newtype_index!(Field, "field");
848
849 impl<'tcx> Lvalue<'tcx> {
850     pub fn field(self, f: Field, ty: Ty<'tcx>) -> Lvalue<'tcx> {
851         self.elem(ProjectionElem::Field(f, ty))
852     }
853
854     pub fn deref(self) -> Lvalue<'tcx> {
855         self.elem(ProjectionElem::Deref)
856     }
857
858     pub fn index(self, index: Operand<'tcx>) -> Lvalue<'tcx> {
859         self.elem(ProjectionElem::Index(index))
860     }
861
862     pub fn elem(self, elem: LvalueElem<'tcx>) -> Lvalue<'tcx> {
863         Lvalue::Projection(Box::new(LvalueProjection {
864             base: self,
865             elem: elem,
866         }))
867     }
868
869     pub fn from_local(mir: &Mir<'tcx>, local: Local) -> Lvalue<'tcx> {
870         let mut index = local.index();
871         index = match index.checked_sub(mir.arg_decls.len()) {
872             None => return Lvalue::Arg(Arg(index as u32)),
873             Some(index) => index,
874         };
875         index = match index.checked_sub(mir.var_decls.len()) {
876             None => return Lvalue::Var(Var(index as u32)),
877             Some(index) => index,
878         };
879         index = match index.checked_sub(mir.temp_decls.len()) {
880             None => return Lvalue::Temp(Temp(index as u32)),
881             Some(index) => index,
882         };
883         debug_assert!(index == 0);
884         Lvalue::ReturnPointer
885     }
886 }
887
888 impl<'tcx> Debug for Lvalue<'tcx> {
889     fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
890         use self::Lvalue::*;
891
892         match *self {
893             Var(id) => write!(fmt, "{:?}", id),
894             Arg(id) => write!(fmt, "{:?}", id),
895             Temp(id) => write!(fmt, "{:?}", id),
896             Static(def_id) =>
897                 write!(fmt, "{}", ty::tls::with(|tcx| tcx.item_path_str(def_id))),
898             ReturnPointer =>
899                 write!(fmt, "return"),
900             Projection(ref data) =>
901                 match data.elem {
902                     ProjectionElem::Downcast(ref adt_def, index) =>
903                         write!(fmt, "({:?} as {})", data.base, adt_def.variants[index].name),
904                     ProjectionElem::Deref =>
905                         write!(fmt, "(*{:?})", data.base),
906                     ProjectionElem::Field(field, ty) =>
907                         write!(fmt, "({:?}.{:?}: {:?})", data.base, field.index(), ty),
908                     ProjectionElem::Index(ref index) =>
909                         write!(fmt, "{:?}[{:?}]", data.base, index),
910                     ProjectionElem::ConstantIndex { offset, min_length, from_end: false } =>
911                         write!(fmt, "{:?}[{:?} of {:?}]", data.base, offset, min_length),
912                     ProjectionElem::ConstantIndex { offset, min_length, from_end: true } =>
913                         write!(fmt, "{:?}[-{:?} of {:?}]", data.base, offset, min_length),
914                     ProjectionElem::Subslice { from, to } if to == 0 =>
915                         write!(fmt, "{:?}[{:?}:", data.base, from),
916                     ProjectionElem::Subslice { from, to } if from == 0 =>
917                         write!(fmt, "{:?}[:-{:?}]", data.base, to),
918                     ProjectionElem::Subslice { from, to } =>
919                         write!(fmt, "{:?}[{:?}:-{:?}]", data.base,
920                                from, to),
921
922                 },
923         }
924     }
925 }
926
927 ///////////////////////////////////////////////////////////////////////////
928 // Scopes
929
930 newtype_index!(VisibilityScope, "scope");
931 pub const ARGUMENT_VISIBILITY_SCOPE : VisibilityScope = VisibilityScope(0);
932
933 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
934 pub struct VisibilityScopeData {
935     pub span: Span,
936     pub parent_scope: Option<VisibilityScope>,
937 }
938
939 ///////////////////////////////////////////////////////////////////////////
940 // Operands
941
942 /// These are values that can appear inside an rvalue (or an index
943 /// lvalue). They are intentionally limited to prevent rvalues from
944 /// being nested in one another.
945 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable)]
946 pub enum Operand<'tcx> {
947     Consume(Lvalue<'tcx>),
948     Constant(Constant<'tcx>),
949 }
950
951 impl<'tcx> Debug for Operand<'tcx> {
952     fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
953         use self::Operand::*;
954         match *self {
955             Constant(ref a) => write!(fmt, "{:?}", a),
956             Consume(ref lv) => write!(fmt, "{:?}", lv),
957         }
958     }
959 }
960
961 ///////////////////////////////////////////////////////////////////////////
962 /// Rvalues
963
964 #[derive(Clone, RustcEncodable, RustcDecodable)]
965 pub enum Rvalue<'tcx> {
966     /// x (either a move or copy, depending on type of x)
967     Use(Operand<'tcx>),
968
969     /// [x; 32]
970     Repeat(Operand<'tcx>, TypedConstVal<'tcx>),
971
972     /// &x or &mut x
973     Ref(&'tcx Region, BorrowKind, Lvalue<'tcx>),
974
975     /// length of a [X] or [X;n] value
976     Len(Lvalue<'tcx>),
977
978     Cast(CastKind, Operand<'tcx>, Ty<'tcx>),
979
980     BinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
981     CheckedBinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
982
983     UnaryOp(UnOp, Operand<'tcx>),
984
985     /// Creates an *uninitialized* Box
986     Box(Ty<'tcx>),
987
988     /// Create an aggregate value, like a tuple or struct.  This is
989     /// only needed because we want to distinguish `dest = Foo { x:
990     /// ..., y: ... }` from `dest.x = ...; dest.y = ...;` in the case
991     /// that `Foo` has a destructor. These rvalues can be optimized
992     /// away after type-checking and before lowering.
993     Aggregate(AggregateKind<'tcx>, Vec<Operand<'tcx>>),
994
995     InlineAsm {
996         asm: InlineAsm,
997         outputs: Vec<Lvalue<'tcx>>,
998         inputs: Vec<Operand<'tcx>>
999     }
1000 }
1001
1002 #[derive(Clone, Copy, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
1003 pub enum CastKind {
1004     Misc,
1005
1006     /// Convert unique, zero-sized type for a fn to fn()
1007     ReifyFnPointer,
1008
1009     /// Convert safe fn() to unsafe fn()
1010     UnsafeFnPointer,
1011
1012     /// "Unsize" -- convert a thin-or-fat pointer to a fat pointer.
1013     /// trans must figure out the details once full monomorphization
1014     /// is known. For example, this could be used to cast from a
1015     /// `&[i32;N]` to a `&[i32]`, or a `Box<T>` to a `Box<Trait>`
1016     /// (presuming `T: Trait`).
1017     Unsize,
1018 }
1019
1020 #[derive(Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
1021 pub enum AggregateKind<'tcx> {
1022     Vec,
1023     Tuple,
1024     /// The second field is variant number (discriminant), it's equal to 0
1025     /// for struct and union expressions. The fourth field is active field
1026     /// number and is present only for union expressions.
1027     Adt(AdtDef<'tcx>, usize, &'tcx Substs<'tcx>, Option<usize>),
1028     Closure(DefId, ClosureSubsts<'tcx>),
1029 }
1030
1031 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
1032 pub enum BinOp {
1033     /// The `+` operator (addition)
1034     Add,
1035     /// The `-` operator (subtraction)
1036     Sub,
1037     /// The `*` operator (multiplication)
1038     Mul,
1039     /// The `/` operator (division)
1040     Div,
1041     /// The `%` operator (modulus)
1042     Rem,
1043     /// The `^` operator (bitwise xor)
1044     BitXor,
1045     /// The `&` operator (bitwise and)
1046     BitAnd,
1047     /// The `|` operator (bitwise or)
1048     BitOr,
1049     /// The `<<` operator (shift left)
1050     Shl,
1051     /// The `>>` operator (shift right)
1052     Shr,
1053     /// The `==` operator (equality)
1054     Eq,
1055     /// The `<` operator (less than)
1056     Lt,
1057     /// The `<=` operator (less than or equal to)
1058     Le,
1059     /// The `!=` operator (not equal to)
1060     Ne,
1061     /// The `>=` operator (greater than or equal to)
1062     Ge,
1063     /// The `>` operator (greater than)
1064     Gt,
1065 }
1066
1067 impl BinOp {
1068     pub fn is_checkable(self) -> bool {
1069         use self::BinOp::*;
1070         match self {
1071             Add | Sub | Mul | Shl | Shr => true,
1072             _ => false
1073         }
1074     }
1075 }
1076
1077 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
1078 pub enum UnOp {
1079     /// The `!` operator for logical inversion
1080     Not,
1081     /// The `-` operator for negation
1082     Neg,
1083 }
1084
1085 impl<'tcx> Debug for Rvalue<'tcx> {
1086     fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
1087         use self::Rvalue::*;
1088
1089         match *self {
1090             Use(ref lvalue) => write!(fmt, "{:?}", lvalue),
1091             Repeat(ref a, ref b) => write!(fmt, "[{:?}; {:?}]", a, b),
1092             Len(ref a) => write!(fmt, "Len({:?})", a),
1093             Cast(ref kind, ref lv, ref ty) => write!(fmt, "{:?} as {:?} ({:?})", lv, ty, kind),
1094             BinaryOp(ref op, ref a, ref b) => write!(fmt, "{:?}({:?}, {:?})", op, a, b),
1095             CheckedBinaryOp(ref op, ref a, ref b) => {
1096                 write!(fmt, "Checked{:?}({:?}, {:?})", op, a, b)
1097             }
1098             UnaryOp(ref op, ref a) => write!(fmt, "{:?}({:?})", op, a),
1099             Box(ref t) => write!(fmt, "Box({:?})", t),
1100             InlineAsm { ref asm, ref outputs, ref inputs } => {
1101                 write!(fmt, "asm!({:?} : {:?} : {:?})", asm, outputs, inputs)
1102             }
1103
1104             Ref(_, borrow_kind, ref lv) => {
1105                 let kind_str = match borrow_kind {
1106                     BorrowKind::Shared => "",
1107                     BorrowKind::Mut | BorrowKind::Unique => "mut ",
1108                 };
1109                 write!(fmt, "&{}{:?}", kind_str, lv)
1110             }
1111
1112             Aggregate(ref kind, ref lvs) => {
1113                 use self::AggregateKind::*;
1114
1115                 fn fmt_tuple(fmt: &mut Formatter, lvs: &[Operand]) -> fmt::Result {
1116                     let mut tuple_fmt = fmt.debug_tuple("");
1117                     for lv in lvs {
1118                         tuple_fmt.field(lv);
1119                     }
1120                     tuple_fmt.finish()
1121                 }
1122
1123                 match *kind {
1124                     Vec => write!(fmt, "{:?}", lvs),
1125
1126                     Tuple => {
1127                         match lvs.len() {
1128                             0 => write!(fmt, "()"),
1129                             1 => write!(fmt, "({:?},)", lvs[0]),
1130                             _ => fmt_tuple(fmt, lvs),
1131                         }
1132                     }
1133
1134                     Adt(adt_def, variant, substs, _) => {
1135                         let variant_def = &adt_def.variants[variant];
1136
1137                         ppaux::parameterized(fmt, substs, variant_def.did,
1138                                              ppaux::Ns::Value, &[])?;
1139
1140                         match variant_def.kind {
1141                             ty::VariantKind::Unit => Ok(()),
1142                             ty::VariantKind::Tuple => fmt_tuple(fmt, lvs),
1143                             ty::VariantKind::Struct => {
1144                                 let mut struct_fmt = fmt.debug_struct("");
1145                                 for (field, lv) in variant_def.fields.iter().zip(lvs) {
1146                                     struct_fmt.field(&field.name.as_str(), lv);
1147                                 }
1148                                 struct_fmt.finish()
1149                             }
1150                         }
1151                     }
1152
1153                     Closure(def_id, _) => ty::tls::with(|tcx| {
1154                         if let Some(node_id) = tcx.map.as_local_node_id(def_id) {
1155                             let name = format!("[closure@{:?}]", tcx.map.span(node_id));
1156                             let mut struct_fmt = fmt.debug_struct(&name);
1157
1158                             tcx.with_freevars(node_id, |freevars| {
1159                                 for (freevar, lv) in freevars.iter().zip(lvs) {
1160                                     let def_id = freevar.def.def_id();
1161                                     let var_id = tcx.map.as_local_node_id(def_id).unwrap();
1162                                     let var_name = tcx.local_var_name_str(var_id);
1163                                     struct_fmt.field(&var_name, lv);
1164                                 }
1165                             });
1166
1167                             struct_fmt.finish()
1168                         } else {
1169                             write!(fmt, "[closure]")
1170                         }
1171                     }),
1172                 }
1173             }
1174         }
1175     }
1176 }
1177
1178 ///////////////////////////////////////////////////////////////////////////
1179 /// Constants
1180 ///
1181 /// Two constants are equal if they are the same constant. Note that
1182 /// this does not necessarily mean that they are "==" in Rust -- in
1183 /// particular one must be wary of `NaN`!
1184
1185 #[derive(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1186 pub struct Constant<'tcx> {
1187     pub span: Span,
1188     pub ty: Ty<'tcx>,
1189     pub literal: Literal<'tcx>,
1190 }
1191
1192 #[derive(Clone, RustcEncodable, RustcDecodable)]
1193 pub struct TypedConstVal<'tcx> {
1194     pub ty: Ty<'tcx>,
1195     pub span: Span,
1196     pub value: ConstUsize,
1197 }
1198
1199 impl<'tcx> Debug for TypedConstVal<'tcx> {
1200     fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
1201         write!(fmt, "const {}", ConstInt::Usize(self.value))
1202     }
1203 }
1204
1205 newtype_index!(Promoted, "promoted");
1206
1207 #[derive(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1208 pub enum Literal<'tcx> {
1209     Item {
1210         def_id: DefId,
1211         substs: &'tcx Substs<'tcx>,
1212     },
1213     Value {
1214         value: ConstVal,
1215     },
1216     Promoted {
1217         // Index into the `promoted` vector of `Mir`.
1218         index: Promoted
1219     },
1220 }
1221
1222 impl<'tcx> Debug for Constant<'tcx> {
1223     fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
1224         write!(fmt, "{:?}", self.literal)
1225     }
1226 }
1227
1228 impl<'tcx> Debug for Literal<'tcx> {
1229     fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
1230         use self::Literal::*;
1231         match *self {
1232             Item { def_id, substs } => {
1233                 ppaux::parameterized(fmt, substs, def_id, ppaux::Ns::Value, &[])
1234             }
1235             Value { ref value } => {
1236                 write!(fmt, "const ")?;
1237                 fmt_const_val(fmt, value)
1238             }
1239             Promoted { index } => {
1240                 write!(fmt, "{:?}", index)
1241             }
1242         }
1243     }
1244 }
1245
1246 /// Write a `ConstVal` in a way closer to the original source code than the `Debug` output.
1247 fn fmt_const_val<W: Write>(fmt: &mut W, const_val: &ConstVal) -> fmt::Result {
1248     use middle::const_val::ConstVal::*;
1249     match *const_val {
1250         Float(f) => write!(fmt, "{:?}", f),
1251         Integral(n) => write!(fmt, "{}", n),
1252         Str(ref s) => write!(fmt, "{:?}", s),
1253         ByteStr(ref bytes) => {
1254             let escaped: String = bytes
1255                 .iter()
1256                 .flat_map(|&ch| ascii::escape_default(ch).map(|c| c as char))
1257                 .collect();
1258             write!(fmt, "b\"{}\"", escaped)
1259         }
1260         Bool(b) => write!(fmt, "{:?}", b),
1261         Function(def_id) => write!(fmt, "{}", item_path_str(def_id)),
1262         Struct(node_id) | Tuple(node_id) | Array(node_id, _) | Repeat(node_id, _) =>
1263             write!(fmt, "{}", node_to_string(node_id)),
1264         Char(c) => write!(fmt, "{:?}", c),
1265         Dummy => bug!(),
1266     }
1267 }
1268
1269 fn node_to_string(node_id: ast::NodeId) -> String {
1270     ty::tls::with(|tcx| tcx.map.node_to_user_string(node_id))
1271 }
1272
1273 fn item_path_str(def_id: DefId) -> String {
1274     ty::tls::with(|tcx| tcx.item_path_str(def_id))
1275 }
1276
1277 impl<'tcx> ControlFlowGraph for Mir<'tcx> {
1278
1279     type Node = BasicBlock;
1280
1281     fn num_nodes(&self) -> usize { self.basic_blocks.len() }
1282
1283     fn start_node(&self) -> Self::Node { START_BLOCK }
1284
1285     fn predecessors<'graph>(&'graph self, node: Self::Node)
1286                             -> <Self as GraphPredecessors<'graph>>::Iter
1287     {
1288         self.predecessors_for(node).clone().into_iter()
1289     }
1290     fn successors<'graph>(&'graph self, node: Self::Node)
1291                           -> <Self as GraphSuccessors<'graph>>::Iter
1292     {
1293         self.basic_blocks[node].terminator().successors().into_owned().into_iter()
1294     }
1295 }
1296
1297 impl<'a, 'b> GraphPredecessors<'b> for Mir<'a> {
1298     type Item = BasicBlock;
1299     type Iter = IntoIter<BasicBlock>;
1300 }
1301
1302 impl<'a, 'b>  GraphSuccessors<'b> for Mir<'a> {
1303     type Item = BasicBlock;
1304     type Iter = IntoIter<BasicBlock>;
1305 }
1306
1307 #[derive(Copy, Clone, PartialEq, Eq, Hash, Ord, PartialOrd)]
1308 pub struct Location {
1309     /// the location is within this block
1310     pub block: BasicBlock,
1311
1312     /// the location is the start of the this statement; or, if `statement_index`
1313     /// == num-statements, then the start of the terminator.
1314     pub statement_index: usize,
1315 }
1316
1317 impl fmt::Debug for Location {
1318     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1319         write!(fmt, "{:?}[{}]", self.block, self.statement_index)
1320     }
1321 }
1322
1323 impl Location {
1324     pub fn dominates(&self, other: &Location, dominators: &Dominators<BasicBlock>) -> bool {
1325         if self.block == other.block {
1326             self.statement_index <= other.statement_index
1327         } else {
1328             dominators.is_dominated_by(other.block, self.block)
1329         }
1330     }
1331 }