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