]> git.lizzy.rs Git - rust.git/blob - src/librustc/mir/mod.rs
Auto merge of #41258 - clarcharr:str_box_extras, r=Kimundi
[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].is_user_variable {
201                 None
202             } else {
203                 Some(local)
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].is_user_variable {
214                 Some(local)
215             } else {
216                 None
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     /// True if this corresponds to a user-declared local variable.
374     pub is_user_variable: bool,
375
376     /// Type of this local.
377     pub ty: Ty<'tcx>,
378
379     /// Name of the local, used in debuginfo and pretty-printing.
380     ///
381     /// Note that function arguments can also have this set to `Some(_)`
382     /// to generate better debuginfo.
383     pub name: Option<Name>,
384
385     /// Source info of the local.
386     pub source_info: SourceInfo,
387 }
388
389 impl<'tcx> LocalDecl<'tcx> {
390     /// Create a new `LocalDecl` for a temporary.
391     #[inline]
392     pub fn new_temp(ty: Ty<'tcx>, span: Span) -> Self {
393         LocalDecl {
394             mutability: Mutability::Mut,
395             ty: ty,
396             name: None,
397             source_info: SourceInfo {
398                 span: span,
399                 scope: ARGUMENT_VISIBILITY_SCOPE
400             },
401             is_user_variable: false
402         }
403     }
404
405     /// Builds a `LocalDecl` for the return pointer.
406     ///
407     /// This must be inserted into the `local_decls` list as the first local.
408     #[inline]
409     pub fn new_return_pointer(return_ty: Ty, span: Span) -> LocalDecl {
410         LocalDecl {
411             mutability: Mutability::Mut,
412             ty: return_ty,
413             source_info: SourceInfo {
414                 span: span,
415                 scope: ARGUMENT_VISIBILITY_SCOPE
416             },
417             name: None,     // FIXME maybe we do want some name here?
418             is_user_variable: false
419         }
420     }
421 }
422
423 /// A closure capture, with its name and mode.
424 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
425 pub struct UpvarDecl {
426     pub debug_name: Name,
427
428     /// If true, the capture is behind a reference.
429     pub by_ref: bool
430 }
431
432 ///////////////////////////////////////////////////////////////////////////
433 // BasicBlock
434
435 newtype_index!(BasicBlock, "bb");
436
437 ///////////////////////////////////////////////////////////////////////////
438 // BasicBlockData and Terminator
439
440 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
441 pub struct BasicBlockData<'tcx> {
442     /// List of statements in this block.
443     pub statements: Vec<Statement<'tcx>>,
444
445     /// Terminator for this block.
446     ///
447     /// NB. This should generally ONLY be `None` during construction.
448     /// Therefore, you should generally access it via the
449     /// `terminator()` or `terminator_mut()` methods. The only
450     /// exception is that certain passes, such as `simplify_cfg`, swap
451     /// out the terminator temporarily with `None` while they continue
452     /// to recurse over the set of basic blocks.
453     pub terminator: Option<Terminator<'tcx>>,
454
455     /// If true, this block lies on an unwind path. This is used
456     /// during trans where distinct kinds of basic blocks may be
457     /// generated (particularly for MSVC cleanup). Unwind blocks must
458     /// only branch to other unwind blocks.
459     pub is_cleanup: bool,
460 }
461
462 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
463 pub struct Terminator<'tcx> {
464     pub source_info: SourceInfo,
465     pub kind: TerminatorKind<'tcx>
466 }
467
468 #[derive(Clone, RustcEncodable, RustcDecodable)]
469 pub enum TerminatorKind<'tcx> {
470     /// block should have one successor in the graph; we jump there
471     Goto {
472         target: BasicBlock,
473     },
474
475     /// operand evaluates to an integer; jump depending on its value
476     /// to one of the targets, and otherwise fallback to `otherwise`
477     SwitchInt {
478         /// discriminant value being tested
479         discr: Operand<'tcx>,
480
481         /// type of value being tested
482         switch_ty: Ty<'tcx>,
483
484         /// Possible values. The locations to branch to in each case
485         /// are found in the corresponding indices from the `targets` vector.
486         values: Cow<'tcx, [ConstInt]>,
487
488         /// Possible branch sites. The last element of this vector is used
489         /// for the otherwise branch, so targets.len() == values.len() + 1
490         /// should hold.
491         // This invariant is quite non-obvious and also could be improved.
492         // One way to make this invariant is to have something like this instead:
493         //
494         // branches: Vec<(ConstInt, BasicBlock)>,
495         // otherwise: Option<BasicBlock> // exhaustive if None
496         //
497         // However we’ve decided to keep this as-is until we figure a case
498         // where some other approach seems to be strictly better than other.
499         targets: Vec<BasicBlock>,
500     },
501
502     /// Indicates that the landing pad is finished and unwinding should
503     /// continue. Emitted by build::scope::diverge_cleanup.
504     Resume,
505
506     /// Indicates a normal return. The return pointer lvalue should
507     /// have been filled in by now. This should occur at most once.
508     Return,
509
510     /// Indicates a terminator that can never be reached.
511     Unreachable,
512
513     /// Drop the Lvalue
514     Drop {
515         location: Lvalue<'tcx>,
516         target: BasicBlock,
517         unwind: Option<BasicBlock>
518     },
519
520     /// Drop the Lvalue and assign the new value over it
521     DropAndReplace {
522         location: Lvalue<'tcx>,
523         value: Operand<'tcx>,
524         target: BasicBlock,
525         unwind: Option<BasicBlock>,
526     },
527
528     /// Block ends with a call of a converging function
529     Call {
530         /// The function that’s being called
531         func: Operand<'tcx>,
532         /// Arguments the function is called with
533         args: Vec<Operand<'tcx>>,
534         /// Destination for the return value. If some, the call is converging.
535         destination: Option<(Lvalue<'tcx>, BasicBlock)>,
536         /// Cleanups to be done if the call unwinds.
537         cleanup: Option<BasicBlock>
538     },
539
540     /// Jump to the target if the condition has the expected value,
541     /// otherwise panic with a message and a cleanup target.
542     Assert {
543         cond: Operand<'tcx>,
544         expected: bool,
545         msg: AssertMessage<'tcx>,
546         target: BasicBlock,
547         cleanup: Option<BasicBlock>
548     }
549 }
550
551 impl<'tcx> Terminator<'tcx> {
552     pub fn successors(&self) -> Cow<[BasicBlock]> {
553         self.kind.successors()
554     }
555
556     pub fn successors_mut(&mut self) -> Vec<&mut BasicBlock> {
557         self.kind.successors_mut()
558     }
559 }
560
561 impl<'tcx> TerminatorKind<'tcx> {
562     pub fn if_<'a, 'gcx>(tcx: ty::TyCtxt<'a, 'gcx, 'tcx>, cond: Operand<'tcx>,
563                          t: BasicBlock, f: BasicBlock) -> TerminatorKind<'tcx> {
564         static BOOL_SWITCH_FALSE: &'static [ConstInt] = &[ConstInt::U8(0)];
565         TerminatorKind::SwitchInt {
566             discr: cond,
567             switch_ty: tcx.types.bool,
568             values: From::from(BOOL_SWITCH_FALSE),
569             targets: vec![f, t],
570         }
571     }
572
573     pub fn successors(&self) -> Cow<[BasicBlock]> {
574         use self::TerminatorKind::*;
575         match *self {
576             Goto { target: ref b } => slice::ref_slice(b).into_cow(),
577             SwitchInt { targets: ref b, .. } => b[..].into_cow(),
578             Resume => (&[]).into_cow(),
579             Return => (&[]).into_cow(),
580             Unreachable => (&[]).into_cow(),
581             Call { destination: Some((_, t)), cleanup: Some(c), .. } => vec![t, c].into_cow(),
582             Call { destination: Some((_, ref t)), cleanup: None, .. } =>
583                 slice::ref_slice(t).into_cow(),
584             Call { destination: None, cleanup: Some(ref c), .. } => slice::ref_slice(c).into_cow(),
585             Call { destination: None, cleanup: None, .. } => (&[]).into_cow(),
586             DropAndReplace { target, unwind: Some(unwind), .. } |
587             Drop { target, unwind: Some(unwind), .. } => {
588                 vec![target, unwind].into_cow()
589             }
590             DropAndReplace { ref target, unwind: None, .. } |
591             Drop { ref target, unwind: None, .. } => {
592                 slice::ref_slice(target).into_cow()
593             }
594             Assert { target, cleanup: Some(unwind), .. } => vec![target, unwind].into_cow(),
595             Assert { ref target, .. } => slice::ref_slice(target).into_cow(),
596         }
597     }
598
599     // FIXME: no mootable cow. I’m honestly not sure what a “cow” between `&mut [BasicBlock]` and
600     // `Vec<&mut BasicBlock>` would look like in the first place.
601     pub fn successors_mut(&mut self) -> Vec<&mut BasicBlock> {
602         use self::TerminatorKind::*;
603         match *self {
604             Goto { target: ref mut b } => vec![b],
605             SwitchInt { targets: ref mut b, .. } => b.iter_mut().collect(),
606             Resume => Vec::new(),
607             Return => Vec::new(),
608             Unreachable => Vec::new(),
609             Call { destination: Some((_, ref mut t)), cleanup: Some(ref mut c), .. } => vec![t, c],
610             Call { destination: Some((_, ref mut t)), cleanup: None, .. } => vec![t],
611             Call { destination: None, cleanup: Some(ref mut c), .. } => vec![c],
612             Call { destination: None, cleanup: None, .. } => vec![],
613             DropAndReplace { ref mut target, unwind: Some(ref mut unwind), .. } |
614             Drop { ref mut target, unwind: Some(ref mut unwind), .. } => vec![target, unwind],
615             DropAndReplace { ref mut target, unwind: None, .. } |
616             Drop { ref mut target, unwind: None, .. } => {
617                 vec![target]
618             }
619             Assert { ref mut target, cleanup: Some(ref mut unwind), .. } => vec![target, unwind],
620             Assert { ref mut target, .. } => vec![target]
621         }
622     }
623 }
624
625 impl<'tcx> BasicBlockData<'tcx> {
626     pub fn new(terminator: Option<Terminator<'tcx>>) -> BasicBlockData<'tcx> {
627         BasicBlockData {
628             statements: vec![],
629             terminator: terminator,
630             is_cleanup: false,
631         }
632     }
633
634     /// Accessor for terminator.
635     ///
636     /// Terminator may not be None after construction of the basic block is complete. This accessor
637     /// provides a convenience way to reach the terminator.
638     pub fn terminator(&self) -> &Terminator<'tcx> {
639         self.terminator.as_ref().expect("invalid terminator state")
640     }
641
642     pub fn terminator_mut(&mut self) -> &mut Terminator<'tcx> {
643         self.terminator.as_mut().expect("invalid terminator state")
644     }
645 }
646
647 impl<'tcx> Debug for TerminatorKind<'tcx> {
648     fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
649         self.fmt_head(fmt)?;
650         let successors = self.successors();
651         let labels = self.fmt_successor_labels();
652         assert_eq!(successors.len(), labels.len());
653
654         match successors.len() {
655             0 => Ok(()),
656
657             1 => write!(fmt, " -> {:?}", successors[0]),
658
659             _ => {
660                 write!(fmt, " -> [")?;
661                 for (i, target) in successors.iter().enumerate() {
662                     if i > 0 {
663                         write!(fmt, ", ")?;
664                     }
665                     write!(fmt, "{}: {:?}", labels[i], target)?;
666                 }
667                 write!(fmt, "]")
668             }
669
670         }
671     }
672 }
673
674 impl<'tcx> TerminatorKind<'tcx> {
675     /// Write the "head" part of the terminator; that is, its name and the data it uses to pick the
676     /// successor basic block, if any. The only information not inlcuded is the list of possible
677     /// successors, which may be rendered differently between the text and the graphviz format.
678     pub fn fmt_head<W: Write>(&self, fmt: &mut W) -> fmt::Result {
679         use self::TerminatorKind::*;
680         match *self {
681             Goto { .. } => write!(fmt, "goto"),
682             SwitchInt { discr: ref lv, .. } => write!(fmt, "switchInt({:?})", lv),
683             Return => write!(fmt, "return"),
684             Resume => write!(fmt, "resume"),
685             Unreachable => write!(fmt, "unreachable"),
686             Drop { ref location, .. } => write!(fmt, "drop({:?})", location),
687             DropAndReplace { ref location, ref value, .. } =>
688                 write!(fmt, "replace({:?} <- {:?})", location, value),
689             Call { ref func, ref args, ref destination, .. } => {
690                 if let Some((ref destination, _)) = *destination {
691                     write!(fmt, "{:?} = ", destination)?;
692                 }
693                 write!(fmt, "{:?}(", func)?;
694                 for (index, arg) in args.iter().enumerate() {
695                     if index > 0 {
696                         write!(fmt, ", ")?;
697                     }
698                     write!(fmt, "{:?}", arg)?;
699                 }
700                 write!(fmt, ")")
701             }
702             Assert { ref cond, expected, ref msg, .. } => {
703                 write!(fmt, "assert(")?;
704                 if !expected {
705                     write!(fmt, "!")?;
706                 }
707                 write!(fmt, "{:?}, ", cond)?;
708
709                 match *msg {
710                     AssertMessage::BoundsCheck { ref len, ref index } => {
711                         write!(fmt, "{:?}, {:?}, {:?}",
712                                "index out of bounds: the len is {} but the index is {}",
713                                len, index)?;
714                     }
715                     AssertMessage::Math(ref err) => {
716                         write!(fmt, "{:?}", err.description())?;
717                     }
718                 }
719
720                 write!(fmt, ")")
721             }
722         }
723     }
724
725     /// Return the list of labels for the edges to the successor basic blocks.
726     pub fn fmt_successor_labels(&self) -> Vec<Cow<'static, str>> {
727         use self::TerminatorKind::*;
728         match *self {
729             Return | Resume | Unreachable => vec![],
730             Goto { .. } => vec!["".into()],
731             SwitchInt { ref values, .. } => {
732                 values.iter()
733                       .map(|const_val| {
734                           let mut buf = String::new();
735                           fmt_const_val(&mut buf, &ConstVal::Integral(*const_val)).unwrap();
736                           buf.into()
737                       })
738                       .chain(iter::once(String::from("otherwise").into()))
739                       .collect()
740             }
741             Call { destination: Some(_), cleanup: Some(_), .. } =>
742                 vec!["return".into_cow(), "unwind".into_cow()],
743             Call { destination: Some(_), cleanup: None, .. } => vec!["return".into_cow()],
744             Call { destination: None, cleanup: Some(_), .. } => vec!["unwind".into_cow()],
745             Call { destination: None, cleanup: None, .. } => vec![],
746             DropAndReplace { unwind: None, .. } |
747             Drop { unwind: None, .. } => vec!["return".into_cow()],
748             DropAndReplace { unwind: Some(_), .. } |
749             Drop { unwind: Some(_), .. } => {
750                 vec!["return".into_cow(), "unwind".into_cow()]
751             }
752             Assert { cleanup: None, .. } => vec!["".into()],
753             Assert { .. } =>
754                 vec!["success".into_cow(), "unwind".into_cow()]
755         }
756     }
757 }
758
759 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
760 pub enum AssertMessage<'tcx> {
761     BoundsCheck {
762         len: Operand<'tcx>,
763         index: Operand<'tcx>
764     },
765     Math(ConstMathErr)
766 }
767
768 ///////////////////////////////////////////////////////////////////////////
769 // Statements
770
771 #[derive(Clone, RustcEncodable, RustcDecodable)]
772 pub struct Statement<'tcx> {
773     pub source_info: SourceInfo,
774     pub kind: StatementKind<'tcx>,
775 }
776
777 impl<'tcx> Statement<'tcx> {
778     /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
779     /// invalidating statement indices in `Location`s.
780     pub fn make_nop(&mut self) {
781         self.kind = StatementKind::Nop
782     }
783 }
784
785 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
786 pub enum StatementKind<'tcx> {
787     /// Write the RHS Rvalue to the LHS Lvalue.
788     Assign(Lvalue<'tcx>, Rvalue<'tcx>),
789
790     /// Write the discriminant for a variant to the enum Lvalue.
791     SetDiscriminant { lvalue: Lvalue<'tcx>, variant_index: usize },
792
793     /// Start a live range for the storage of the local.
794     StorageLive(Lvalue<'tcx>),
795
796     /// End the current live range for the storage of the local.
797     StorageDead(Lvalue<'tcx>),
798
799     InlineAsm {
800         asm: InlineAsm,
801         outputs: Vec<Lvalue<'tcx>>,
802         inputs: Vec<Operand<'tcx>>
803     },
804
805     /// No-op. Useful for deleting instructions without affecting statement indices.
806     Nop,
807 }
808
809 impl<'tcx> Debug for Statement<'tcx> {
810     fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
811         use self::StatementKind::*;
812         match self.kind {
813             Assign(ref lv, ref rv) => write!(fmt, "{:?} = {:?}", lv, rv),
814             StorageLive(ref lv) => write!(fmt, "StorageLive({:?})", lv),
815             StorageDead(ref lv) => write!(fmt, "StorageDead({:?})", lv),
816             SetDiscriminant{lvalue: ref lv, variant_index: index} => {
817                 write!(fmt, "discriminant({:?}) = {:?}", lv, index)
818             },
819             InlineAsm { ref asm, ref outputs, ref inputs } => {
820                 write!(fmt, "asm!({:?} : {:?} : {:?})", asm, outputs, inputs)
821             },
822             Nop => write!(fmt, "nop"),
823         }
824     }
825 }
826
827 ///////////////////////////////////////////////////////////////////////////
828 // Lvalues
829
830 /// A path to a value; something that can be evaluated without
831 /// changing or disturbing program state.
832 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable)]
833 pub enum Lvalue<'tcx> {
834     /// local variable
835     Local(Local),
836
837     /// static or static mut variable
838     Static(Box<Static<'tcx>>),
839
840     /// projection out of an lvalue (access a field, deref a pointer, etc)
841     Projection(Box<LvalueProjection<'tcx>>),
842 }
843
844 /// The def-id of a static, along with its normalized type (which is
845 /// stored to avoid requiring normalization when reading MIR).
846 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable)]
847 pub struct Static<'tcx> {
848     pub def_id: DefId,
849     pub ty: Ty<'tcx>,
850 }
851
852 impl_stable_hash_for!(struct Static<'tcx> {
853     def_id,
854     ty
855 });
856
857 /// The `Projection` data structure defines things of the form `B.x`
858 /// or `*B` or `B[index]`. Note that it is parameterized because it is
859 /// shared between `Constant` and `Lvalue`. See the aliases
860 /// `LvalueProjection` etc below.
861 #[derive(Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
862 pub struct Projection<'tcx, B, V> {
863     pub base: B,
864     pub elem: ProjectionElem<'tcx, V>,
865 }
866
867 #[derive(Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
868 pub enum ProjectionElem<'tcx, V> {
869     Deref,
870     Field(Field, Ty<'tcx>),
871     Index(V),
872
873     /// These indices are generated by slice patterns. Easiest to explain
874     /// by example:
875     ///
876     /// ```
877     /// [X, _, .._, _, _] => { offset: 0, min_length: 4, from_end: false },
878     /// [_, X, .._, _, _] => { offset: 1, min_length: 4, from_end: false },
879     /// [_, _, .._, X, _] => { offset: 2, min_length: 4, from_end: true },
880     /// [_, _, .._, _, X] => { offset: 1, min_length: 4, from_end: true },
881     /// ```
882     ConstantIndex {
883         /// index or -index (in Python terms), depending on from_end
884         offset: u32,
885         /// thing being indexed must be at least this long
886         min_length: u32,
887         /// counting backwards from end?
888         from_end: bool,
889     },
890
891     /// These indices are generated by slice patterns.
892     ///
893     /// slice[from:-to] in Python terms.
894     Subslice {
895         from: u32,
896         to: u32,
897     },
898
899     /// "Downcast" to a variant of an ADT. Currently, we only introduce
900     /// this for ADTs with more than one variant. It may be better to
901     /// just introduce it always, or always for enums.
902     Downcast(&'tcx AdtDef, usize),
903 }
904
905 /// Alias for projections as they appear in lvalues, where the base is an lvalue
906 /// and the index is an operand.
907 pub type LvalueProjection<'tcx> = Projection<'tcx, Lvalue<'tcx>, Operand<'tcx>>;
908
909 /// Alias for projections as they appear in lvalues, where the base is an lvalue
910 /// and the index is an operand.
911 pub type LvalueElem<'tcx> = ProjectionElem<'tcx, Operand<'tcx>>;
912
913 newtype_index!(Field, "field");
914
915 impl<'tcx> Lvalue<'tcx> {
916     pub fn field(self, f: Field, ty: Ty<'tcx>) -> Lvalue<'tcx> {
917         self.elem(ProjectionElem::Field(f, ty))
918     }
919
920     pub fn deref(self) -> Lvalue<'tcx> {
921         self.elem(ProjectionElem::Deref)
922     }
923
924     pub fn downcast(self, adt_def: &'tcx AdtDef, variant_index: usize) -> Lvalue<'tcx> {
925         self.elem(ProjectionElem::Downcast(adt_def, variant_index))
926     }
927
928     pub fn index(self, index: Operand<'tcx>) -> Lvalue<'tcx> {
929         self.elem(ProjectionElem::Index(index))
930     }
931
932     pub fn elem(self, elem: LvalueElem<'tcx>) -> Lvalue<'tcx> {
933         Lvalue::Projection(Box::new(LvalueProjection {
934             base: self,
935             elem: elem,
936         }))
937     }
938 }
939
940 impl<'tcx> Debug for Lvalue<'tcx> {
941     fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
942         use self::Lvalue::*;
943
944         match *self {
945             Local(id) => write!(fmt, "{:?}", id),
946             Static(box self::Static { def_id, ty }) =>
947                 write!(fmt, "({}: {:?})", ty::tls::with(|tcx| tcx.item_path_str(def_id)), ty),
948             Projection(ref data) =>
949                 match data.elem {
950                     ProjectionElem::Downcast(ref adt_def, index) =>
951                         write!(fmt, "({:?} as {})", data.base, adt_def.variants[index].name),
952                     ProjectionElem::Deref =>
953                         write!(fmt, "(*{:?})", data.base),
954                     ProjectionElem::Field(field, ty) =>
955                         write!(fmt, "({:?}.{:?}: {:?})", data.base, field.index(), ty),
956                     ProjectionElem::Index(ref index) =>
957                         write!(fmt, "{:?}[{:?}]", data.base, index),
958                     ProjectionElem::ConstantIndex { offset, min_length, from_end: false } =>
959                         write!(fmt, "{:?}[{:?} of {:?}]", data.base, offset, min_length),
960                     ProjectionElem::ConstantIndex { offset, min_length, from_end: true } =>
961                         write!(fmt, "{:?}[-{:?} of {:?}]", data.base, offset, min_length),
962                     ProjectionElem::Subslice { from, to } if to == 0 =>
963                         write!(fmt, "{:?}[{:?}:]", data.base, from),
964                     ProjectionElem::Subslice { from, to } if from == 0 =>
965                         write!(fmt, "{:?}[:-{:?}]", data.base, to),
966                     ProjectionElem::Subslice { from, to } =>
967                         write!(fmt, "{:?}[{:?}:-{:?}]", data.base,
968                                from, to),
969
970                 },
971         }
972     }
973 }
974
975 ///////////////////////////////////////////////////////////////////////////
976 // Scopes
977
978 newtype_index!(VisibilityScope, "scope");
979 pub const ARGUMENT_VISIBILITY_SCOPE : VisibilityScope = VisibilityScope(0);
980
981 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
982 pub struct VisibilityScopeData {
983     pub span: Span,
984     pub parent_scope: Option<VisibilityScope>,
985 }
986
987 ///////////////////////////////////////////////////////////////////////////
988 // Operands
989
990 /// These are values that can appear inside an rvalue (or an index
991 /// lvalue). They are intentionally limited to prevent rvalues from
992 /// being nested in one another.
993 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable)]
994 pub enum Operand<'tcx> {
995     Consume(Lvalue<'tcx>),
996     Constant(Constant<'tcx>),
997 }
998
999 impl<'tcx> Debug for Operand<'tcx> {
1000     fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
1001         use self::Operand::*;
1002         match *self {
1003             Constant(ref a) => write!(fmt, "{:?}", a),
1004             Consume(ref lv) => write!(fmt, "{:?}", lv),
1005         }
1006     }
1007 }
1008
1009 impl<'tcx> Operand<'tcx> {
1010     pub fn function_handle<'a>(
1011         tcx: ty::TyCtxt<'a, 'tcx, 'tcx>,
1012         def_id: DefId,
1013         substs: &'tcx Substs<'tcx>,
1014         span: Span,
1015     ) -> Self {
1016         Operand::Constant(Constant {
1017             span: span,
1018             ty: tcx.item_type(def_id).subst(tcx, substs),
1019             literal: Literal::Value { value: ConstVal::Function(def_id, substs) },
1020         })
1021     }
1022
1023 }
1024
1025 ///////////////////////////////////////////////////////////////////////////
1026 /// Rvalues
1027
1028 #[derive(Clone, RustcEncodable, RustcDecodable)]
1029 pub enum Rvalue<'tcx> {
1030     /// x (either a move or copy, depending on type of x)
1031     Use(Operand<'tcx>),
1032
1033     /// [x; 32]
1034     Repeat(Operand<'tcx>, ConstUsize),
1035
1036     /// &x or &mut x
1037     Ref(&'tcx Region, BorrowKind, Lvalue<'tcx>),
1038
1039     /// length of a [X] or [X;n] value
1040     Len(Lvalue<'tcx>),
1041
1042     Cast(CastKind, Operand<'tcx>, Ty<'tcx>),
1043
1044     BinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
1045     CheckedBinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
1046
1047     UnaryOp(UnOp, Operand<'tcx>),
1048
1049     /// Read the discriminant of an ADT.
1050     ///
1051     /// Undefined (i.e. no effort is made to make it defined, but there’s no reason why it cannot
1052     /// be defined to return, say, a 0) if ADT is not an enum.
1053     Discriminant(Lvalue<'tcx>),
1054
1055     /// Creates an *uninitialized* Box
1056     Box(Ty<'tcx>),
1057
1058     /// Create an aggregate value, like a tuple or struct.  This is
1059     /// only needed because we want to distinguish `dest = Foo { x:
1060     /// ..., y: ... }` from `dest.x = ...; dest.y = ...;` in the case
1061     /// that `Foo` has a destructor. These rvalues can be optimized
1062     /// away after type-checking and before lowering.
1063     Aggregate(AggregateKind<'tcx>, Vec<Operand<'tcx>>),
1064 }
1065
1066 #[derive(Clone, Copy, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
1067 pub enum CastKind {
1068     Misc,
1069
1070     /// Convert unique, zero-sized type for a fn to fn()
1071     ReifyFnPointer,
1072
1073     /// Convert non capturing closure to fn()
1074     ClosureFnPointer,
1075
1076     /// Convert safe fn() to unsafe fn()
1077     UnsafeFnPointer,
1078
1079     /// "Unsize" -- convert a thin-or-fat pointer to a fat pointer.
1080     /// trans must figure out the details once full monomorphization
1081     /// is known. For example, this could be used to cast from a
1082     /// `&[i32;N]` to a `&[i32]`, or a `Box<T>` to a `Box<Trait>`
1083     /// (presuming `T: Trait`).
1084     Unsize,
1085 }
1086
1087 #[derive(Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
1088 pub enum AggregateKind<'tcx> {
1089     /// The type is of the element
1090     Array(Ty<'tcx>),
1091     Tuple,
1092     /// The second field is variant number (discriminant), it's equal to 0
1093     /// for struct and union expressions. The fourth field is active field
1094     /// number and is present only for union expressions.
1095     Adt(&'tcx AdtDef, usize, &'tcx Substs<'tcx>, Option<usize>),
1096     Closure(DefId, ClosureSubsts<'tcx>),
1097 }
1098
1099 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
1100 pub enum BinOp {
1101     /// The `+` operator (addition)
1102     Add,
1103     /// The `-` operator (subtraction)
1104     Sub,
1105     /// The `*` operator (multiplication)
1106     Mul,
1107     /// The `/` operator (division)
1108     Div,
1109     /// The `%` operator (modulus)
1110     Rem,
1111     /// The `^` operator (bitwise xor)
1112     BitXor,
1113     /// The `&` operator (bitwise and)
1114     BitAnd,
1115     /// The `|` operator (bitwise or)
1116     BitOr,
1117     /// The `<<` operator (shift left)
1118     Shl,
1119     /// The `>>` operator (shift right)
1120     Shr,
1121     /// The `==` operator (equality)
1122     Eq,
1123     /// The `<` operator (less than)
1124     Lt,
1125     /// The `<=` operator (less than or equal to)
1126     Le,
1127     /// The `!=` operator (not equal to)
1128     Ne,
1129     /// The `>=` operator (greater than or equal to)
1130     Ge,
1131     /// The `>` operator (greater than)
1132     Gt,
1133 }
1134
1135 impl BinOp {
1136     pub fn is_checkable(self) -> bool {
1137         use self::BinOp::*;
1138         match self {
1139             Add | Sub | Mul | Shl | Shr => true,
1140             _ => false
1141         }
1142     }
1143 }
1144
1145 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
1146 pub enum UnOp {
1147     /// The `!` operator for logical inversion
1148     Not,
1149     /// The `-` operator for negation
1150     Neg,
1151 }
1152
1153 impl<'tcx> Debug for Rvalue<'tcx> {
1154     fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
1155         use self::Rvalue::*;
1156
1157         match *self {
1158             Use(ref lvalue) => write!(fmt, "{:?}", lvalue),
1159             Repeat(ref a, ref b) => write!(fmt, "[{:?}; {:?}]", a, b),
1160             Len(ref a) => write!(fmt, "Len({:?})", a),
1161             Cast(ref kind, ref lv, ref ty) => write!(fmt, "{:?} as {:?} ({:?})", lv, ty, kind),
1162             BinaryOp(ref op, ref a, ref b) => write!(fmt, "{:?}({:?}, {:?})", op, a, b),
1163             CheckedBinaryOp(ref op, ref a, ref b) => {
1164                 write!(fmt, "Checked{:?}({:?}, {:?})", op, a, b)
1165             }
1166             UnaryOp(ref op, ref a) => write!(fmt, "{:?}({:?})", op, a),
1167             Discriminant(ref lval) => write!(fmt, "discriminant({:?})", lval),
1168             Box(ref t) => write!(fmt, "Box({:?})", t),
1169             Ref(_, borrow_kind, ref lv) => {
1170                 let kind_str = match borrow_kind {
1171                     BorrowKind::Shared => "",
1172                     BorrowKind::Mut | BorrowKind::Unique => "mut ",
1173                 };
1174                 write!(fmt, "&{}{:?}", kind_str, lv)
1175             }
1176
1177             Aggregate(ref kind, ref lvs) => {
1178                 fn fmt_tuple(fmt: &mut Formatter, lvs: &[Operand]) -> fmt::Result {
1179                     let mut tuple_fmt = fmt.debug_tuple("");
1180                     for lv in lvs {
1181                         tuple_fmt.field(lv);
1182                     }
1183                     tuple_fmt.finish()
1184                 }
1185
1186                 match *kind {
1187                     AggregateKind::Array(_) => write!(fmt, "{:?}", lvs),
1188
1189                     AggregateKind::Tuple => {
1190                         match lvs.len() {
1191                             0 => write!(fmt, "()"),
1192                             1 => write!(fmt, "({:?},)", lvs[0]),
1193                             _ => fmt_tuple(fmt, lvs),
1194                         }
1195                     }
1196
1197                     AggregateKind::Adt(adt_def, variant, substs, _) => {
1198                         let variant_def = &adt_def.variants[variant];
1199
1200                         ppaux::parameterized(fmt, substs, variant_def.did, &[])?;
1201
1202                         match variant_def.ctor_kind {
1203                             CtorKind::Const => Ok(()),
1204                             CtorKind::Fn => fmt_tuple(fmt, lvs),
1205                             CtorKind::Fictive => {
1206                                 let mut struct_fmt = fmt.debug_struct("");
1207                                 for (field, lv) in variant_def.fields.iter().zip(lvs) {
1208                                     struct_fmt.field(&field.name.as_str(), lv);
1209                                 }
1210                                 struct_fmt.finish()
1211                             }
1212                         }
1213                     }
1214
1215                     AggregateKind::Closure(def_id, _) => ty::tls::with(|tcx| {
1216                         if let Some(node_id) = tcx.hir.as_local_node_id(def_id) {
1217                             let name = format!("[closure@{:?}]", tcx.hir.span(node_id));
1218                             let mut struct_fmt = fmt.debug_struct(&name);
1219
1220                             tcx.with_freevars(node_id, |freevars| {
1221                                 for (freevar, lv) in freevars.iter().zip(lvs) {
1222                                     let def_id = freevar.def.def_id();
1223                                     let var_id = tcx.hir.as_local_node_id(def_id).unwrap();
1224                                     let var_name = tcx.local_var_name_str(var_id);
1225                                     struct_fmt.field(&var_name, lv);
1226                                 }
1227                             });
1228
1229                             struct_fmt.finish()
1230                         } else {
1231                             write!(fmt, "[closure]")
1232                         }
1233                     }),
1234                 }
1235             }
1236         }
1237     }
1238 }
1239
1240 ///////////////////////////////////////////////////////////////////////////
1241 /// Constants
1242 ///
1243 /// Two constants are equal if they are the same constant. Note that
1244 /// this does not necessarily mean that they are "==" in Rust -- in
1245 /// particular one must be wary of `NaN`!
1246
1247 #[derive(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1248 pub struct Constant<'tcx> {
1249     pub span: Span,
1250     pub ty: Ty<'tcx>,
1251     pub literal: Literal<'tcx>,
1252 }
1253
1254 newtype_index!(Promoted, "promoted");
1255
1256 #[derive(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1257 pub enum Literal<'tcx> {
1258     Item {
1259         def_id: DefId,
1260         substs: &'tcx Substs<'tcx>,
1261     },
1262     Value {
1263         value: ConstVal<'tcx>,
1264     },
1265     Promoted {
1266         // Index into the `promoted` vector of `Mir`.
1267         index: Promoted
1268     },
1269 }
1270
1271 impl<'tcx> Debug for Constant<'tcx> {
1272     fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
1273         write!(fmt, "{:?}", self.literal)
1274     }
1275 }
1276
1277 impl<'tcx> Debug for Literal<'tcx> {
1278     fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
1279         use self::Literal::*;
1280         match *self {
1281             Item { def_id, substs } => {
1282                 ppaux::parameterized(fmt, substs, def_id, &[])
1283             }
1284             Value { ref value } => {
1285                 write!(fmt, "const ")?;
1286                 fmt_const_val(fmt, value)
1287             }
1288             Promoted { index } => {
1289                 write!(fmt, "{:?}", index)
1290             }
1291         }
1292     }
1293 }
1294
1295 /// Write a `ConstVal` in a way closer to the original source code than the `Debug` output.
1296 fn fmt_const_val<W: Write>(fmt: &mut W, const_val: &ConstVal) -> fmt::Result {
1297     use middle::const_val::ConstVal::*;
1298     match *const_val {
1299         Float(f) => write!(fmt, "{:?}", f),
1300         Integral(n) => write!(fmt, "{}", n),
1301         Str(ref s) => write!(fmt, "{:?}", s),
1302         ByteStr(ref bytes) => {
1303             let escaped: String = bytes
1304                 .iter()
1305                 .flat_map(|&ch| ascii::escape_default(ch).map(|c| c as char))
1306                 .collect();
1307             write!(fmt, "b\"{}\"", escaped)
1308         }
1309         Bool(b) => write!(fmt, "{:?}", b),
1310         Char(c) => write!(fmt, "{:?}", c),
1311         Variant(def_id) |
1312         Function(def_id, _) => write!(fmt, "{}", item_path_str(def_id)),
1313         Struct(_) | Tuple(_) | Array(_) | Repeat(..) =>
1314             bug!("ConstVal `{:?}` should not be in MIR", const_val),
1315     }
1316 }
1317
1318 fn item_path_str(def_id: DefId) -> String {
1319     ty::tls::with(|tcx| tcx.item_path_str(def_id))
1320 }
1321
1322 impl<'tcx> ControlFlowGraph for Mir<'tcx> {
1323
1324     type Node = BasicBlock;
1325
1326     fn num_nodes(&self) -> usize { self.basic_blocks.len() }
1327
1328     fn start_node(&self) -> Self::Node { START_BLOCK }
1329
1330     fn predecessors<'graph>(&'graph self, node: Self::Node)
1331                             -> <Self as GraphPredecessors<'graph>>::Iter
1332     {
1333         self.predecessors_for(node).clone().into_iter()
1334     }
1335     fn successors<'graph>(&'graph self, node: Self::Node)
1336                           -> <Self as GraphSuccessors<'graph>>::Iter
1337     {
1338         self.basic_blocks[node].terminator().successors().into_owned().into_iter()
1339     }
1340 }
1341
1342 impl<'a, 'b> GraphPredecessors<'b> for Mir<'a> {
1343     type Item = BasicBlock;
1344     type Iter = IntoIter<BasicBlock>;
1345 }
1346
1347 impl<'a, 'b>  GraphSuccessors<'b> for Mir<'a> {
1348     type Item = BasicBlock;
1349     type Iter = IntoIter<BasicBlock>;
1350 }
1351
1352 #[derive(Copy, Clone, PartialEq, Eq, Hash, Ord, PartialOrd)]
1353 pub struct Location {
1354     /// the location is within this block
1355     pub block: BasicBlock,
1356
1357     /// the location is the start of the this statement; or, if `statement_index`
1358     /// == num-statements, then the start of the terminator.
1359     pub statement_index: usize,
1360 }
1361
1362 impl fmt::Debug for Location {
1363     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1364         write!(fmt, "{:?}[{}]", self.block, self.statement_index)
1365     }
1366 }
1367
1368 impl Location {
1369     pub fn dominates(&self, other: &Location, dominators: &Dominators<BasicBlock>) -> bool {
1370         if self.block == other.block {
1371             self.statement_index <= other.statement_index
1372         } else {
1373             dominators.is_dominated_by(other.block, self.block)
1374         }
1375     }
1376 }
1377
1378
1379 /*
1380  * TypeFoldable implementations for MIR types
1381  */
1382
1383 impl<'tcx> TypeFoldable<'tcx> for Mir<'tcx> {
1384     fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1385         Mir {
1386             basic_blocks: self.basic_blocks.fold_with(folder),
1387             visibility_scopes: self.visibility_scopes.clone(),
1388             promoted: self.promoted.fold_with(folder),
1389             return_ty: self.return_ty.fold_with(folder),
1390             local_decls: self.local_decls.fold_with(folder),
1391             arg_count: self.arg_count,
1392             upvar_decls: self.upvar_decls.clone(),
1393             spread_arg: self.spread_arg,
1394             span: self.span,
1395             cache: cache::Cache::new()
1396         }
1397     }
1398
1399     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1400         self.basic_blocks.visit_with(visitor) ||
1401         self.promoted.visit_with(visitor)     ||
1402         self.return_ty.visit_with(visitor)    ||
1403         self.local_decls.visit_with(visitor)
1404     }
1405 }
1406
1407 impl<'tcx> TypeFoldable<'tcx> for LocalDecl<'tcx> {
1408     fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1409         LocalDecl {
1410             ty: self.ty.fold_with(folder),
1411             ..self.clone()
1412         }
1413     }
1414
1415     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1416         self.ty.visit_with(visitor)
1417     }
1418 }
1419
1420 impl<'tcx> TypeFoldable<'tcx> for BasicBlockData<'tcx> {
1421     fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1422         BasicBlockData {
1423             statements: self.statements.fold_with(folder),
1424             terminator: self.terminator.fold_with(folder),
1425             is_cleanup: self.is_cleanup
1426         }
1427     }
1428
1429     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1430         self.statements.visit_with(visitor) || self.terminator.visit_with(visitor)
1431     }
1432 }
1433
1434 impl<'tcx> TypeFoldable<'tcx> for Statement<'tcx> {
1435     fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1436         use mir::StatementKind::*;
1437
1438         let kind = match self.kind {
1439             Assign(ref lval, ref rval) => Assign(lval.fold_with(folder), rval.fold_with(folder)),
1440             SetDiscriminant { ref lvalue, variant_index } => SetDiscriminant {
1441                 lvalue: lvalue.fold_with(folder),
1442                 variant_index: variant_index
1443             },
1444             StorageLive(ref lval) => StorageLive(lval.fold_with(folder)),
1445             StorageDead(ref lval) => StorageDead(lval.fold_with(folder)),
1446             InlineAsm { ref asm, ref outputs, ref inputs } => InlineAsm {
1447                 asm: asm.clone(),
1448                 outputs: outputs.fold_with(folder),
1449                 inputs: inputs.fold_with(folder)
1450             },
1451             Nop => Nop,
1452         };
1453         Statement {
1454             source_info: self.source_info,
1455             kind: kind
1456         }
1457     }
1458
1459     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1460         use mir::StatementKind::*;
1461
1462         match self.kind {
1463             Assign(ref lval, ref rval) => { lval.visit_with(visitor) || rval.visit_with(visitor) }
1464             SetDiscriminant { ref lvalue, .. } |
1465             StorageLive(ref lvalue) |
1466             StorageDead(ref lvalue) => lvalue.visit_with(visitor),
1467             InlineAsm { ref outputs, ref inputs, .. } =>
1468                 outputs.visit_with(visitor) || inputs.visit_with(visitor),
1469             Nop => false,
1470         }
1471     }
1472 }
1473
1474 impl<'tcx> TypeFoldable<'tcx> for Terminator<'tcx> {
1475     fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1476         use mir::TerminatorKind::*;
1477
1478         let kind = match self.kind {
1479             Goto { target } => Goto { target: target },
1480             SwitchInt { ref discr, switch_ty, ref values, ref targets } => SwitchInt {
1481                 discr: discr.fold_with(folder),
1482                 switch_ty: switch_ty.fold_with(folder),
1483                 values: values.clone(),
1484                 targets: targets.clone()
1485             },
1486             Drop { ref location, target, unwind } => Drop {
1487                 location: location.fold_with(folder),
1488                 target: target,
1489                 unwind: unwind
1490             },
1491             DropAndReplace { ref location, ref value, target, unwind } => DropAndReplace {
1492                 location: location.fold_with(folder),
1493                 value: value.fold_with(folder),
1494                 target: target,
1495                 unwind: unwind
1496             },
1497             Call { ref func, ref args, ref destination, cleanup } => {
1498                 let dest = destination.as_ref().map(|&(ref loc, dest)| {
1499                     (loc.fold_with(folder), dest)
1500                 });
1501
1502                 Call {
1503                     func: func.fold_with(folder),
1504                     args: args.fold_with(folder),
1505                     destination: dest,
1506                     cleanup: cleanup
1507                 }
1508             },
1509             Assert { ref cond, expected, ref msg, target, cleanup } => {
1510                 let msg = if let AssertMessage::BoundsCheck { ref len, ref index } = *msg {
1511                     AssertMessage::BoundsCheck {
1512                         len: len.fold_with(folder),
1513                         index: index.fold_with(folder),
1514                     }
1515                 } else {
1516                     msg.clone()
1517                 };
1518                 Assert {
1519                     cond: cond.fold_with(folder),
1520                     expected: expected,
1521                     msg: msg,
1522                     target: target,
1523                     cleanup: cleanup
1524                 }
1525             },
1526             Resume => Resume,
1527             Return => Return,
1528             Unreachable => Unreachable,
1529         };
1530         Terminator {
1531             source_info: self.source_info,
1532             kind: kind
1533         }
1534     }
1535
1536     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1537         use mir::TerminatorKind::*;
1538
1539         match self.kind {
1540             SwitchInt { ref discr, switch_ty, .. } =>
1541                 discr.visit_with(visitor) || switch_ty.visit_with(visitor),
1542             Drop { ref location, ..} => location.visit_with(visitor),
1543             DropAndReplace { ref location, ref value, ..} =>
1544                 location.visit_with(visitor) || value.visit_with(visitor),
1545             Call { ref func, ref args, ref destination, .. } => {
1546                 let dest = if let Some((ref loc, _)) = *destination {
1547                     loc.visit_with(visitor)
1548                 } else { false };
1549                 dest || func.visit_with(visitor) || args.visit_with(visitor)
1550             },
1551             Assert { ref cond, ref msg, .. } => {
1552                 if cond.visit_with(visitor) {
1553                     if let AssertMessage::BoundsCheck { ref len, ref index } = *msg {
1554                         len.visit_with(visitor) || index.visit_with(visitor)
1555                     } else {
1556                         false
1557                     }
1558                 } else {
1559                     false
1560                 }
1561             },
1562             Goto { .. } |
1563             Resume |
1564             Return |
1565             Unreachable => false
1566         }
1567     }
1568 }
1569
1570 impl<'tcx> TypeFoldable<'tcx> for Lvalue<'tcx> {
1571     fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1572         match self {
1573             &Lvalue::Projection(ref p) => Lvalue::Projection(p.fold_with(folder)),
1574             _ => self.clone()
1575         }
1576     }
1577
1578     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1579         if let &Lvalue::Projection(ref p) = self {
1580             p.visit_with(visitor)
1581         } else {
1582             false
1583         }
1584     }
1585 }
1586
1587 impl<'tcx> TypeFoldable<'tcx> for Rvalue<'tcx> {
1588     fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1589         use mir::Rvalue::*;
1590         match *self {
1591             Use(ref op) => Use(op.fold_with(folder)),
1592             Repeat(ref op, len) => Repeat(op.fold_with(folder), len),
1593             Ref(region, bk, ref lval) => Ref(region.fold_with(folder), bk, lval.fold_with(folder)),
1594             Len(ref lval) => Len(lval.fold_with(folder)),
1595             Cast(kind, ref op, ty) => Cast(kind, op.fold_with(folder), ty.fold_with(folder)),
1596             BinaryOp(op, ref rhs, ref lhs) =>
1597                 BinaryOp(op, rhs.fold_with(folder), lhs.fold_with(folder)),
1598             CheckedBinaryOp(op, ref rhs, ref lhs) =>
1599                 CheckedBinaryOp(op, rhs.fold_with(folder), lhs.fold_with(folder)),
1600             UnaryOp(op, ref val) => UnaryOp(op, val.fold_with(folder)),
1601             Discriminant(ref lval) => Discriminant(lval.fold_with(folder)),
1602             Box(ty) => Box(ty.fold_with(folder)),
1603             Aggregate(ref kind, ref fields) => {
1604                 let kind = match *kind {
1605                     AggregateKind::Array(ty) => AggregateKind::Array(ty.fold_with(folder)),
1606                     AggregateKind::Tuple => AggregateKind::Tuple,
1607                     AggregateKind::Adt(def, v, substs, n) =>
1608                         AggregateKind::Adt(def, v, substs.fold_with(folder), n),
1609                     AggregateKind::Closure(id, substs) =>
1610                         AggregateKind::Closure(id, substs.fold_with(folder))
1611                 };
1612                 Aggregate(kind, fields.fold_with(folder))
1613             }
1614         }
1615     }
1616
1617     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1618         use mir::Rvalue::*;
1619         match *self {
1620             Use(ref op) => op.visit_with(visitor),
1621             Repeat(ref op, _) => op.visit_with(visitor),
1622             Ref(region, _, ref lval) => region.visit_with(visitor) || lval.visit_with(visitor),
1623             Len(ref lval) => lval.visit_with(visitor),
1624             Cast(_, ref op, ty) => op.visit_with(visitor) || ty.visit_with(visitor),
1625             BinaryOp(_, ref rhs, ref lhs) |
1626             CheckedBinaryOp(_, ref rhs, ref lhs) =>
1627                 rhs.visit_with(visitor) || lhs.visit_with(visitor),
1628             UnaryOp(_, ref val) => val.visit_with(visitor),
1629             Discriminant(ref lval) => lval.visit_with(visitor),
1630             Box(ty) => ty.visit_with(visitor),
1631             Aggregate(ref kind, ref fields) => {
1632                 (match *kind {
1633                     AggregateKind::Array(ty) => ty.visit_with(visitor),
1634                     AggregateKind::Tuple => false,
1635                     AggregateKind::Adt(_, _, substs, _) => substs.visit_with(visitor),
1636                     AggregateKind::Closure(_, substs) => substs.visit_with(visitor)
1637                 }) || fields.visit_with(visitor)
1638             }
1639         }
1640     }
1641 }
1642
1643 impl<'tcx> TypeFoldable<'tcx> for Operand<'tcx> {
1644     fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1645         match *self {
1646             Operand::Consume(ref lval) => Operand::Consume(lval.fold_with(folder)),
1647             Operand::Constant(ref c) => Operand::Constant(c.fold_with(folder)),
1648         }
1649     }
1650
1651     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1652         match *self {
1653             Operand::Consume(ref lval) => lval.visit_with(visitor),
1654             Operand::Constant(ref c) => c.visit_with(visitor)
1655         }
1656     }
1657 }
1658
1659 impl<'tcx, B, V> TypeFoldable<'tcx> for Projection<'tcx, B, V>
1660     where B: TypeFoldable<'tcx>, V: TypeFoldable<'tcx>
1661 {
1662     fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1663         use mir::ProjectionElem::*;
1664
1665         let base = self.base.fold_with(folder);
1666         let elem = match self.elem {
1667             Deref => Deref,
1668             Field(f, ty) => Field(f, ty.fold_with(folder)),
1669             Index(ref v) => Index(v.fold_with(folder)),
1670             ref elem => elem.clone()
1671         };
1672
1673         Projection {
1674             base: base,
1675             elem: elem
1676         }
1677     }
1678
1679     fn super_visit_with<Vs: TypeVisitor<'tcx>>(&self, visitor: &mut Vs) -> bool {
1680         use mir::ProjectionElem::*;
1681
1682         self.base.visit_with(visitor) ||
1683             match self.elem {
1684                 Field(_, ty) => ty.visit_with(visitor),
1685                 Index(ref v) => v.visit_with(visitor),
1686                 _ => false
1687             }
1688     }
1689 }
1690
1691 impl<'tcx> TypeFoldable<'tcx> for Constant<'tcx> {
1692     fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1693         Constant {
1694             span: self.span.clone(),
1695             ty: self.ty.fold_with(folder),
1696             literal: self.literal.fold_with(folder)
1697         }
1698     }
1699     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1700         self.ty.visit_with(visitor) || self.literal.visit_with(visitor)
1701     }
1702 }
1703
1704 impl<'tcx> TypeFoldable<'tcx> for Literal<'tcx> {
1705     fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1706         match *self {
1707             Literal::Item { def_id, substs } => Literal::Item {
1708                 def_id: def_id,
1709                 substs: substs.fold_with(folder)
1710             },
1711             _ => self.clone()
1712         }
1713     }
1714     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1715         match *self {
1716             Literal::Item { substs, .. } => substs.visit_with(visitor),
1717             _ => false
1718         }
1719     }
1720 }