]> git.lizzy.rs Git - rust.git/blob - src/librustc/mir/mod.rs
Refactor: {Lvalue,Rvalue,Operand}::ty only need the locals' types, not the full &Mir
[rust.git] / src / librustc / mir / mod.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 //! MIR datatypes and passes. See [the README](README.md) for details.
12
13 use graphviz::IntoCow;
14 use middle::const_val::ConstVal;
15 use middle::region::CodeExtent;
16 use rustc_const_math::{ConstUsize, ConstInt, ConstMathErr};
17 use rustc_data_structures::indexed_vec::{IndexVec, Idx};
18 use rustc_data_structures::control_flow_graph::dominators::{Dominators, dominators};
19 use rustc_data_structures::control_flow_graph::{GraphPredecessors, GraphSuccessors};
20 use rustc_data_structures::control_flow_graph::ControlFlowGraph;
21 use hir::def::CtorKind;
22 use hir::def_id::DefId;
23 use ty::subst::{Subst, Substs};
24 use ty::{self, AdtDef, ClosureSubsts, Region, Ty};
25 use ty::fold::{TypeFoldable, TypeFolder, TypeVisitor};
26 use util::ppaux;
27 use rustc_back::slice;
28 use hir::InlineAsm;
29 use std::ascii;
30 use std::borrow::{Cow};
31 use std::cell::Ref;
32 use std::fmt::{self, Debug, Formatter, Write};
33 use std::{iter, u32};
34 use std::ops::{Index, IndexMut};
35 use std::vec::IntoIter;
36 use syntax::ast::Name;
37 use syntax_pos::Span;
38
39 mod cache;
40 pub mod tcx;
41 pub mod visit;
42 pub mod transform;
43 pub mod traversal;
44
45 macro_rules! newtype_index {
46     ($name:ident, $debug_name:expr) => (
47         #[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord,
48          RustcEncodable, RustcDecodable)]
49         pub struct $name(u32);
50
51         impl Idx for $name {
52             fn new(value: usize) -> Self {
53                 assert!(value < (u32::MAX) as usize);
54                 $name(value as u32)
55             }
56             fn index(self) -> usize {
57                 self.0 as usize
58             }
59         }
60
61         impl Debug for $name {
62             fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
63                 write!(fmt, "{}{}", $debug_name, self.0)
64             }
65         }
66     )
67 }
68
69 /// Types for locals
70 type LocalDecls<'tcx> = IndexVec<Local, LocalDecl<'tcx>>;
71
72 /// Lowered representation of a single function.
73 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
74 pub struct Mir<'tcx> {
75     /// List of basic blocks. References to basic block use a newtyped index type `BasicBlock`
76     /// that indexes into this vector.
77     basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
78
79     /// List of visibility (lexical) scopes; these are referenced by statements
80     /// and used (eventually) for debuginfo. Indexed by a `VisibilityScope`.
81     pub visibility_scopes: IndexVec<VisibilityScope, VisibilityScopeData>,
82
83     /// Rvalues promoted from this function, such as borrows of constants.
84     /// Each of them is the Mir of a constant with the fn's type parameters
85     /// in scope, but a separate set of locals.
86     pub promoted: IndexVec<Promoted, Mir<'tcx>>,
87
88     /// Return type of the function.
89     pub return_ty: Ty<'tcx>,
90
91     /// Declarations of locals.
92     ///
93     /// The first local is the return value pointer, followed by `arg_count`
94     /// locals for the function arguments, followed by any user-declared
95     /// variables and temporaries.
96     pub local_decls: LocalDecls<'tcx>,
97
98     /// Number of arguments this function takes.
99     ///
100     /// Starting at local 1, `arg_count` locals will be provided by the caller
101     /// and can be assumed to be initialized.
102     ///
103     /// If this MIR was built for a constant, this will be 0.
104     pub arg_count: usize,
105
106     /// Names and capture modes of all the closure upvars, assuming
107     /// the first argument is either the closure or a reference to it.
108     pub upvar_decls: Vec<UpvarDecl>,
109
110     /// Mark an argument local (which must be a tuple) as getting passed as
111     /// its individual components at the LLVM level.
112     ///
113     /// This is used for the "rust-call" ABI.
114     pub spread_arg: Option<Local>,
115
116     /// A span representing this MIR, for error reporting
117     pub span: Span,
118
119     /// A cache for various calculations
120     cache: cache::Cache
121 }
122
123 /// where execution begins
124 pub const START_BLOCK: BasicBlock = BasicBlock(0);
125
126 impl<'tcx> Mir<'tcx> {
127     pub fn new(basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
128                visibility_scopes: IndexVec<VisibilityScope, VisibilityScopeData>,
129                promoted: IndexVec<Promoted, Mir<'tcx>>,
130                return_ty: Ty<'tcx>,
131                local_decls: IndexVec<Local, LocalDecl<'tcx>>,
132                arg_count: usize,
133                upvar_decls: Vec<UpvarDecl>,
134                span: Span) -> Self
135     {
136         // We need `arg_count` locals, and one for the return pointer
137         assert!(local_decls.len() >= arg_count + 1,
138             "expected at least {} locals, got {}", arg_count + 1, local_decls.len());
139         assert_eq!(local_decls[RETURN_POINTER].ty, return_ty);
140
141         Mir {
142             basic_blocks,
143             visibility_scopes,
144             promoted,
145             return_ty,
146             local_decls,
147             arg_count,
148             upvar_decls,
149             spread_arg: None,
150             span,
151             cache: cache::Cache::new()
152         }
153     }
154
155     #[inline]
156     pub fn basic_blocks(&self) -> &IndexVec<BasicBlock, BasicBlockData<'tcx>> {
157         &self.basic_blocks
158     }
159
160     #[inline]
161     pub fn basic_blocks_mut(&mut self) -> &mut IndexVec<BasicBlock, BasicBlockData<'tcx>> {
162         self.cache.invalidate();
163         &mut self.basic_blocks
164     }
165
166     #[inline]
167     pub fn predecessors(&self) -> Ref<IndexVec<BasicBlock, Vec<BasicBlock>>> {
168         self.cache.predecessors(self)
169     }
170
171     #[inline]
172     pub fn predecessors_for(&self, bb: BasicBlock) -> Ref<Vec<BasicBlock>> {
173         Ref::map(self.predecessors(), |p| &p[bb])
174     }
175
176     #[inline]
177     pub fn dominators(&self) -> Dominators<BasicBlock> {
178         dominators(self)
179     }
180
181     #[inline]
182     pub fn local_kind(&self, local: Local) -> LocalKind {
183         let index = local.0 as usize;
184         if index == 0 {
185             debug_assert!(self.local_decls[local].mutability == Mutability::Mut,
186                           "return pointer should be mutable");
187
188             LocalKind::ReturnPointer
189         } else if index < self.arg_count + 1 {
190             LocalKind::Arg
191         } else if self.local_decls[local].name.is_some() {
192             LocalKind::Var
193         } else {
194             debug_assert!(self.local_decls[local].mutability == Mutability::Mut,
195                           "temp should be mutable");
196
197             LocalKind::Temp
198         }
199     }
200
201     /// Returns an iterator over all temporaries.
202     #[inline]
203     pub fn temps_iter<'a>(&'a self) -> impl Iterator<Item=Local> + 'a {
204         (self.arg_count+1..self.local_decls.len()).filter_map(move |index| {
205             let local = Local::new(index);
206             if self.local_decls[local].is_user_variable {
207                 None
208             } else {
209                 Some(local)
210             }
211         })
212     }
213
214     /// Returns an iterator over all user-declared locals.
215     #[inline]
216     pub fn vars_iter<'a>(&'a self) -> impl Iterator<Item=Local> + 'a {
217         (self.arg_count+1..self.local_decls.len()).filter_map(move |index| {
218             let local = Local::new(index);
219             if self.local_decls[local].is_user_variable {
220                 Some(local)
221             } else {
222                 None
223             }
224         })
225     }
226
227     /// Returns an iterator over all function arguments.
228     #[inline]
229     pub fn args_iter(&self) -> impl Iterator<Item=Local> {
230         let arg_count = self.arg_count;
231         (1..arg_count+1).map(Local::new)
232     }
233
234     /// Returns an iterator over all user-defined variables and compiler-generated temporaries (all
235     /// locals that are neither arguments nor the return pointer).
236     #[inline]
237     pub fn vars_and_temps_iter(&self) -> impl Iterator<Item=Local> {
238         let arg_count = self.arg_count;
239         let local_count = self.local_decls.len();
240         (arg_count+1..local_count).map(Local::new)
241     }
242
243     /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
244     /// invalidating statement indices in `Location`s.
245     pub fn make_statement_nop(&mut self, location: Location) {
246         let block = &mut self[location.block];
247         debug_assert!(location.statement_index < block.statements.len());
248         block.statements[location.statement_index].make_nop()
249     }
250 }
251
252 impl_stable_hash_for!(struct Mir<'tcx> {
253     basic_blocks,
254     visibility_scopes,
255     promoted,
256     return_ty,
257     local_decls,
258     arg_count,
259     upvar_decls,
260     spread_arg,
261     span,
262     cache
263 });
264
265 impl<'tcx> Index<BasicBlock> for Mir<'tcx> {
266     type Output = BasicBlockData<'tcx>;
267
268     #[inline]
269     fn index(&self, index: BasicBlock) -> &BasicBlockData<'tcx> {
270         &self.basic_blocks()[index]
271     }
272 }
273
274 impl<'tcx> IndexMut<BasicBlock> for Mir<'tcx> {
275     #[inline]
276     fn index_mut(&mut self, index: BasicBlock) -> &mut BasicBlockData<'tcx> {
277         &mut self.basic_blocks_mut()[index]
278     }
279 }
280
281 /// Grouped information about the source code origin of a MIR entity.
282 /// Intended to be inspected by diagnostics and debuginfo.
283 /// Most passes can work with it as a whole, within a single function.
284 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
285 pub struct SourceInfo {
286     /// Source span for the AST pertaining to this MIR entity.
287     pub span: Span,
288
289     /// The lexical visibility scope, i.e. which bindings can be seen.
290     pub scope: VisibilityScope
291 }
292
293 ///////////////////////////////////////////////////////////////////////////
294 // Mutability and borrow kinds
295
296 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
297 pub enum Mutability {
298     Mut,
299     Not,
300 }
301
302 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
303 pub enum BorrowKind {
304     /// Data must be immutable and is aliasable.
305     Shared,
306
307     /// Data must be immutable but not aliasable.  This kind of borrow
308     /// cannot currently be expressed by the user and is used only in
309     /// implicit closure bindings. It is needed when you the closure
310     /// is borrowing or mutating a mutable referent, e.g.:
311     ///
312     ///    let x: &mut isize = ...;
313     ///    let y = || *x += 5;
314     ///
315     /// If we were to try to translate this closure into a more explicit
316     /// form, we'd encounter an error with the code as written:
317     ///
318     ///    struct Env { x: & &mut isize }
319     ///    let x: &mut isize = ...;
320     ///    let y = (&mut Env { &x }, fn_ptr);  // Closure is pair of env and fn
321     ///    fn fn_ptr(env: &mut Env) { **env.x += 5; }
322     ///
323     /// This is then illegal because you cannot mutate a `&mut` found
324     /// in an aliasable location. To solve, you'd have to translate with
325     /// an `&mut` borrow:
326     ///
327     ///    struct Env { x: & &mut isize }
328     ///    let x: &mut isize = ...;
329     ///    let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
330     ///    fn fn_ptr(env: &mut Env) { **env.x += 5; }
331     ///
332     /// Now the assignment to `**env.x` is legal, but creating a
333     /// mutable pointer to `x` is not because `x` is not mutable. We
334     /// could fix this by declaring `x` as `let mut x`. This is ok in
335     /// user code, if awkward, but extra weird for closures, since the
336     /// borrow is hidden.
337     ///
338     /// So we introduce a "unique imm" borrow -- the referent is
339     /// immutable, but not aliasable. This solves the problem. For
340     /// simplicity, we don't give users the way to express this
341     /// borrow, it's just used when translating closures.
342     Unique,
343
344     /// Data is mutable and not aliasable.
345     Mut,
346 }
347
348 ///////////////////////////////////////////////////////////////////////////
349 // Variables and temps
350
351 newtype_index!(Local, "_");
352
353 pub const RETURN_POINTER: Local = Local(0);
354
355 /// Classifies locals into categories. See `Mir::local_kind`.
356 #[derive(PartialEq, Eq, Debug)]
357 pub enum LocalKind {
358     /// User-declared variable binding
359     Var,
360     /// Compiler-introduced temporary
361     Temp,
362     /// Function argument
363     Arg,
364     /// Location of function's return value
365     ReturnPointer,
366 }
367
368 /// A MIR local.
369 ///
370 /// This can be a binding declared by the user, a temporary inserted by the compiler, a function
371 /// argument, or the return pointer.
372 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
373 pub struct LocalDecl<'tcx> {
374     /// `let mut x` vs `let x`.
375     ///
376     /// Temporaries and the return pointer are always mutable.
377     pub mutability: Mutability,
378
379     /// True if this corresponds to a user-declared local variable.
380     pub is_user_variable: bool,
381
382     /// Type of this local.
383     pub ty: Ty<'tcx>,
384
385     /// Name of the local, used in debuginfo and pretty-printing.
386     ///
387     /// Note that function arguments can also have this set to `Some(_)`
388     /// to generate better debuginfo.
389     pub name: Option<Name>,
390
391     /// Source info of the local.
392     pub source_info: SourceInfo,
393 }
394
395 impl<'tcx> LocalDecl<'tcx> {
396     /// Create a new `LocalDecl` for a temporary.
397     #[inline]
398     pub fn new_temp(ty: Ty<'tcx>, span: Span) -> Self {
399         LocalDecl {
400             mutability: Mutability::Mut,
401             ty,
402             name: None,
403             source_info: SourceInfo {
404                 span,
405                 scope: ARGUMENT_VISIBILITY_SCOPE
406             },
407             is_user_variable: false
408         }
409     }
410
411     /// Builds a `LocalDecl` for the return pointer.
412     ///
413     /// This must be inserted into the `local_decls` list as the first local.
414     #[inline]
415     pub fn new_return_pointer(return_ty: Ty, span: Span) -> LocalDecl {
416         LocalDecl {
417             mutability: Mutability::Mut,
418             ty: return_ty,
419             source_info: SourceInfo {
420                 span,
421                 scope: ARGUMENT_VISIBILITY_SCOPE
422             },
423             name: None,     // FIXME maybe we do want some name here?
424             is_user_variable: false
425         }
426     }
427 }
428
429 /// A closure capture, with its name and mode.
430 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
431 pub struct UpvarDecl {
432     pub debug_name: Name,
433
434     /// If true, the capture is behind a reference.
435     pub by_ref: bool
436 }
437
438 ///////////////////////////////////////////////////////////////////////////
439 // BasicBlock
440
441 newtype_index!(BasicBlock, "bb");
442
443 ///////////////////////////////////////////////////////////////////////////
444 // BasicBlockData and Terminator
445
446 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
447 pub struct BasicBlockData<'tcx> {
448     /// List of statements in this block.
449     pub statements: Vec<Statement<'tcx>>,
450
451     /// Terminator for this block.
452     ///
453     /// NB. This should generally ONLY be `None` during construction.
454     /// Therefore, you should generally access it via the
455     /// `terminator()` or `terminator_mut()` methods. The only
456     /// exception is that certain passes, such as `simplify_cfg`, swap
457     /// out the terminator temporarily with `None` while they continue
458     /// to recurse over the set of basic blocks.
459     pub terminator: Option<Terminator<'tcx>>,
460
461     /// If true, this block lies on an unwind path. This is used
462     /// during trans where distinct kinds of basic blocks may be
463     /// generated (particularly for MSVC cleanup). Unwind blocks must
464     /// only branch to other unwind blocks.
465     pub is_cleanup: bool,
466 }
467
468 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
469 pub struct Terminator<'tcx> {
470     pub source_info: SourceInfo,
471     pub kind: TerminatorKind<'tcx>
472 }
473
474 #[derive(Clone, RustcEncodable, RustcDecodable)]
475 pub enum TerminatorKind<'tcx> {
476     /// block should have one successor in the graph; we jump there
477     Goto {
478         target: BasicBlock,
479     },
480
481     /// operand evaluates to an integer; jump depending on its value
482     /// to one of the targets, and otherwise fallback to `otherwise`
483     SwitchInt {
484         /// discriminant value being tested
485         discr: Operand<'tcx>,
486
487         /// type of value being tested
488         switch_ty: Ty<'tcx>,
489
490         /// Possible values. The locations to branch to in each case
491         /// are found in the corresponding indices from the `targets` vector.
492         values: Cow<'tcx, [ConstInt]>,
493
494         /// Possible branch sites. The last element of this vector is used
495         /// for the otherwise branch, so targets.len() == values.len() + 1
496         /// should hold.
497         // This invariant is quite non-obvious and also could be improved.
498         // One way to make this invariant is to have something like this instead:
499         //
500         // branches: Vec<(ConstInt, BasicBlock)>,
501         // otherwise: Option<BasicBlock> // exhaustive if None
502         //
503         // However we’ve decided to keep this as-is until we figure a case
504         // where some other approach seems to be strictly better than other.
505         targets: Vec<BasicBlock>,
506     },
507
508     /// Indicates that the landing pad is finished and unwinding should
509     /// continue. Emitted by build::scope::diverge_cleanup.
510     Resume,
511
512     /// Indicates a normal return. The return pointer lvalue should
513     /// have been filled in by now. This should occur at most once.
514     Return,
515
516     /// Indicates a terminator that can never be reached.
517     Unreachable,
518
519     /// Drop the Lvalue
520     Drop {
521         location: Lvalue<'tcx>,
522         target: BasicBlock,
523         unwind: Option<BasicBlock>
524     },
525
526     /// Drop the Lvalue and assign the new value over it
527     DropAndReplace {
528         location: Lvalue<'tcx>,
529         value: Operand<'tcx>,
530         target: BasicBlock,
531         unwind: Option<BasicBlock>,
532     },
533
534     /// Block ends with a call of a converging function
535     Call {
536         /// The function that’s being called
537         func: Operand<'tcx>,
538         /// Arguments the function is called with
539         args: Vec<Operand<'tcx>>,
540         /// Destination for the return value. If some, the call is converging.
541         destination: Option<(Lvalue<'tcx>, BasicBlock)>,
542         /// Cleanups to be done if the call unwinds.
543         cleanup: Option<BasicBlock>
544     },
545
546     /// Jump to the target if the condition has the expected value,
547     /// otherwise panic with a message and a cleanup target.
548     Assert {
549         cond: Operand<'tcx>,
550         expected: bool,
551         msg: AssertMessage<'tcx>,
552         target: BasicBlock,
553         cleanup: Option<BasicBlock>
554     }
555 }
556
557 impl<'tcx> Terminator<'tcx> {
558     pub fn successors(&self) -> Cow<[BasicBlock]> {
559         self.kind.successors()
560     }
561
562     pub fn successors_mut(&mut self) -> Vec<&mut BasicBlock> {
563         self.kind.successors_mut()
564     }
565 }
566
567 impl<'tcx> TerminatorKind<'tcx> {
568     pub fn if_<'a, 'gcx>(tcx: ty::TyCtxt<'a, 'gcx, 'tcx>, cond: Operand<'tcx>,
569                          t: BasicBlock, f: BasicBlock) -> TerminatorKind<'tcx> {
570         static BOOL_SWITCH_FALSE: &'static [ConstInt] = &[ConstInt::U8(0)];
571         TerminatorKind::SwitchInt {
572             discr: cond,
573             switch_ty: tcx.types.bool,
574             values: From::from(BOOL_SWITCH_FALSE),
575             targets: vec![f, t],
576         }
577     }
578
579     pub fn successors(&self) -> Cow<[BasicBlock]> {
580         use self::TerminatorKind::*;
581         match *self {
582             Goto { target: ref b } => slice::ref_slice(b).into_cow(),
583             SwitchInt { targets: ref b, .. } => b[..].into_cow(),
584             Resume => (&[]).into_cow(),
585             Return => (&[]).into_cow(),
586             Unreachable => (&[]).into_cow(),
587             Call { destination: Some((_, t)), cleanup: Some(c), .. } => vec![t, c].into_cow(),
588             Call { destination: Some((_, ref t)), cleanup: None, .. } =>
589                 slice::ref_slice(t).into_cow(),
590             Call { destination: None, cleanup: Some(ref c), .. } => slice::ref_slice(c).into_cow(),
591             Call { destination: None, cleanup: None, .. } => (&[]).into_cow(),
592             DropAndReplace { target, unwind: Some(unwind), .. } |
593             Drop { target, unwind: Some(unwind), .. } => {
594                 vec![target, unwind].into_cow()
595             }
596             DropAndReplace { ref target, unwind: None, .. } |
597             Drop { ref target, unwind: None, .. } => {
598                 slice::ref_slice(target).into_cow()
599             }
600             Assert { target, cleanup: Some(unwind), .. } => vec![target, unwind].into_cow(),
601             Assert { ref target, .. } => slice::ref_slice(target).into_cow(),
602         }
603     }
604
605     // FIXME: no mootable cow. I’m honestly not sure what a “cow” between `&mut [BasicBlock]` and
606     // `Vec<&mut BasicBlock>` would look like in the first place.
607     pub fn successors_mut(&mut self) -> Vec<&mut BasicBlock> {
608         use self::TerminatorKind::*;
609         match *self {
610             Goto { target: ref mut b } => vec![b],
611             SwitchInt { targets: ref mut b, .. } => b.iter_mut().collect(),
612             Resume => Vec::new(),
613             Return => Vec::new(),
614             Unreachable => Vec::new(),
615             Call { destination: Some((_, ref mut t)), cleanup: Some(ref mut c), .. } => vec![t, c],
616             Call { destination: Some((_, ref mut t)), cleanup: None, .. } => vec![t],
617             Call { destination: None, cleanup: Some(ref mut c), .. } => vec![c],
618             Call { destination: None, cleanup: None, .. } => vec![],
619             DropAndReplace { ref mut target, unwind: Some(ref mut unwind), .. } |
620             Drop { ref mut target, unwind: Some(ref mut unwind), .. } => vec![target, unwind],
621             DropAndReplace { ref mut target, unwind: None, .. } |
622             Drop { ref mut target, unwind: None, .. } => {
623                 vec![target]
624             }
625             Assert { ref mut target, cleanup: Some(ref mut unwind), .. } => vec![target, unwind],
626             Assert { ref mut target, .. } => vec![target]
627         }
628     }
629 }
630
631 impl<'tcx> BasicBlockData<'tcx> {
632     pub fn new(terminator: Option<Terminator<'tcx>>) -> BasicBlockData<'tcx> {
633         BasicBlockData {
634             statements: vec![],
635             terminator,
636             is_cleanup: false,
637         }
638     }
639
640     /// Accessor for terminator.
641     ///
642     /// Terminator may not be None after construction of the basic block is complete. This accessor
643     /// provides a convenience way to reach the terminator.
644     pub fn terminator(&self) -> &Terminator<'tcx> {
645         self.terminator.as_ref().expect("invalid terminator state")
646     }
647
648     pub fn terminator_mut(&mut self) -> &mut Terminator<'tcx> {
649         self.terminator.as_mut().expect("invalid terminator state")
650     }
651 }
652
653 impl<'tcx> Debug for TerminatorKind<'tcx> {
654     fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
655         self.fmt_head(fmt)?;
656         let successors = self.successors();
657         let labels = self.fmt_successor_labels();
658         assert_eq!(successors.len(), labels.len());
659
660         match successors.len() {
661             0 => Ok(()),
662
663             1 => write!(fmt, " -> {:?}", successors[0]),
664
665             _ => {
666                 write!(fmt, " -> [")?;
667                 for (i, target) in successors.iter().enumerate() {
668                     if i > 0 {
669                         write!(fmt, ", ")?;
670                     }
671                     write!(fmt, "{}: {:?}", labels[i], target)?;
672                 }
673                 write!(fmt, "]")
674             }
675
676         }
677     }
678 }
679
680 impl<'tcx> TerminatorKind<'tcx> {
681     /// Write the "head" part of the terminator; that is, its name and the data it uses to pick the
682     /// successor basic block, if any. The only information not inlcuded is the list of possible
683     /// successors, which may be rendered differently between the text and the graphviz format.
684     pub fn fmt_head<W: Write>(&self, fmt: &mut W) -> fmt::Result {
685         use self::TerminatorKind::*;
686         match *self {
687             Goto { .. } => write!(fmt, "goto"),
688             SwitchInt { discr: ref lv, .. } => write!(fmt, "switchInt({:?})", lv),
689             Return => write!(fmt, "return"),
690             Resume => write!(fmt, "resume"),
691             Unreachable => write!(fmt, "unreachable"),
692             Drop { ref location, .. } => write!(fmt, "drop({:?})", location),
693             DropAndReplace { ref location, ref value, .. } =>
694                 write!(fmt, "replace({:?} <- {:?})", location, value),
695             Call { ref func, ref args, ref destination, .. } => {
696                 if let Some((ref destination, _)) = *destination {
697                     write!(fmt, "{:?} = ", destination)?;
698                 }
699                 write!(fmt, "{:?}(", func)?;
700                 for (index, arg) in args.iter().enumerate() {
701                     if index > 0 {
702                         write!(fmt, ", ")?;
703                     }
704                     write!(fmt, "{:?}", arg)?;
705                 }
706                 write!(fmt, ")")
707             }
708             Assert { ref cond, expected, ref msg, .. } => {
709                 write!(fmt, "assert(")?;
710                 if !expected {
711                     write!(fmt, "!")?;
712                 }
713                 write!(fmt, "{:?}, ", cond)?;
714
715                 match *msg {
716                     AssertMessage::BoundsCheck { ref len, ref index } => {
717                         write!(fmt, "{:?}, {:?}, {:?}",
718                                "index out of bounds: the len is {} but the index is {}",
719                                len, index)?;
720                     }
721                     AssertMessage::Math(ref err) => {
722                         write!(fmt, "{:?}", err.description())?;
723                     }
724                 }
725
726                 write!(fmt, ")")
727             }
728         }
729     }
730
731     /// Return the list of labels for the edges to the successor basic blocks.
732     pub fn fmt_successor_labels(&self) -> Vec<Cow<'static, str>> {
733         use self::TerminatorKind::*;
734         match *self {
735             Return | Resume | Unreachable => vec![],
736             Goto { .. } => vec!["".into()],
737             SwitchInt { ref values, .. } => {
738                 values.iter()
739                       .map(|const_val| {
740                           let mut buf = String::new();
741                           fmt_const_val(&mut buf, &ConstVal::Integral(*const_val)).unwrap();
742                           buf.into()
743                       })
744                       .chain(iter::once(String::from("otherwise").into()))
745                       .collect()
746             }
747             Call { destination: Some(_), cleanup: Some(_), .. } =>
748                 vec!["return".into_cow(), "unwind".into_cow()],
749             Call { destination: Some(_), cleanup: None, .. } => vec!["return".into_cow()],
750             Call { destination: None, cleanup: Some(_), .. } => vec!["unwind".into_cow()],
751             Call { destination: None, cleanup: None, .. } => vec![],
752             DropAndReplace { unwind: None, .. } |
753             Drop { unwind: None, .. } => vec!["return".into_cow()],
754             DropAndReplace { unwind: Some(_), .. } |
755             Drop { unwind: Some(_), .. } => {
756                 vec!["return".into_cow(), "unwind".into_cow()]
757             }
758             Assert { cleanup: None, .. } => vec!["".into()],
759             Assert { .. } =>
760                 vec!["success".into_cow(), "unwind".into_cow()]
761         }
762     }
763 }
764
765 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
766 pub enum AssertMessage<'tcx> {
767     BoundsCheck {
768         len: Operand<'tcx>,
769         index: Operand<'tcx>
770     },
771     Math(ConstMathErr)
772 }
773
774 ///////////////////////////////////////////////////////////////////////////
775 // Statements
776
777 #[derive(Clone, RustcEncodable, RustcDecodable)]
778 pub struct Statement<'tcx> {
779     pub source_info: SourceInfo,
780     pub kind: StatementKind<'tcx>,
781 }
782
783 impl<'tcx> Statement<'tcx> {
784     /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
785     /// invalidating statement indices in `Location`s.
786     pub fn make_nop(&mut self) {
787         self.kind = StatementKind::Nop
788     }
789 }
790
791 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
792 pub enum StatementKind<'tcx> {
793     /// Write the RHS Rvalue to the LHS Lvalue.
794     Assign(Lvalue<'tcx>, Rvalue<'tcx>),
795
796     /// Write the discriminant for a variant to the enum Lvalue.
797     SetDiscriminant { lvalue: Lvalue<'tcx>, variant_index: usize },
798
799     /// Start a live range for the storage of the local.
800     StorageLive(Lvalue<'tcx>),
801
802     /// End the current live range for the storage of the local.
803     StorageDead(Lvalue<'tcx>),
804
805     InlineAsm {
806         asm: Box<InlineAsm>,
807         outputs: Vec<Lvalue<'tcx>>,
808         inputs: Vec<Operand<'tcx>>
809     },
810
811     /// Mark one terminating point of an extent (i.e. static region).
812     /// (The starting point(s) arise implicitly from borrows.)
813     EndRegion(CodeExtent),
814
815     /// No-op. Useful for deleting instructions without affecting statement indices.
816     Nop,
817 }
818
819 impl<'tcx> Debug for Statement<'tcx> {
820     fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
821         use self::StatementKind::*;
822         match self.kind {
823             Assign(ref lv, ref rv) => write!(fmt, "{:?} = {:?}", lv, rv),
824             // (reuse lifetime rendering policy from ppaux.)
825             EndRegion(ref ce) => write!(fmt, "EndRegion({})", ty::ReScope(*ce)),
826             StorageLive(ref lv) => write!(fmt, "StorageLive({:?})", lv),
827             StorageDead(ref lv) => write!(fmt, "StorageDead({:?})", lv),
828             SetDiscriminant{lvalue: ref lv, variant_index: index} => {
829                 write!(fmt, "discriminant({:?}) = {:?}", lv, index)
830             },
831             InlineAsm { ref asm, ref outputs, ref inputs } => {
832                 write!(fmt, "asm!({:?} : {:?} : {:?})", asm, outputs, inputs)
833             },
834             Nop => write!(fmt, "nop"),
835         }
836     }
837 }
838
839 ///////////////////////////////////////////////////////////////////////////
840 // Lvalues
841
842 /// A path to a value; something that can be evaluated without
843 /// changing or disturbing program state.
844 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable)]
845 pub enum Lvalue<'tcx> {
846     /// local variable
847     Local(Local),
848
849     /// static or static mut variable
850     Static(Box<Static<'tcx>>),
851
852     /// projection out of an lvalue (access a field, deref a pointer, etc)
853     Projection(Box<LvalueProjection<'tcx>>),
854 }
855
856 /// The def-id of a static, along with its normalized type (which is
857 /// stored to avoid requiring normalization when reading MIR).
858 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable)]
859 pub struct Static<'tcx> {
860     pub def_id: DefId,
861     pub ty: Ty<'tcx>,
862 }
863
864 impl_stable_hash_for!(struct Static<'tcx> {
865     def_id,
866     ty
867 });
868
869 /// The `Projection` data structure defines things of the form `B.x`
870 /// or `*B` or `B[index]`. Note that it is parameterized because it is
871 /// shared between `Constant` and `Lvalue`. See the aliases
872 /// `LvalueProjection` etc below.
873 #[derive(Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
874 pub struct Projection<'tcx, B, V> {
875     pub base: B,
876     pub elem: ProjectionElem<'tcx, V>,
877 }
878
879 #[derive(Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
880 pub enum ProjectionElem<'tcx, V> {
881     Deref,
882     Field(Field, Ty<'tcx>),
883     Index(V),
884
885     /// These indices are generated by slice patterns. Easiest to explain
886     /// by example:
887     ///
888     /// ```
889     /// [X, _, .._, _, _] => { offset: 0, min_length: 4, from_end: false },
890     /// [_, X, .._, _, _] => { offset: 1, min_length: 4, from_end: false },
891     /// [_, _, .._, X, _] => { offset: 2, min_length: 4, from_end: true },
892     /// [_, _, .._, _, X] => { offset: 1, min_length: 4, from_end: true },
893     /// ```
894     ConstantIndex {
895         /// index or -index (in Python terms), depending on from_end
896         offset: u32,
897         /// thing being indexed must be at least this long
898         min_length: u32,
899         /// counting backwards from end?
900         from_end: bool,
901     },
902
903     /// These indices are generated by slice patterns.
904     ///
905     /// slice[from:-to] in Python terms.
906     Subslice {
907         from: u32,
908         to: u32,
909     },
910
911     /// "Downcast" to a variant of an ADT. Currently, we only introduce
912     /// this for ADTs with more than one variant. It may be better to
913     /// just introduce it always, or always for enums.
914     Downcast(&'tcx AdtDef, usize),
915 }
916
917 /// Alias for projections as they appear in lvalues, where the base is an lvalue
918 /// and the index is an operand.
919 pub type LvalueProjection<'tcx> = Projection<'tcx, Lvalue<'tcx>, Operand<'tcx>>;
920
921 /// Alias for projections as they appear in lvalues, where the base is an lvalue
922 /// and the index is an operand.
923 pub type LvalueElem<'tcx> = ProjectionElem<'tcx, Operand<'tcx>>;
924
925 newtype_index!(Field, "field");
926
927 impl<'tcx> Lvalue<'tcx> {
928     pub fn field(self, f: Field, ty: Ty<'tcx>) -> Lvalue<'tcx> {
929         self.elem(ProjectionElem::Field(f, ty))
930     }
931
932     pub fn deref(self) -> Lvalue<'tcx> {
933         self.elem(ProjectionElem::Deref)
934     }
935
936     pub fn downcast(self, adt_def: &'tcx AdtDef, variant_index: usize) -> Lvalue<'tcx> {
937         self.elem(ProjectionElem::Downcast(adt_def, variant_index))
938     }
939
940     pub fn index(self, index: Operand<'tcx>) -> Lvalue<'tcx> {
941         self.elem(ProjectionElem::Index(index))
942     }
943
944     pub fn elem(self, elem: LvalueElem<'tcx>) -> Lvalue<'tcx> {
945         Lvalue::Projection(Box::new(LvalueProjection {
946             base: self,
947             elem,
948         }))
949     }
950 }
951
952 impl<'tcx> Debug for Lvalue<'tcx> {
953     fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
954         use self::Lvalue::*;
955
956         match *self {
957             Local(id) => write!(fmt, "{:?}", id),
958             Static(box self::Static { def_id, ty }) =>
959                 write!(fmt, "({}: {:?})", ty::tls::with(|tcx| tcx.item_path_str(def_id)), ty),
960             Projection(ref data) =>
961                 match data.elem {
962                     ProjectionElem::Downcast(ref adt_def, index) =>
963                         write!(fmt, "({:?} as {})", data.base, adt_def.variants[index].name),
964                     ProjectionElem::Deref =>
965                         write!(fmt, "(*{:?})", data.base),
966                     ProjectionElem::Field(field, ty) =>
967                         write!(fmt, "({:?}.{:?}: {:?})", data.base, field.index(), ty),
968                     ProjectionElem::Index(ref index) =>
969                         write!(fmt, "{:?}[{:?}]", data.base, index),
970                     ProjectionElem::ConstantIndex { offset, min_length, from_end: false } =>
971                         write!(fmt, "{:?}[{:?} of {:?}]", data.base, offset, min_length),
972                     ProjectionElem::ConstantIndex { offset, min_length, from_end: true } =>
973                         write!(fmt, "{:?}[-{:?} of {:?}]", data.base, offset, min_length),
974                     ProjectionElem::Subslice { from, to } if to == 0 =>
975                         write!(fmt, "{:?}[{:?}:]", data.base, from),
976                     ProjectionElem::Subslice { from, to } if from == 0 =>
977                         write!(fmt, "{:?}[:-{:?}]", data.base, to),
978                     ProjectionElem::Subslice { from, to } =>
979                         write!(fmt, "{:?}[{:?}:-{:?}]", data.base,
980                                from, to),
981
982                 },
983         }
984     }
985 }
986
987 ///////////////////////////////////////////////////////////////////////////
988 // Scopes
989
990 newtype_index!(VisibilityScope, "scope");
991 pub const ARGUMENT_VISIBILITY_SCOPE : VisibilityScope = VisibilityScope(0);
992
993 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
994 pub struct VisibilityScopeData {
995     pub span: Span,
996     pub parent_scope: Option<VisibilityScope>,
997 }
998
999 ///////////////////////////////////////////////////////////////////////////
1000 // Operands
1001
1002 /// These are values that can appear inside an rvalue (or an index
1003 /// lvalue). They are intentionally limited to prevent rvalues from
1004 /// being nested in one another.
1005 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable)]
1006 pub enum Operand<'tcx> {
1007     Consume(Lvalue<'tcx>),
1008     Constant(Box<Constant<'tcx>>),
1009 }
1010
1011 impl<'tcx> Debug for Operand<'tcx> {
1012     fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
1013         use self::Operand::*;
1014         match *self {
1015             Constant(ref a) => write!(fmt, "{:?}", a),
1016             Consume(ref lv) => write!(fmt, "{:?}", lv),
1017         }
1018     }
1019 }
1020
1021 impl<'tcx> Operand<'tcx> {
1022     pub fn function_handle<'a>(
1023         tcx: ty::TyCtxt<'a, 'tcx, 'tcx>,
1024         def_id: DefId,
1025         substs: &'tcx Substs<'tcx>,
1026         span: Span,
1027     ) -> Self {
1028         Operand::Constant(box Constant {
1029             span,
1030             ty: tcx.type_of(def_id).subst(tcx, substs),
1031             literal: Literal::Value { value: ConstVal::Function(def_id, substs) },
1032         })
1033     }
1034
1035 }
1036
1037 ///////////////////////////////////////////////////////////////////////////
1038 /// Rvalues
1039
1040 #[derive(Clone, RustcEncodable, RustcDecodable)]
1041 pub enum Rvalue<'tcx> {
1042     /// x (either a move or copy, depending on type of x)
1043     Use(Operand<'tcx>),
1044
1045     /// [x; 32]
1046     Repeat(Operand<'tcx>, ConstUsize),
1047
1048     /// &x or &mut x
1049     Ref(Region<'tcx>, BorrowKind, Lvalue<'tcx>),
1050
1051     /// length of a [X] or [X;n] value
1052     Len(Lvalue<'tcx>),
1053
1054     Cast(CastKind, Operand<'tcx>, Ty<'tcx>),
1055
1056     BinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
1057     CheckedBinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
1058
1059     NullaryOp(NullOp, Ty<'tcx>),
1060     UnaryOp(UnOp, Operand<'tcx>),
1061
1062     /// Read the discriminant of an ADT.
1063     ///
1064     /// Undefined (i.e. no effort is made to make it defined, but there’s no reason why it cannot
1065     /// be defined to return, say, a 0) if ADT is not an enum.
1066     Discriminant(Lvalue<'tcx>),
1067
1068     /// Create an aggregate value, like a tuple or struct.  This is
1069     /// only needed because we want to distinguish `dest = Foo { x:
1070     /// ..., y: ... }` from `dest.x = ...; dest.y = ...;` in the case
1071     /// that `Foo` has a destructor. These rvalues can be optimized
1072     /// away after type-checking and before lowering.
1073     Aggregate(Box<AggregateKind<'tcx>>, Vec<Operand<'tcx>>),
1074 }
1075
1076 #[derive(Clone, Copy, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
1077 pub enum CastKind {
1078     Misc,
1079
1080     /// Convert unique, zero-sized type for a fn to fn()
1081     ReifyFnPointer,
1082
1083     /// Convert non capturing closure to fn()
1084     ClosureFnPointer,
1085
1086     /// Convert safe fn() to unsafe fn()
1087     UnsafeFnPointer,
1088
1089     /// "Unsize" -- convert a thin-or-fat pointer to a fat pointer.
1090     /// trans must figure out the details once full monomorphization
1091     /// is known. For example, this could be used to cast from a
1092     /// `&[i32;N]` to a `&[i32]`, or a `Box<T>` to a `Box<Trait>`
1093     /// (presuming `T: Trait`).
1094     Unsize,
1095 }
1096
1097 #[derive(Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
1098 pub enum AggregateKind<'tcx> {
1099     /// The type is of the element
1100     Array(Ty<'tcx>),
1101     Tuple,
1102     /// The second field is variant number (discriminant), it's equal to 0
1103     /// for struct and union expressions. The fourth field is active field
1104     /// number and is present only for union expressions.
1105     Adt(&'tcx AdtDef, usize, &'tcx Substs<'tcx>, Option<usize>),
1106     Closure(DefId, ClosureSubsts<'tcx>),
1107 }
1108
1109 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
1110 pub enum BinOp {
1111     /// The `+` operator (addition)
1112     Add,
1113     /// The `-` operator (subtraction)
1114     Sub,
1115     /// The `*` operator (multiplication)
1116     Mul,
1117     /// The `/` operator (division)
1118     Div,
1119     /// The `%` operator (modulus)
1120     Rem,
1121     /// The `^` operator (bitwise xor)
1122     BitXor,
1123     /// The `&` operator (bitwise and)
1124     BitAnd,
1125     /// The `|` operator (bitwise or)
1126     BitOr,
1127     /// The `<<` operator (shift left)
1128     Shl,
1129     /// The `>>` operator (shift right)
1130     Shr,
1131     /// The `==` operator (equality)
1132     Eq,
1133     /// The `<` operator (less than)
1134     Lt,
1135     /// The `<=` operator (less than or equal to)
1136     Le,
1137     /// The `!=` operator (not equal to)
1138     Ne,
1139     /// The `>=` operator (greater than or equal to)
1140     Ge,
1141     /// The `>` operator (greater than)
1142     Gt,
1143     /// The `ptr.offset` operator
1144     Offset,
1145 }
1146
1147 impl BinOp {
1148     pub fn is_checkable(self) -> bool {
1149         use self::BinOp::*;
1150         match self {
1151             Add | Sub | Mul | Shl | Shr => true,
1152             _ => false
1153         }
1154     }
1155 }
1156
1157 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
1158 pub enum NullOp {
1159     /// Return the size of a value of that type
1160     SizeOf,
1161     /// Create a new uninitialized box for a value of that type
1162     Box,
1163 }
1164
1165 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
1166 pub enum UnOp {
1167     /// The `!` operator for logical inversion
1168     Not,
1169     /// The `-` operator for negation
1170     Neg,
1171 }
1172
1173 impl<'tcx> Debug for Rvalue<'tcx> {
1174     fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
1175         use self::Rvalue::*;
1176
1177         match *self {
1178             Use(ref lvalue) => write!(fmt, "{:?}", lvalue),
1179             Repeat(ref a, ref b) => write!(fmt, "[{:?}; {:?}]", a, b),
1180             Len(ref a) => write!(fmt, "Len({:?})", a),
1181             Cast(ref kind, ref lv, ref ty) => write!(fmt, "{:?} as {:?} ({:?})", lv, ty, kind),
1182             BinaryOp(ref op, ref a, ref b) => write!(fmt, "{:?}({:?}, {:?})", op, a, b),
1183             CheckedBinaryOp(ref op, ref a, ref b) => {
1184                 write!(fmt, "Checked{:?}({:?}, {:?})", op, a, b)
1185             }
1186             UnaryOp(ref op, ref a) => write!(fmt, "{:?}({:?})", op, a),
1187             Discriminant(ref lval) => write!(fmt, "discriminant({:?})", lval),
1188             NullaryOp(ref op, ref t) => write!(fmt, "{:?}({:?})", op, t),
1189             Ref(region, borrow_kind, ref lv) => {
1190                 let kind_str = match borrow_kind {
1191                     BorrowKind::Shared => "",
1192                     BorrowKind::Mut | BorrowKind::Unique => "mut ",
1193                 };
1194
1195                 // When identifying regions, add trailing space if
1196                 // necessary.
1197                 let region = if ppaux::identify_regions() {
1198                     let mut region = format!("{}", region);
1199                     if region.len() > 0 { region.push(' '); }
1200                     region
1201                 } else {
1202                     "".to_owned()
1203                 };
1204                 write!(fmt, "&{}{}{:?}", region, kind_str, lv)
1205             }
1206
1207             Aggregate(ref kind, ref lvs) => {
1208                 fn fmt_tuple(fmt: &mut Formatter, lvs: &[Operand]) -> fmt::Result {
1209                     let mut tuple_fmt = fmt.debug_tuple("");
1210                     for lv in lvs {
1211                         tuple_fmt.field(lv);
1212                     }
1213                     tuple_fmt.finish()
1214                 }
1215
1216                 match **kind {
1217                     AggregateKind::Array(_) => write!(fmt, "{:?}", lvs),
1218
1219                     AggregateKind::Tuple => {
1220                         match lvs.len() {
1221                             0 => write!(fmt, "()"),
1222                             1 => write!(fmt, "({:?},)", lvs[0]),
1223                             _ => fmt_tuple(fmt, lvs),
1224                         }
1225                     }
1226
1227                     AggregateKind::Adt(adt_def, variant, substs, _) => {
1228                         let variant_def = &adt_def.variants[variant];
1229
1230                         ppaux::parameterized(fmt, substs, variant_def.did, &[])?;
1231
1232                         match variant_def.ctor_kind {
1233                             CtorKind::Const => Ok(()),
1234                             CtorKind::Fn => fmt_tuple(fmt, lvs),
1235                             CtorKind::Fictive => {
1236                                 let mut struct_fmt = fmt.debug_struct("");
1237                                 for (field, lv) in variant_def.fields.iter().zip(lvs) {
1238                                     struct_fmt.field(&field.name.as_str(), lv);
1239                                 }
1240                                 struct_fmt.finish()
1241                             }
1242                         }
1243                     }
1244
1245                     AggregateKind::Closure(def_id, _) => ty::tls::with(|tcx| {
1246                         if let Some(node_id) = tcx.hir.as_local_node_id(def_id) {
1247                             let name = if tcx.sess.opts.debugging_opts.span_free_formats {
1248                                 format!("[closure@{:?}]", node_id)
1249                             } else {
1250                                 format!("[closure@{:?}]", tcx.hir.span(node_id))
1251                             };
1252                             let mut struct_fmt = fmt.debug_struct(&name);
1253
1254                             tcx.with_freevars(node_id, |freevars| {
1255                                 for (freevar, lv) in freevars.iter().zip(lvs) {
1256                                     let def_id = freevar.def.def_id();
1257                                     let var_id = tcx.hir.as_local_node_id(def_id).unwrap();
1258                                     let var_name = tcx.local_var_name_str(var_id);
1259                                     struct_fmt.field(&var_name, lv);
1260                                 }
1261                             });
1262
1263                             struct_fmt.finish()
1264                         } else {
1265                             write!(fmt, "[closure]")
1266                         }
1267                     }),
1268                 }
1269             }
1270         }
1271     }
1272 }
1273
1274 ///////////////////////////////////////////////////////////////////////////
1275 /// Constants
1276 ///
1277 /// Two constants are equal if they are the same constant. Note that
1278 /// this does not necessarily mean that they are "==" in Rust -- in
1279 /// particular one must be wary of `NaN`!
1280
1281 #[derive(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1282 pub struct Constant<'tcx> {
1283     pub span: Span,
1284     pub ty: Ty<'tcx>,
1285     pub literal: Literal<'tcx>,
1286 }
1287
1288 newtype_index!(Promoted, "promoted");
1289
1290 #[derive(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1291 pub enum Literal<'tcx> {
1292     Item {
1293         def_id: DefId,
1294         substs: &'tcx Substs<'tcx>,
1295     },
1296     Value {
1297         value: ConstVal<'tcx>,
1298     },
1299     Promoted {
1300         // Index into the `promoted` vector of `Mir`.
1301         index: Promoted
1302     },
1303 }
1304
1305 impl<'tcx> Debug for Constant<'tcx> {
1306     fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
1307         write!(fmt, "{:?}", self.literal)
1308     }
1309 }
1310
1311 impl<'tcx> Debug for Literal<'tcx> {
1312     fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
1313         use self::Literal::*;
1314         match *self {
1315             Item { def_id, substs } => {
1316                 ppaux::parameterized(fmt, substs, def_id, &[])
1317             }
1318             Value { ref value } => {
1319                 write!(fmt, "const ")?;
1320                 fmt_const_val(fmt, value)
1321             }
1322             Promoted { index } => {
1323                 write!(fmt, "{:?}", index)
1324             }
1325         }
1326     }
1327 }
1328
1329 /// Write a `ConstVal` in a way closer to the original source code than the `Debug` output.
1330 fn fmt_const_val<W: Write>(fmt: &mut W, const_val: &ConstVal) -> fmt::Result {
1331     use middle::const_val::ConstVal::*;
1332     match *const_val {
1333         Float(f) => write!(fmt, "{:?}", f),
1334         Integral(n) => write!(fmt, "{}", n),
1335         Str(ref s) => write!(fmt, "{:?}", s),
1336         ByteStr(ref bytes) => {
1337             let escaped: String = bytes
1338                 .iter()
1339                 .flat_map(|&ch| ascii::escape_default(ch).map(|c| c as char))
1340                 .collect();
1341             write!(fmt, "b\"{}\"", escaped)
1342         }
1343         Bool(b) => write!(fmt, "{:?}", b),
1344         Char(c) => write!(fmt, "{:?}", c),
1345         Variant(def_id) |
1346         Function(def_id, _) => write!(fmt, "{}", item_path_str(def_id)),
1347         Struct(_) | Tuple(_) | Array(_) | Repeat(..) =>
1348             bug!("ConstVal `{:?}` should not be in MIR", const_val),
1349     }
1350 }
1351
1352 fn item_path_str(def_id: DefId) -> String {
1353     ty::tls::with(|tcx| tcx.item_path_str(def_id))
1354 }
1355
1356 impl<'tcx> ControlFlowGraph for Mir<'tcx> {
1357
1358     type Node = BasicBlock;
1359
1360     fn num_nodes(&self) -> usize { self.basic_blocks.len() }
1361
1362     fn start_node(&self) -> Self::Node { START_BLOCK }
1363
1364     fn predecessors<'graph>(&'graph self, node: Self::Node)
1365                             -> <Self as GraphPredecessors<'graph>>::Iter
1366     {
1367         self.predecessors_for(node).clone().into_iter()
1368     }
1369     fn successors<'graph>(&'graph self, node: Self::Node)
1370                           -> <Self as GraphSuccessors<'graph>>::Iter
1371     {
1372         self.basic_blocks[node].terminator().successors().into_owned().into_iter()
1373     }
1374 }
1375
1376 impl<'a, 'b> GraphPredecessors<'b> for Mir<'a> {
1377     type Item = BasicBlock;
1378     type Iter = IntoIter<BasicBlock>;
1379 }
1380
1381 impl<'a, 'b>  GraphSuccessors<'b> for Mir<'a> {
1382     type Item = BasicBlock;
1383     type Iter = IntoIter<BasicBlock>;
1384 }
1385
1386 #[derive(Copy, Clone, PartialEq, Eq, Hash, Ord, PartialOrd)]
1387 pub struct Location {
1388     /// the location is within this block
1389     pub block: BasicBlock,
1390
1391     /// the location is the start of the this statement; or, if `statement_index`
1392     /// == num-statements, then the start of the terminator.
1393     pub statement_index: usize,
1394 }
1395
1396 impl fmt::Debug for Location {
1397     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1398         write!(fmt, "{:?}[{}]", self.block, self.statement_index)
1399     }
1400 }
1401
1402 impl Location {
1403     pub fn dominates(&self, other: &Location, dominators: &Dominators<BasicBlock>) -> bool {
1404         if self.block == other.block {
1405             self.statement_index <= other.statement_index
1406         } else {
1407             dominators.is_dominated_by(other.block, self.block)
1408         }
1409     }
1410 }
1411
1412
1413 /*
1414  * TypeFoldable implementations for MIR types
1415  */
1416
1417 impl<'tcx> TypeFoldable<'tcx> for Mir<'tcx> {
1418     fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1419         Mir {
1420             basic_blocks: self.basic_blocks.fold_with(folder),
1421             visibility_scopes: self.visibility_scopes.clone(),
1422             promoted: self.promoted.fold_with(folder),
1423             return_ty: self.return_ty.fold_with(folder),
1424             local_decls: self.local_decls.fold_with(folder),
1425             arg_count: self.arg_count,
1426             upvar_decls: self.upvar_decls.clone(),
1427             spread_arg: self.spread_arg,
1428             span: self.span,
1429             cache: cache::Cache::new()
1430         }
1431     }
1432
1433     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1434         self.basic_blocks.visit_with(visitor) ||
1435         self.promoted.visit_with(visitor)     ||
1436         self.return_ty.visit_with(visitor)    ||
1437         self.local_decls.visit_with(visitor)
1438     }
1439 }
1440
1441 impl<'tcx> TypeFoldable<'tcx> for LocalDecl<'tcx> {
1442     fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1443         LocalDecl {
1444             ty: self.ty.fold_with(folder),
1445             ..self.clone()
1446         }
1447     }
1448
1449     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1450         self.ty.visit_with(visitor)
1451     }
1452 }
1453
1454 impl<'tcx> TypeFoldable<'tcx> for BasicBlockData<'tcx> {
1455     fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1456         BasicBlockData {
1457             statements: self.statements.fold_with(folder),
1458             terminator: self.terminator.fold_with(folder),
1459             is_cleanup: self.is_cleanup
1460         }
1461     }
1462
1463     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1464         self.statements.visit_with(visitor) || self.terminator.visit_with(visitor)
1465     }
1466 }
1467
1468 impl<'tcx> TypeFoldable<'tcx> for Statement<'tcx> {
1469     fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1470         use mir::StatementKind::*;
1471
1472         let kind = match self.kind {
1473             Assign(ref lval, ref rval) => Assign(lval.fold_with(folder), rval.fold_with(folder)),
1474             SetDiscriminant { ref lvalue, variant_index } => SetDiscriminant {
1475                 lvalue: lvalue.fold_with(folder),
1476                 variant_index,
1477             },
1478             StorageLive(ref lval) => StorageLive(lval.fold_with(folder)),
1479             StorageDead(ref lval) => StorageDead(lval.fold_with(folder)),
1480             InlineAsm { ref asm, ref outputs, ref inputs } => InlineAsm {
1481                 asm: asm.clone(),
1482                 outputs: outputs.fold_with(folder),
1483                 inputs: inputs.fold_with(folder)
1484             },
1485
1486             // Note for future: If we want to expose the extents
1487             // during the fold, we need to either generalize EndRegion
1488             // to carry `[ty::Region]`, or extend the `TypeFolder`
1489             // trait with a `fn fold_extent`.
1490             EndRegion(ref extent) => EndRegion(extent.clone()),
1491
1492             Nop => Nop,
1493         };
1494         Statement {
1495             source_info: self.source_info,
1496             kind,
1497         }
1498     }
1499
1500     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1501         use mir::StatementKind::*;
1502
1503         match self.kind {
1504             Assign(ref lval, ref rval) => { lval.visit_with(visitor) || rval.visit_with(visitor) }
1505             SetDiscriminant { ref lvalue, .. } |
1506             StorageLive(ref lvalue) |
1507             StorageDead(ref lvalue) => lvalue.visit_with(visitor),
1508             InlineAsm { ref outputs, ref inputs, .. } =>
1509                 outputs.visit_with(visitor) || inputs.visit_with(visitor),
1510
1511             // Note for future: If we want to expose the extents
1512             // during the visit, we need to either generalize EndRegion
1513             // to carry `[ty::Region]`, or extend the `TypeVisitor`
1514             // trait with a `fn visit_extent`.
1515             EndRegion(ref _extent) => false,
1516
1517             Nop => false,
1518         }
1519     }
1520 }
1521
1522 impl<'tcx> TypeFoldable<'tcx> for Terminator<'tcx> {
1523     fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1524         use mir::TerminatorKind::*;
1525
1526         let kind = match self.kind {
1527             Goto { target } => Goto { target: target },
1528             SwitchInt { ref discr, switch_ty, ref values, ref targets } => SwitchInt {
1529                 discr: discr.fold_with(folder),
1530                 switch_ty: switch_ty.fold_with(folder),
1531                 values: values.clone(),
1532                 targets: targets.clone()
1533             },
1534             Drop { ref location, target, unwind } => Drop {
1535                 location: location.fold_with(folder),
1536                 target,
1537                 unwind,
1538             },
1539             DropAndReplace { ref location, ref value, target, unwind } => DropAndReplace {
1540                 location: location.fold_with(folder),
1541                 value: value.fold_with(folder),
1542                 target,
1543                 unwind,
1544             },
1545             Call { ref func, ref args, ref destination, cleanup } => {
1546                 let dest = destination.as_ref().map(|&(ref loc, dest)| {
1547                     (loc.fold_with(folder), dest)
1548                 });
1549
1550                 Call {
1551                     func: func.fold_with(folder),
1552                     args: args.fold_with(folder),
1553                     destination: dest,
1554                     cleanup,
1555                 }
1556             },
1557             Assert { ref cond, expected, ref msg, target, cleanup } => {
1558                 let msg = if let AssertMessage::BoundsCheck { ref len, ref index } = *msg {
1559                     AssertMessage::BoundsCheck {
1560                         len: len.fold_with(folder),
1561                         index: index.fold_with(folder),
1562                     }
1563                 } else {
1564                     msg.clone()
1565                 };
1566                 Assert {
1567                     cond: cond.fold_with(folder),
1568                     expected,
1569                     msg,
1570                     target,
1571                     cleanup,
1572                 }
1573             },
1574             Resume => Resume,
1575             Return => Return,
1576             Unreachable => Unreachable,
1577         };
1578         Terminator {
1579             source_info: self.source_info,
1580             kind,
1581         }
1582     }
1583
1584     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1585         use mir::TerminatorKind::*;
1586
1587         match self.kind {
1588             SwitchInt { ref discr, switch_ty, .. } =>
1589                 discr.visit_with(visitor) || switch_ty.visit_with(visitor),
1590             Drop { ref location, ..} => location.visit_with(visitor),
1591             DropAndReplace { ref location, ref value, ..} =>
1592                 location.visit_with(visitor) || value.visit_with(visitor),
1593             Call { ref func, ref args, ref destination, .. } => {
1594                 let dest = if let Some((ref loc, _)) = *destination {
1595                     loc.visit_with(visitor)
1596                 } else { false };
1597                 dest || func.visit_with(visitor) || args.visit_with(visitor)
1598             },
1599             Assert { ref cond, ref msg, .. } => {
1600                 if cond.visit_with(visitor) {
1601                     if let AssertMessage::BoundsCheck { ref len, ref index } = *msg {
1602                         len.visit_with(visitor) || index.visit_with(visitor)
1603                     } else {
1604                         false
1605                     }
1606                 } else {
1607                     false
1608                 }
1609             },
1610             Goto { .. } |
1611             Resume |
1612             Return |
1613             Unreachable => false
1614         }
1615     }
1616 }
1617
1618 impl<'tcx> TypeFoldable<'tcx> for Lvalue<'tcx> {
1619     fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1620         match self {
1621             &Lvalue::Projection(ref p) => Lvalue::Projection(p.fold_with(folder)),
1622             _ => self.clone()
1623         }
1624     }
1625
1626     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1627         if let &Lvalue::Projection(ref p) = self {
1628             p.visit_with(visitor)
1629         } else {
1630             false
1631         }
1632     }
1633 }
1634
1635 impl<'tcx> TypeFoldable<'tcx> for Rvalue<'tcx> {
1636     fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1637         use mir::Rvalue::*;
1638         match *self {
1639             Use(ref op) => Use(op.fold_with(folder)),
1640             Repeat(ref op, len) => Repeat(op.fold_with(folder), len),
1641             Ref(region, bk, ref lval) => Ref(region.fold_with(folder), bk, lval.fold_with(folder)),
1642             Len(ref lval) => Len(lval.fold_with(folder)),
1643             Cast(kind, ref op, ty) => Cast(kind, op.fold_with(folder), ty.fold_with(folder)),
1644             BinaryOp(op, ref rhs, ref lhs) =>
1645                 BinaryOp(op, rhs.fold_with(folder), lhs.fold_with(folder)),
1646             CheckedBinaryOp(op, ref rhs, ref lhs) =>
1647                 CheckedBinaryOp(op, rhs.fold_with(folder), lhs.fold_with(folder)),
1648             UnaryOp(op, ref val) => UnaryOp(op, val.fold_with(folder)),
1649             Discriminant(ref lval) => Discriminant(lval.fold_with(folder)),
1650             NullaryOp(op, ty) => NullaryOp(op, ty.fold_with(folder)),
1651             Aggregate(ref kind, ref fields) => {
1652                 let kind = box match **kind {
1653                     AggregateKind::Array(ty) => AggregateKind::Array(ty.fold_with(folder)),
1654                     AggregateKind::Tuple => AggregateKind::Tuple,
1655                     AggregateKind::Adt(def, v, substs, n) =>
1656                         AggregateKind::Adt(def, v, substs.fold_with(folder), n),
1657                     AggregateKind::Closure(id, substs) =>
1658                         AggregateKind::Closure(id, substs.fold_with(folder))
1659                 };
1660                 Aggregate(kind, fields.fold_with(folder))
1661             }
1662         }
1663     }
1664
1665     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1666         use mir::Rvalue::*;
1667         match *self {
1668             Use(ref op) => op.visit_with(visitor),
1669             Repeat(ref op, _) => op.visit_with(visitor),
1670             Ref(region, _, ref lval) => region.visit_with(visitor) || lval.visit_with(visitor),
1671             Len(ref lval) => lval.visit_with(visitor),
1672             Cast(_, ref op, ty) => op.visit_with(visitor) || ty.visit_with(visitor),
1673             BinaryOp(_, ref rhs, ref lhs) |
1674             CheckedBinaryOp(_, ref rhs, ref lhs) =>
1675                 rhs.visit_with(visitor) || lhs.visit_with(visitor),
1676             UnaryOp(_, ref val) => val.visit_with(visitor),
1677             Discriminant(ref lval) => lval.visit_with(visitor),
1678             NullaryOp(_, ty) => ty.visit_with(visitor),
1679             Aggregate(ref kind, ref fields) => {
1680                 (match **kind {
1681                     AggregateKind::Array(ty) => ty.visit_with(visitor),
1682                     AggregateKind::Tuple => false,
1683                     AggregateKind::Adt(_, _, substs, _) => substs.visit_with(visitor),
1684                     AggregateKind::Closure(_, substs) => substs.visit_with(visitor)
1685                 }) || fields.visit_with(visitor)
1686             }
1687         }
1688     }
1689 }
1690
1691 impl<'tcx> TypeFoldable<'tcx> for Operand<'tcx> {
1692     fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1693         match *self {
1694             Operand::Consume(ref lval) => Operand::Consume(lval.fold_with(folder)),
1695             Operand::Constant(ref c) => Operand::Constant(c.fold_with(folder)),
1696         }
1697     }
1698
1699     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1700         match *self {
1701             Operand::Consume(ref lval) => lval.visit_with(visitor),
1702             Operand::Constant(ref c) => c.visit_with(visitor)
1703         }
1704     }
1705 }
1706
1707 impl<'tcx, B, V> TypeFoldable<'tcx> for Projection<'tcx, B, V>
1708     where B: TypeFoldable<'tcx>, V: TypeFoldable<'tcx>
1709 {
1710     fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1711         use mir::ProjectionElem::*;
1712
1713         let base = self.base.fold_with(folder);
1714         let elem = match self.elem {
1715             Deref => Deref,
1716             Field(f, ty) => Field(f, ty.fold_with(folder)),
1717             Index(ref v) => Index(v.fold_with(folder)),
1718             ref elem => elem.clone()
1719         };
1720
1721         Projection {
1722             base,
1723             elem,
1724         }
1725     }
1726
1727     fn super_visit_with<Vs: TypeVisitor<'tcx>>(&self, visitor: &mut Vs) -> bool {
1728         use mir::ProjectionElem::*;
1729
1730         self.base.visit_with(visitor) ||
1731             match self.elem {
1732                 Field(_, ty) => ty.visit_with(visitor),
1733                 Index(ref v) => v.visit_with(visitor),
1734                 _ => false
1735             }
1736     }
1737 }
1738
1739 impl<'tcx> TypeFoldable<'tcx> for Constant<'tcx> {
1740     fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1741         Constant {
1742             span: self.span.clone(),
1743             ty: self.ty.fold_with(folder),
1744             literal: self.literal.fold_with(folder)
1745         }
1746     }
1747     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1748         self.ty.visit_with(visitor) || self.literal.visit_with(visitor)
1749     }
1750 }
1751
1752 impl<'tcx> TypeFoldable<'tcx> for Literal<'tcx> {
1753     fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1754         match *self {
1755             Literal::Item { def_id, substs } => Literal::Item {
1756                 def_id,
1757                 substs: substs.fold_with(folder)
1758             },
1759             _ => self.clone()
1760         }
1761     }
1762     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1763         match *self {
1764             Literal::Item { substs, .. } => substs.visit_with(visitor),
1765             _ => false
1766         }
1767     }
1768 }