]> git.lizzy.rs Git - rust.git/blob - src/librustc/mir/mod.rs
Nuke the entire ctfe from orbit, it's the only way to be sure
[rust.git] / src / librustc / mir / mod.rs
1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! MIR datatypes and passes. See the module-level [README] for details.
12 //!
13 //! [README]: https://github.com/rust-lang/rust/blob/master/src/librustc/mir/README.md
14
15 use graphviz::IntoCow;
16 use middle::const_val::ConstVal;
17 use middle::region;
18 use rustc_const_math::{ConstUsize, ConstMathErr};
19 use rustc_data_structures::sync::{Lrc};
20 use rustc_data_structures::indexed_vec::{IndexVec, Idx};
21 use rustc_data_structures::control_flow_graph::dominators::{Dominators, dominators};
22 use rustc_data_structures::control_flow_graph::{GraphPredecessors, GraphSuccessors};
23 use rustc_data_structures::control_flow_graph::ControlFlowGraph;
24 use rustc_serialize as serialize;
25 use hir::def::CtorKind;
26 use hir::def_id::DefId;
27 use mir::visit::MirVisitable;
28 use mir::interpret::{Value, PrimVal};
29 use ty::subst::{Subst, Substs};
30 use ty::{self, AdtDef, ClosureSubsts, Region, Ty, TyCtxt, GeneratorInterior};
31 use ty::fold::{TypeFoldable, TypeFolder, TypeVisitor};
32 use ty::TypeAndMut;
33 use util::ppaux;
34 use std::slice;
35 use hir::{self, InlineAsm};
36 use std::borrow::{Cow};
37 use std::cell::Ref;
38 use std::fmt::{self, Debug, Formatter, Write};
39 use std::{iter, mem, u32};
40 use std::ops::{Index, IndexMut};
41 use std::vec::IntoIter;
42 use syntax::ast::{self, Name};
43 use syntax::symbol::InternedString;
44 use syntax_pos::{Span, DUMMY_SP};
45
46 mod cache;
47 pub mod tcx;
48 pub mod visit;
49 pub mod traversal;
50 pub mod interpret;
51 pub mod mono;
52
53 /// Types for locals
54 type LocalDecls<'tcx> = IndexVec<Local, LocalDecl<'tcx>>;
55
56 pub trait HasLocalDecls<'tcx> {
57     fn local_decls(&self) -> &LocalDecls<'tcx>;
58 }
59
60 impl<'tcx> HasLocalDecls<'tcx> for LocalDecls<'tcx> {
61     fn local_decls(&self) -> &LocalDecls<'tcx> {
62         self
63     }
64 }
65
66 impl<'tcx> HasLocalDecls<'tcx> for Mir<'tcx> {
67     fn local_decls(&self) -> &LocalDecls<'tcx> {
68         &self.local_decls
69     }
70 }
71
72 /// Lowered representation of a single function.
73 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
74 pub struct Mir<'tcx> {
75     /// List of basic blocks. References to basic block use a newtyped index type `BasicBlock`
76     /// that indexes into this vector.
77     basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
78
79     /// List of visibility (lexical) scopes; these are referenced by statements
80     /// and used (eventually) for debuginfo. Indexed by a `VisibilityScope`.
81     pub visibility_scopes: IndexVec<VisibilityScope, VisibilityScopeData>,
82
83     /// Crate-local information for each visibility scope, that can't (and
84     /// needn't) be tracked across crates.
85     pub visibility_scope_info: ClearCrossCrate<IndexVec<VisibilityScope, VisibilityScopeInfo>>,
86
87     /// Rvalues promoted from this function, such as borrows of constants.
88     /// Each of them is the Mir of a constant with the fn's type parameters
89     /// in scope, but a separate set of locals.
90     pub promoted: IndexVec<Promoted, Mir<'tcx>>,
91
92     /// Yield type of the function, if it is a generator.
93     pub yield_ty: Option<Ty<'tcx>>,
94
95     /// Generator drop glue
96     pub generator_drop: Option<Box<Mir<'tcx>>>,
97
98     /// The layout of a generator. Produced by the state transformation.
99     pub generator_layout: Option<GeneratorLayout<'tcx>>,
100
101     /// Declarations of locals.
102     ///
103     /// The first local is the return value pointer, followed by `arg_count`
104     /// locals for the function arguments, followed by any user-declared
105     /// variables and temporaries.
106     pub local_decls: LocalDecls<'tcx>,
107
108     /// Number of arguments this function takes.
109     ///
110     /// Starting at local 1, `arg_count` locals will be provided by the caller
111     /// and can be assumed to be initialized.
112     ///
113     /// If this MIR was built for a constant, this will be 0.
114     pub arg_count: usize,
115
116     /// Names and capture modes of all the closure upvars, assuming
117     /// the first argument is either the closure or a reference to it.
118     pub upvar_decls: Vec<UpvarDecl>,
119
120     /// Mark an argument local (which must be a tuple) as getting passed as
121     /// its individual components at the LLVM level.
122     ///
123     /// This is used for the "rust-call" ABI.
124     pub spread_arg: Option<Local>,
125
126     /// A span representing this MIR, for error reporting
127     pub span: Span,
128
129     /// A cache for various calculations
130     cache: cache::Cache
131 }
132
133 /// where execution begins
134 pub const START_BLOCK: BasicBlock = BasicBlock(0);
135
136 impl<'tcx> Mir<'tcx> {
137     pub fn new(basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
138                visibility_scopes: IndexVec<VisibilityScope, VisibilityScopeData>,
139                visibility_scope_info: ClearCrossCrate<IndexVec<VisibilityScope,
140                                                                VisibilityScopeInfo>>,
141                promoted: IndexVec<Promoted, Mir<'tcx>>,
142                yield_ty: Option<Ty<'tcx>>,
143                local_decls: IndexVec<Local, LocalDecl<'tcx>>,
144                arg_count: usize,
145                upvar_decls: Vec<UpvarDecl>,
146                span: Span) -> Self
147     {
148         // We need `arg_count` locals, and one for the return place
149         assert!(local_decls.len() >= arg_count + 1,
150             "expected at least {} locals, got {}", arg_count + 1, local_decls.len());
151
152         Mir {
153             basic_blocks,
154             visibility_scopes,
155             visibility_scope_info,
156             promoted,
157             yield_ty,
158             generator_drop: None,
159             generator_layout: None,
160             local_decls,
161             arg_count,
162             upvar_decls,
163             spread_arg: None,
164             span,
165             cache: cache::Cache::new()
166         }
167     }
168
169     #[inline]
170     pub fn basic_blocks(&self) -> &IndexVec<BasicBlock, BasicBlockData<'tcx>> {
171         &self.basic_blocks
172     }
173
174     #[inline]
175     pub fn basic_blocks_mut(&mut self) -> &mut IndexVec<BasicBlock, BasicBlockData<'tcx>> {
176         self.cache.invalidate();
177         &mut self.basic_blocks
178     }
179
180     #[inline]
181     pub fn basic_blocks_and_local_decls_mut(&mut self) -> (
182         &mut IndexVec<BasicBlock, BasicBlockData<'tcx>>,
183         &mut LocalDecls<'tcx>,
184     ) {
185         self.cache.invalidate();
186         (&mut self.basic_blocks, &mut self.local_decls)
187     }
188
189     #[inline]
190     pub fn predecessors(&self) -> Ref<IndexVec<BasicBlock, Vec<BasicBlock>>> {
191         self.cache.predecessors(self)
192     }
193
194     #[inline]
195     pub fn predecessors_for(&self, bb: BasicBlock) -> Ref<Vec<BasicBlock>> {
196         Ref::map(self.predecessors(), |p| &p[bb])
197     }
198
199     #[inline]
200     pub fn dominators(&self) -> Dominators<BasicBlock> {
201         dominators(self)
202     }
203
204     #[inline]
205     pub fn local_kind(&self, local: Local) -> LocalKind {
206         let index = local.0 as usize;
207         if index == 0 {
208             debug_assert!(self.local_decls[local].mutability == Mutability::Mut,
209                           "return place should be mutable");
210
211             LocalKind::ReturnPointer
212         } else if index < self.arg_count + 1 {
213             LocalKind::Arg
214         } else if self.local_decls[local].name.is_some() {
215             LocalKind::Var
216         } else {
217             debug_assert!(self.local_decls[local].mutability == Mutability::Mut,
218                           "temp should be mutable");
219
220             LocalKind::Temp
221         }
222     }
223
224     /// Returns an iterator over all temporaries.
225     #[inline]
226     pub fn temps_iter<'a>(&'a self) -> impl Iterator<Item=Local> + 'a {
227         (self.arg_count+1..self.local_decls.len()).filter_map(move |index| {
228             let local = Local::new(index);
229             if self.local_decls[local].is_user_variable {
230                 None
231             } else {
232                 Some(local)
233             }
234         })
235     }
236
237     /// Returns an iterator over all user-declared locals.
238     #[inline]
239     pub fn vars_iter<'a>(&'a self) -> impl Iterator<Item=Local> + 'a {
240         (self.arg_count+1..self.local_decls.len()).filter_map(move |index| {
241             let local = Local::new(index);
242             if self.local_decls[local].is_user_variable {
243                 Some(local)
244             } else {
245                 None
246             }
247         })
248     }
249
250     /// Returns an iterator over all function arguments.
251     #[inline]
252     pub fn args_iter(&self) -> impl Iterator<Item=Local> {
253         let arg_count = self.arg_count;
254         (1..arg_count+1).map(Local::new)
255     }
256
257     /// Returns an iterator over all user-defined variables and compiler-generated temporaries (all
258     /// locals that are neither arguments nor the return place).
259     #[inline]
260     pub fn vars_and_temps_iter(&self) -> impl Iterator<Item=Local> {
261         let arg_count = self.arg_count;
262         let local_count = self.local_decls.len();
263         (arg_count+1..local_count).map(Local::new)
264     }
265
266     /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
267     /// invalidating statement indices in `Location`s.
268     pub fn make_statement_nop(&mut self, location: Location) {
269         let block = &mut self[location.block];
270         debug_assert!(location.statement_index < block.statements.len());
271         block.statements[location.statement_index].make_nop()
272     }
273
274     /// Returns the source info associated with `location`.
275     pub fn source_info(&self, location: Location) -> &SourceInfo {
276         let block = &self[location.block];
277         let stmts = &block.statements;
278         let idx = location.statement_index;
279         if idx < stmts.len() {
280             &stmts[idx].source_info
281         } else {
282             assert!(idx == stmts.len());
283             &block.terminator().source_info
284         }
285     }
286
287     /// Return the return type, it always return first element from `local_decls` array
288     pub fn return_ty(&self) -> Ty<'tcx> {
289         self.local_decls[RETURN_PLACE].ty
290     }
291 }
292
293 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
294 pub struct VisibilityScopeInfo {
295     /// A NodeId with lint levels equivalent to this scope's lint levels.
296     pub lint_root: ast::NodeId,
297     /// The unsafe block that contains this node.
298     pub safety: Safety,
299 }
300
301 #[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable)]
302 pub enum Safety {
303     Safe,
304     /// Unsafe because of a PushUnsafeBlock
305     BuiltinUnsafe,
306     /// Unsafe because of an unsafe fn
307     FnUnsafe,
308     /// Unsafe because of an `unsafe` block
309     ExplicitUnsafe(ast::NodeId)
310 }
311
312 impl_stable_hash_for!(struct Mir<'tcx> {
313     basic_blocks,
314     visibility_scopes,
315     visibility_scope_info,
316     promoted,
317     yield_ty,
318     generator_drop,
319     generator_layout,
320     local_decls,
321     arg_count,
322     upvar_decls,
323     spread_arg,
324     span,
325     cache
326 });
327
328 impl<'tcx> Index<BasicBlock> for Mir<'tcx> {
329     type Output = BasicBlockData<'tcx>;
330
331     #[inline]
332     fn index(&self, index: BasicBlock) -> &BasicBlockData<'tcx> {
333         &self.basic_blocks()[index]
334     }
335 }
336
337 impl<'tcx> IndexMut<BasicBlock> for Mir<'tcx> {
338     #[inline]
339     fn index_mut(&mut self, index: BasicBlock) -> &mut BasicBlockData<'tcx> {
340         &mut self.basic_blocks_mut()[index]
341     }
342 }
343
344 #[derive(Clone, Debug)]
345 pub enum ClearCrossCrate<T> {
346     Clear,
347     Set(T)
348 }
349
350 impl<T: serialize::Encodable> serialize::UseSpecializedEncodable for ClearCrossCrate<T> {}
351 impl<T: serialize::Decodable> serialize::UseSpecializedDecodable for ClearCrossCrate<T> {}
352
353 /// Grouped information about the source code origin of a MIR entity.
354 /// Intended to be inspected by diagnostics and debuginfo.
355 /// Most passes can work with it as a whole, within a single function.
356 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
357 pub struct SourceInfo {
358     /// Source span for the AST pertaining to this MIR entity.
359     pub span: Span,
360
361     /// The lexical visibility scope, i.e. which bindings can be seen.
362     pub scope: VisibilityScope
363 }
364
365 ///////////////////////////////////////////////////////////////////////////
366 // Mutability and borrow kinds
367
368 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
369 pub enum Mutability {
370     Mut,
371     Not,
372 }
373
374 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
375 pub enum BorrowKind {
376     /// Data must be immutable and is aliasable.
377     Shared,
378
379     /// Data must be immutable but not aliasable.  This kind of borrow
380     /// cannot currently be expressed by the user and is used only in
381     /// implicit closure bindings. It is needed when you the closure
382     /// is borrowing or mutating a mutable referent, e.g.:
383     ///
384     ///    let x: &mut isize = ...;
385     ///    let y = || *x += 5;
386     ///
387     /// If we were to try to translate this closure into a more explicit
388     /// form, we'd encounter an error with the code as written:
389     ///
390     ///    struct Env { x: & &mut isize }
391     ///    let x: &mut isize = ...;
392     ///    let y = (&mut Env { &x }, fn_ptr);  // Closure is pair of env and fn
393     ///    fn fn_ptr(env: &mut Env) { **env.x += 5; }
394     ///
395     /// This is then illegal because you cannot mutate a `&mut` found
396     /// in an aliasable location. To solve, you'd have to translate with
397     /// an `&mut` borrow:
398     ///
399     ///    struct Env { x: & &mut isize }
400     ///    let x: &mut isize = ...;
401     ///    let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
402     ///    fn fn_ptr(env: &mut Env) { **env.x += 5; }
403     ///
404     /// Now the assignment to `**env.x` is legal, but creating a
405     /// mutable pointer to `x` is not because `x` is not mutable. We
406     /// could fix this by declaring `x` as `let mut x`. This is ok in
407     /// user code, if awkward, but extra weird for closures, since the
408     /// borrow is hidden.
409     ///
410     /// So we introduce a "unique imm" borrow -- the referent is
411     /// immutable, but not aliasable. This solves the problem. For
412     /// simplicity, we don't give users the way to express this
413     /// borrow, it's just used when translating closures.
414     Unique,
415
416     /// Data is mutable and not aliasable.
417     Mut {
418         /// True if this borrow arose from method-call auto-ref
419         /// (i.e. `adjustment::Adjust::Borrow`)
420         allow_two_phase_borrow: bool
421     }
422 }
423
424 impl BorrowKind {
425     pub fn allows_two_phase_borrow(&self) -> bool {
426         match *self {
427             BorrowKind::Shared | BorrowKind::Unique => false,
428             BorrowKind::Mut { allow_two_phase_borrow } => allow_two_phase_borrow,
429         }
430     }
431 }
432
433 ///////////////////////////////////////////////////////////////////////////
434 // Variables and temps
435
436 newtype_index!(Local
437     {
438         DEBUG_FORMAT = "_{}",
439         const RETURN_PLACE = 0,
440     });
441
442 /// Classifies locals into categories. See `Mir::local_kind`.
443 #[derive(PartialEq, Eq, Debug)]
444 pub enum LocalKind {
445     /// User-declared variable binding
446     Var,
447     /// Compiler-introduced temporary
448     Temp,
449     /// Function argument
450     Arg,
451     /// Location of function's return value
452     ReturnPointer,
453 }
454
455 /// A MIR local.
456 ///
457 /// This can be a binding declared by the user, a temporary inserted by the compiler, a function
458 /// argument, or the return place.
459 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
460 pub struct LocalDecl<'tcx> {
461     /// `let mut x` vs `let x`.
462     ///
463     /// Temporaries and the return place are always mutable.
464     pub mutability: Mutability,
465
466     /// True if this corresponds to a user-declared local variable.
467     pub is_user_variable: bool,
468
469     /// True if this is an internal local
470     ///
471     /// These locals are not based on types in the source code and are only used
472     /// for a few desugarings at the moment.
473     ///
474     /// The generator transformation will sanity check the locals which are live
475     /// across a suspension point against the type components of the generator
476     /// which type checking knows are live across a suspension point. We need to
477     /// flag drop flags to avoid triggering this check as they are introduced
478     /// after typeck.
479     ///
480     /// Unsafety checking will also ignore dereferences of these locals,
481     /// so they can be used for raw pointers only used in a desugaring.
482     ///
483     /// This should be sound because the drop flags are fully algebraic, and
484     /// therefore don't affect the OIBIT or outlives properties of the
485     /// generator.
486     pub internal: bool,
487
488     /// Type of this local.
489     pub ty: Ty<'tcx>,
490
491     /// Name of the local, used in debuginfo and pretty-printing.
492     ///
493     /// Note that function arguments can also have this set to `Some(_)`
494     /// to generate better debuginfo.
495     pub name: Option<Name>,
496
497     /// Source info of the local.
498     pub source_info: SourceInfo,
499
500     /// The *syntactic* visibility scope the local is defined
501     /// in. If the local was defined in a let-statement, this
502     /// is *within* the let-statement, rather than outside
503     /// of it.
504     ///
505     /// This is needed because visibility scope of locals within a let-statement
506     /// is weird.
507     ///
508     /// The reason is that we want the local to be *within* the let-statement
509     /// for lint purposes, but we want the local to be *after* the let-statement
510     /// for names-in-scope purposes.
511     ///
512     /// That's it, if we have a let-statement like the one in this
513     /// function:
514     ///
515     /// ```
516     /// fn foo(x: &str) {
517     ///     #[allow(unused_mut)]
518     ///     let mut x: u32 = { // <- one unused mut
519     ///         let mut y: u32 = x.parse().unwrap();
520     ///         y + 2
521     ///     };
522     ///     drop(x);
523     /// }
524     /// ```
525     ///
526     /// Then, from a lint point of view, the declaration of `x: u32`
527     /// (and `y: u32`) are within the `#[allow(unused_mut)]` scope - the
528     /// lint scopes are the same as the AST/HIR nesting.
529     ///
530     /// However, from a name lookup point of view, the scopes look more like
531     /// as if the let-statements were `match` expressions:
532     ///
533     /// ```
534     /// fn foo(x: &str) {
535     ///     match {
536     ///         match x.parse().unwrap() {
537     ///             y => y + 2
538     ///         }
539     ///     } {
540     ///         x => drop(x)
541     ///     };
542     /// }
543     /// ```
544     ///
545     /// We care about the name-lookup scopes for debuginfo - if the
546     /// debuginfo instruction pointer is at the call to `x.parse()`, we
547     /// want `x` to refer to `x: &str`, but if it is at the call to
548     /// `drop(x)`, we want it to refer to `x: u32`.
549     ///
550     /// To allow both uses to work, we need to have more than a single scope
551     /// for a local. We have the `syntactic_scope` represent the
552     /// "syntactic" lint scope (with a variable being under its let
553     /// block) while the source-info scope represents the "local variable"
554     /// scope (where the "rest" of a block is under all prior let-statements).
555     ///
556     /// The end result looks like this:
557     ///
558     /// ```text
559     /// ROOT SCOPE
560     ///  │{ argument x: &str }
561     ///  │
562     ///  │ │{ #[allow(unused_mut] } // this is actually split into 2 scopes
563     ///  │ │                        // in practice because I'm lazy.
564     ///  │ │
565     ///  │ │← x.syntactic_scope
566     ///  │ │← `x.parse().unwrap()`
567     ///  │ │
568     ///  │ │ │← y.syntactic_scope
569     ///  │ │
570     ///  │ │ │{ let y: u32 }
571     ///  │ │ │
572     ///  │ │ │← y.source_info.scope
573     ///  │ │ │← `y + 2`
574     ///  │
575     ///  │ │{ let x: u32 }
576     ///  │ │← x.source_info.scope
577     ///  │ │← `drop(x)` // this accesses `x: u32`
578     /// ```
579     pub syntactic_scope: VisibilityScope,
580 }
581
582 impl<'tcx> LocalDecl<'tcx> {
583     /// Create a new `LocalDecl` for a temporary.
584     #[inline]
585     pub fn new_temp(ty: Ty<'tcx>, span: Span) -> Self {
586         LocalDecl {
587             mutability: Mutability::Mut,
588             ty,
589             name: None,
590             source_info: SourceInfo {
591                 span,
592                 scope: ARGUMENT_VISIBILITY_SCOPE
593             },
594             syntactic_scope: ARGUMENT_VISIBILITY_SCOPE,
595             internal: false,
596             is_user_variable: false
597         }
598     }
599
600     /// Create a new `LocalDecl` for a internal temporary.
601     #[inline]
602     pub fn new_internal(ty: Ty<'tcx>, span: Span) -> Self {
603         LocalDecl {
604             mutability: Mutability::Mut,
605             ty,
606             name: None,
607             source_info: SourceInfo {
608                 span,
609                 scope: ARGUMENT_VISIBILITY_SCOPE
610             },
611             syntactic_scope: ARGUMENT_VISIBILITY_SCOPE,
612             internal: true,
613             is_user_variable: false
614         }
615     }
616
617     /// Builds a `LocalDecl` for the return place.
618     ///
619     /// This must be inserted into the `local_decls` list as the first local.
620     #[inline]
621     pub fn new_return_place(return_ty: Ty, span: Span) -> LocalDecl {
622         LocalDecl {
623             mutability: Mutability::Mut,
624             ty: return_ty,
625             source_info: SourceInfo {
626                 span,
627                 scope: ARGUMENT_VISIBILITY_SCOPE
628             },
629             syntactic_scope: ARGUMENT_VISIBILITY_SCOPE,
630             internal: false,
631             name: None,     // FIXME maybe we do want some name here?
632             is_user_variable: false
633         }
634     }
635 }
636
637 /// A closure capture, with its name and mode.
638 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
639 pub struct UpvarDecl {
640     pub debug_name: Name,
641
642     /// If true, the capture is behind a reference.
643     pub by_ref: bool,
644
645     pub mutability: Mutability,
646 }
647
648 ///////////////////////////////////////////////////////////////////////////
649 // BasicBlock
650
651 newtype_index!(BasicBlock { DEBUG_FORMAT = "bb{}" });
652
653 impl BasicBlock {
654     pub fn start_location(self) -> Location {
655         Location {
656             block: self,
657             statement_index: 0,
658         }
659     }
660 }
661
662 ///////////////////////////////////////////////////////////////////////////
663 // BasicBlockData and Terminator
664
665 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
666 pub struct BasicBlockData<'tcx> {
667     /// List of statements in this block.
668     pub statements: Vec<Statement<'tcx>>,
669
670     /// Terminator for this block.
671     ///
672     /// NB. This should generally ONLY be `None` during construction.
673     /// Therefore, you should generally access it via the
674     /// `terminator()` or `terminator_mut()` methods. The only
675     /// exception is that certain passes, such as `simplify_cfg`, swap
676     /// out the terminator temporarily with `None` while they continue
677     /// to recurse over the set of basic blocks.
678     pub terminator: Option<Terminator<'tcx>>,
679
680     /// If true, this block lies on an unwind path. This is used
681     /// during trans where distinct kinds of basic blocks may be
682     /// generated (particularly for MSVC cleanup). Unwind blocks must
683     /// only branch to other unwind blocks.
684     pub is_cleanup: bool,
685 }
686
687 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
688 pub struct Terminator<'tcx> {
689     pub source_info: SourceInfo,
690     pub kind: TerminatorKind<'tcx>
691 }
692
693 #[derive(Clone, RustcEncodable, RustcDecodable)]
694 pub enum TerminatorKind<'tcx> {
695     /// block should have one successor in the graph; we jump there
696     Goto {
697         target: BasicBlock,
698     },
699
700     /// operand evaluates to an integer; jump depending on its value
701     /// to one of the targets, and otherwise fallback to `otherwise`
702     SwitchInt {
703         /// discriminant value being tested
704         discr: Operand<'tcx>,
705
706         /// type of value being tested
707         switch_ty: Ty<'tcx>,
708
709         /// Possible values. The locations to branch to in each case
710         /// are found in the corresponding indices from the `targets` vector.
711         values: Cow<'tcx, [u128]>,
712
713         /// Possible branch sites. The last element of this vector is used
714         /// for the otherwise branch, so targets.len() == values.len() + 1
715         /// should hold.
716         // This invariant is quite non-obvious and also could be improved.
717         // One way to make this invariant is to have something like this instead:
718         //
719         // branches: Vec<(ConstInt, BasicBlock)>,
720         // otherwise: Option<BasicBlock> // exhaustive if None
721         //
722         // However we’ve decided to keep this as-is until we figure a case
723         // where some other approach seems to be strictly better than other.
724         targets: Vec<BasicBlock>,
725     },
726
727     /// Indicates that the landing pad is finished and unwinding should
728     /// continue. Emitted by build::scope::diverge_cleanup.
729     Resume,
730
731     /// Indicates that the landing pad is finished and that the process
732     /// should abort. Used to prevent unwinding for foreign items.
733     Abort,
734
735     /// Indicates a normal return. The return place should have
736     /// been filled in by now. This should occur at most once.
737     Return,
738
739     /// Indicates a terminator that can never be reached.
740     Unreachable,
741
742     /// Drop the Place
743     Drop {
744         location: Place<'tcx>,
745         target: BasicBlock,
746         unwind: Option<BasicBlock>
747     },
748
749     /// Drop the Place and assign the new value over it. This ensures
750     /// that the assignment to `P` occurs *even if* the destructor for
751     /// place unwinds. Its semantics are best explained by by the
752     /// elaboration:
753     ///
754     /// ```
755     /// BB0 {
756     ///   DropAndReplace(P <- V, goto BB1, unwind BB2)
757     /// }
758     /// ```
759     ///
760     /// becomes
761     ///
762     /// ```
763     /// BB0 {
764     ///   Drop(P, goto BB1, unwind BB2)
765     /// }
766     /// BB1 {
767     ///   // P is now unitialized
768     ///   P <- V
769     /// }
770     /// BB2 {
771     ///   // P is now unitialized -- its dtor panicked
772     ///   P <- V
773     /// }
774     /// ```
775     DropAndReplace {
776         location: Place<'tcx>,
777         value: Operand<'tcx>,
778         target: BasicBlock,
779         unwind: Option<BasicBlock>,
780     },
781
782     /// Block ends with a call of a converging function
783     Call {
784         /// The function that’s being called
785         func: Operand<'tcx>,
786         /// Arguments the function is called with.
787         /// These are owned by the callee, which is free to modify them.
788         /// This allows the memory occupied by "by-value" arguments to be
789         /// reused across function calls without duplicating the contents.
790         args: Vec<Operand<'tcx>>,
791         /// Destination for the return value. If some, the call is converging.
792         destination: Option<(Place<'tcx>, BasicBlock)>,
793         /// Cleanups to be done if the call unwinds.
794         cleanup: Option<BasicBlock>
795     },
796
797     /// Jump to the target if the condition has the expected value,
798     /// otherwise panic with a message and a cleanup target.
799     Assert {
800         cond: Operand<'tcx>,
801         expected: bool,
802         msg: AssertMessage<'tcx>,
803         target: BasicBlock,
804         cleanup: Option<BasicBlock>
805     },
806
807     /// A suspend point
808     Yield {
809         /// The value to return
810         value: Operand<'tcx>,
811         /// Where to resume to
812         resume: BasicBlock,
813         /// Cleanup to be done if the generator is dropped at this suspend point
814         drop: Option<BasicBlock>,
815     },
816
817     /// Indicates the end of the dropping of a generator
818     GeneratorDrop,
819
820     /// A block where control flow only ever takes one real path, but borrowck
821     /// needs to be more conservative.
822     FalseEdges {
823         /// The target normal control flow will take
824         real_target: BasicBlock,
825         /// The list of blocks control flow could conceptually take, but won't
826         /// in practice
827         imaginary_targets: Vec<BasicBlock>,
828     },
829     /// A terminator for blocks that only take one path in reality, but where we
830     /// reserve the right to unwind in borrowck, even if it won't happen in practice.
831     /// This can arise in infinite loops with no function calls for example.
832     FalseUnwind {
833         /// The target normal control flow will take
834         real_target: BasicBlock,
835         /// The imaginary cleanup block link. This particular path will never be taken
836         /// in practice, but in order to avoid fragility we want to always
837         /// consider it in borrowck. We don't want to accept programs which
838         /// pass borrowck only when panic=abort or some assertions are disabled
839         /// due to release vs. debug mode builds. This needs to be an Option because
840         /// of the remove_noop_landing_pads and no_landing_pads passes
841         unwind: Option<BasicBlock>,
842     },
843 }
844
845 impl<'tcx> Terminator<'tcx> {
846     pub fn successors(&self) -> Cow<[BasicBlock]> {
847         self.kind.successors()
848     }
849
850     pub fn successors_mut(&mut self) -> Vec<&mut BasicBlock> {
851         self.kind.successors_mut()
852     }
853
854     pub fn unwind_mut(&mut self) -> Option<&mut Option<BasicBlock>> {
855         self.kind.unwind_mut()
856     }
857 }
858
859 impl<'tcx> TerminatorKind<'tcx> {
860     pub fn if_<'a, 'gcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>, cond: Operand<'tcx>,
861                          t: BasicBlock, f: BasicBlock) -> TerminatorKind<'tcx> {
862         static BOOL_SWITCH_FALSE: &'static [u128] = &[0];
863         TerminatorKind::SwitchInt {
864             discr: cond,
865             switch_ty: tcx.types.bool,
866             values: From::from(BOOL_SWITCH_FALSE),
867             targets: vec![f, t],
868         }
869     }
870
871     pub fn successors(&self) -> Cow<[BasicBlock]> {
872         use self::TerminatorKind::*;
873         match *self {
874             Goto { target: ref b } => slice::from_ref(b).into_cow(),
875             SwitchInt { targets: ref b, .. } => b[..].into_cow(),
876             Resume | Abort | GeneratorDrop => (&[]).into_cow(),
877             Return => (&[]).into_cow(),
878             Unreachable => (&[]).into_cow(),
879             Call { destination: Some((_, t)), cleanup: Some(c), .. } => vec![t, c].into_cow(),
880             Call { destination: Some((_, ref t)), cleanup: None, .. } =>
881                 slice::from_ref(t).into_cow(),
882             Call { destination: None, cleanup: Some(ref c), .. } => slice::from_ref(c).into_cow(),
883             Call { destination: None, cleanup: None, .. } => (&[]).into_cow(),
884             Yield { resume: t, drop: Some(c), .. } => vec![t, c].into_cow(),
885             Yield { resume: ref t, drop: None, .. } => slice::from_ref(t).into_cow(),
886             DropAndReplace { target, unwind: Some(unwind), .. } |
887             Drop { target, unwind: Some(unwind), .. } => {
888                 vec![target, unwind].into_cow()
889             }
890             DropAndReplace { ref target, unwind: None, .. } |
891             Drop { ref target, unwind: None, .. } => {
892                 slice::from_ref(target).into_cow()
893             }
894             Assert { target, cleanup: Some(unwind), .. } => vec![target, unwind].into_cow(),
895             Assert { ref target, .. } => slice::from_ref(target).into_cow(),
896             FalseEdges { ref real_target, ref imaginary_targets } => {
897                 let mut s = vec![*real_target];
898                 s.extend_from_slice(imaginary_targets);
899                 s.into_cow()
900             }
901             FalseUnwind { real_target: t, unwind: Some(u) } => vec![t, u].into_cow(),
902             FalseUnwind { real_target: ref t, unwind: None } => slice::from_ref(t).into_cow(),
903         }
904     }
905
906     // FIXME: no mootable cow. I’m honestly not sure what a “cow” between `&mut [BasicBlock]` and
907     // `Vec<&mut BasicBlock>` would look like in the first place.
908     pub fn successors_mut(&mut self) -> Vec<&mut BasicBlock> {
909         use self::TerminatorKind::*;
910         match *self {
911             Goto { target: ref mut b } => vec![b],
912             SwitchInt { targets: ref mut b, .. } => b.iter_mut().collect(),
913             Resume | Abort | GeneratorDrop => Vec::new(),
914             Return => Vec::new(),
915             Unreachable => Vec::new(),
916             Call { destination: Some((_, ref mut t)), cleanup: Some(ref mut c), .. } => vec![t, c],
917             Call { destination: Some((_, ref mut t)), cleanup: None, .. } => vec![t],
918             Call { destination: None, cleanup: Some(ref mut c), .. } => vec![c],
919             Call { destination: None, cleanup: None, .. } => vec![],
920             Yield { resume: ref mut t, drop: Some(ref mut c), .. } => vec![t, c],
921             Yield { resume: ref mut t, drop: None, .. } => vec![t],
922             DropAndReplace { ref mut target, unwind: Some(ref mut unwind), .. } |
923             Drop { ref mut target, unwind: Some(ref mut unwind), .. } => vec![target, unwind],
924             DropAndReplace { ref mut target, unwind: None, .. } |
925             Drop { ref mut target, unwind: None, .. } => {
926                 vec![target]
927             }
928             Assert { ref mut target, cleanup: Some(ref mut unwind), .. } => vec![target, unwind],
929             Assert { ref mut target, .. } => vec![target],
930             FalseEdges { ref mut real_target, ref mut imaginary_targets } => {
931                 let mut s = vec![real_target];
932                 s.extend(imaginary_targets.iter_mut());
933                 s
934             }
935             FalseUnwind { real_target: ref mut t, unwind: Some(ref mut u) } => vec![t, u],
936             FalseUnwind { ref mut real_target, unwind: None } => vec![real_target],
937         }
938     }
939
940     pub fn unwind_mut(&mut self) -> Option<&mut Option<BasicBlock>> {
941         match *self {
942             TerminatorKind::Goto { .. } |
943             TerminatorKind::Resume |
944             TerminatorKind::Abort |
945             TerminatorKind::Return |
946             TerminatorKind::Unreachable |
947             TerminatorKind::GeneratorDrop |
948             TerminatorKind::Yield { .. } |
949             TerminatorKind::SwitchInt { .. } |
950             TerminatorKind::FalseEdges { .. } => {
951                 None
952             },
953             TerminatorKind::Call { cleanup: ref mut unwind, .. } |
954             TerminatorKind::Assert { cleanup: ref mut unwind, .. } |
955             TerminatorKind::DropAndReplace { ref mut unwind, .. } |
956             TerminatorKind::Drop { ref mut unwind, .. } |
957             TerminatorKind::FalseUnwind { ref mut unwind, .. } => {
958                 Some(unwind)
959             }
960         }
961     }
962 }
963
964 impl<'tcx> BasicBlockData<'tcx> {
965     pub fn new(terminator: Option<Terminator<'tcx>>) -> BasicBlockData<'tcx> {
966         BasicBlockData {
967             statements: vec![],
968             terminator,
969             is_cleanup: false,
970         }
971     }
972
973     /// Accessor for terminator.
974     ///
975     /// Terminator may not be None after construction of the basic block is complete. This accessor
976     /// provides a convenience way to reach the terminator.
977     pub fn terminator(&self) -> &Terminator<'tcx> {
978         self.terminator.as_ref().expect("invalid terminator state")
979     }
980
981     pub fn terminator_mut(&mut self) -> &mut Terminator<'tcx> {
982         self.terminator.as_mut().expect("invalid terminator state")
983     }
984
985     pub fn retain_statements<F>(&mut self, mut f: F) where F: FnMut(&mut Statement) -> bool {
986         for s in &mut self.statements {
987             if !f(s) {
988                 s.make_nop();
989             }
990         }
991     }
992
993     pub fn expand_statements<F, I>(&mut self, mut f: F)
994         where F: FnMut(&mut Statement<'tcx>) -> Option<I>,
995               I: iter::TrustedLen<Item = Statement<'tcx>>
996     {
997         // Gather all the iterators we'll need to splice in, and their positions.
998         let mut splices: Vec<(usize, I)> = vec![];
999         let mut extra_stmts = 0;
1000         for (i, s) in self.statements.iter_mut().enumerate() {
1001             if let Some(mut new_stmts) = f(s) {
1002                 if let Some(first) = new_stmts.next() {
1003                     // We can already store the first new statement.
1004                     *s = first;
1005
1006                     // Save the other statements for optimized splicing.
1007                     let remaining = new_stmts.size_hint().0;
1008                     if remaining > 0 {
1009                         splices.push((i + 1 + extra_stmts, new_stmts));
1010                         extra_stmts += remaining;
1011                     }
1012                 } else {
1013                     s.make_nop();
1014                 }
1015             }
1016         }
1017
1018         // Splice in the new statements, from the end of the block.
1019         // FIXME(eddyb) This could be more efficient with a "gap buffer"
1020         // where a range of elements ("gap") is left uninitialized, with
1021         // splicing adding new elements to the end of that gap and moving
1022         // existing elements from before the gap to the end of the gap.
1023         // For now, this is safe code, emulating a gap but initializing it.
1024         let mut gap = self.statements.len()..self.statements.len()+extra_stmts;
1025         self.statements.resize(gap.end, Statement {
1026             source_info: SourceInfo {
1027                 span: DUMMY_SP,
1028                 scope: ARGUMENT_VISIBILITY_SCOPE
1029             },
1030             kind: StatementKind::Nop
1031         });
1032         for (splice_start, new_stmts) in splices.into_iter().rev() {
1033             let splice_end = splice_start + new_stmts.size_hint().0;
1034             while gap.end > splice_end {
1035                 gap.start -= 1;
1036                 gap.end -= 1;
1037                 self.statements.swap(gap.start, gap.end);
1038             }
1039             self.statements.splice(splice_start..splice_end, new_stmts);
1040             gap.end = splice_start;
1041         }
1042     }
1043
1044     pub fn visitable(&self, index: usize) -> &dyn MirVisitable<'tcx> {
1045         if index < self.statements.len() {
1046             &self.statements[index]
1047         } else {
1048             &self.terminator
1049         }
1050     }
1051 }
1052
1053 impl<'tcx> Debug for TerminatorKind<'tcx> {
1054     fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
1055         self.fmt_head(fmt)?;
1056         let successors = self.successors();
1057         let labels = self.fmt_successor_labels();
1058         assert_eq!(successors.len(), labels.len());
1059
1060         match successors.len() {
1061             0 => Ok(()),
1062
1063             1 => write!(fmt, " -> {:?}", successors[0]),
1064
1065             _ => {
1066                 write!(fmt, " -> [")?;
1067                 for (i, target) in successors.iter().enumerate() {
1068                     if i > 0 {
1069                         write!(fmt, ", ")?;
1070                     }
1071                     write!(fmt, "{}: {:?}", labels[i], target)?;
1072                 }
1073                 write!(fmt, "]")
1074             }
1075
1076         }
1077     }
1078 }
1079
1080 impl<'tcx> TerminatorKind<'tcx> {
1081     /// Write the "head" part of the terminator; that is, its name and the data it uses to pick the
1082     /// successor basic block, if any. The only information not included is the list of possible
1083     /// successors, which may be rendered differently between the text and the graphviz format.
1084     pub fn fmt_head<W: Write>(&self, fmt: &mut W) -> fmt::Result {
1085         use self::TerminatorKind::*;
1086         match *self {
1087             Goto { .. } => write!(fmt, "goto"),
1088             SwitchInt { discr: ref place, .. } => write!(fmt, "switchInt({:?})", place),
1089             Return => write!(fmt, "return"),
1090             GeneratorDrop => write!(fmt, "generator_drop"),
1091             Resume => write!(fmt, "resume"),
1092             Abort => write!(fmt, "abort"),
1093             Yield { ref value, .. } => write!(fmt, "_1 = suspend({:?})", value),
1094             Unreachable => write!(fmt, "unreachable"),
1095             Drop { ref location, .. } => write!(fmt, "drop({:?})", location),
1096             DropAndReplace { ref location, ref value, .. } =>
1097                 write!(fmt, "replace({:?} <- {:?})", location, value),
1098             Call { ref func, ref args, ref destination, .. } => {
1099                 if let Some((ref destination, _)) = *destination {
1100                     write!(fmt, "{:?} = ", destination)?;
1101                 }
1102                 write!(fmt, "{:?}(", func)?;
1103                 for (index, arg) in args.iter().enumerate() {
1104                     if index > 0 {
1105                         write!(fmt, ", ")?;
1106                     }
1107                     write!(fmt, "{:?}", arg)?;
1108                 }
1109                 write!(fmt, ")")
1110             }
1111             Assert { ref cond, expected, ref msg, .. } => {
1112                 write!(fmt, "assert(")?;
1113                 if !expected {
1114                     write!(fmt, "!")?;
1115                 }
1116                 write!(fmt, "{:?}, ", cond)?;
1117
1118                 match *msg {
1119                     AssertMessage::BoundsCheck { ref len, ref index } => {
1120                         write!(fmt, "{:?}, {:?}, {:?}",
1121                                "index out of bounds: the len is {} but the index is {}",
1122                                len, index)?;
1123                     }
1124                     AssertMessage::Math(ref err) => {
1125                         write!(fmt, "{:?}", err.description())?;
1126                     }
1127                     AssertMessage::GeneratorResumedAfterReturn => {
1128                         write!(fmt, "{:?}", "generator resumed after completion")?;
1129                     }
1130                     AssertMessage::GeneratorResumedAfterPanic => {
1131                         write!(fmt, "{:?}", "generator resumed after panicking")?;
1132                     }
1133                 }
1134
1135                 write!(fmt, ")")
1136             },
1137             FalseEdges { .. } => write!(fmt, "falseEdges"),
1138             FalseUnwind { .. } => write!(fmt, "falseUnwind"),
1139         }
1140     }
1141
1142     /// Return the list of labels for the edges to the successor basic blocks.
1143     pub fn fmt_successor_labels(&self) -> Vec<Cow<'static, str>> {
1144         use self::TerminatorKind::*;
1145         match *self {
1146             Return | Resume | Abort | Unreachable | GeneratorDrop => vec![],
1147             Goto { .. } => vec!["".into()],
1148             SwitchInt { ref values, switch_ty, .. } => {
1149                 values.iter()
1150                       .map(|&u| {
1151                           let mut s = String::new();
1152                           print_miri_value(
1153                               Value::ByVal(PrimVal::Bytes(u)),
1154                               switch_ty,
1155                               &mut s,
1156                           ).unwrap();
1157                           s.into()
1158                       })
1159                       .chain(iter::once(String::from("otherwise").into()))
1160                       .collect()
1161             }
1162             Call { destination: Some(_), cleanup: Some(_), .. } =>
1163                 vec!["return".into_cow(), "unwind".into_cow()],
1164             Call { destination: Some(_), cleanup: None, .. } => vec!["return".into_cow()],
1165             Call { destination: None, cleanup: Some(_), .. } => vec!["unwind".into_cow()],
1166             Call { destination: None, cleanup: None, .. } => vec![],
1167             Yield { drop: Some(_), .. } =>
1168                 vec!["resume".into_cow(), "drop".into_cow()],
1169             Yield { drop: None, .. } => vec!["resume".into_cow()],
1170             DropAndReplace { unwind: None, .. } |
1171             Drop { unwind: None, .. } => vec!["return".into_cow()],
1172             DropAndReplace { unwind: Some(_), .. } |
1173             Drop { unwind: Some(_), .. } => {
1174                 vec!["return".into_cow(), "unwind".into_cow()]
1175             }
1176             Assert { cleanup: None, .. } => vec!["".into()],
1177             Assert { .. } =>
1178                 vec!["success".into_cow(), "unwind".into_cow()],
1179             FalseEdges { ref imaginary_targets, .. } => {
1180                 let mut l = vec!["real".into()];
1181                 l.resize(imaginary_targets.len() + 1, "imaginary".into());
1182                 l
1183             }
1184             FalseUnwind { unwind: Some(_), .. } => vec!["real".into(), "cleanup".into()],
1185             FalseUnwind { unwind: None, .. } => vec!["real".into()],
1186         }
1187     }
1188 }
1189
1190 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
1191 pub enum AssertMessage<'tcx> {
1192     BoundsCheck {
1193         len: Operand<'tcx>,
1194         index: Operand<'tcx>
1195     },
1196     Math(ConstMathErr),
1197     GeneratorResumedAfterReturn,
1198     GeneratorResumedAfterPanic,
1199 }
1200
1201 ///////////////////////////////////////////////////////////////////////////
1202 // Statements
1203
1204 #[derive(Clone, RustcEncodable, RustcDecodable)]
1205 pub struct Statement<'tcx> {
1206     pub source_info: SourceInfo,
1207     pub kind: StatementKind<'tcx>,
1208 }
1209
1210 impl<'tcx> Statement<'tcx> {
1211     /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
1212     /// invalidating statement indices in `Location`s.
1213     pub fn make_nop(&mut self) {
1214         self.kind = StatementKind::Nop
1215     }
1216
1217     /// Changes a statement to a nop and returns the original statement.
1218     pub fn replace_nop(&mut self) -> Self {
1219         Statement {
1220             source_info: self.source_info,
1221             kind: mem::replace(&mut self.kind, StatementKind::Nop)
1222         }
1223     }
1224 }
1225
1226 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
1227 pub enum StatementKind<'tcx> {
1228     /// Write the RHS Rvalue to the LHS Place.
1229     Assign(Place<'tcx>, Rvalue<'tcx>),
1230
1231     /// Write the discriminant for a variant to the enum Place.
1232     SetDiscriminant { place: Place<'tcx>, variant_index: usize },
1233
1234     /// Start a live range for the storage of the local.
1235     StorageLive(Local),
1236
1237     /// End the current live range for the storage of the local.
1238     StorageDead(Local),
1239
1240     /// Execute a piece of inline Assembly.
1241     InlineAsm {
1242         asm: Box<InlineAsm>,
1243         outputs: Vec<Place<'tcx>>,
1244         inputs: Vec<Operand<'tcx>>
1245     },
1246
1247     /// Assert the given places to be valid inhabitants of their type.  These statements are
1248     /// currently only interpreted by miri and only generated when "-Z mir-emit-validate" is passed.
1249     /// See <https://internals.rust-lang.org/t/types-as-contracts/5562/73> for more details.
1250     Validate(ValidationOp, Vec<ValidationOperand<'tcx, Place<'tcx>>>),
1251
1252     /// Mark one terminating point of a region scope (i.e. static region).
1253     /// (The starting point(s) arise implicitly from borrows.)
1254     EndRegion(region::Scope),
1255
1256     /// No-op. Useful for deleting instructions without affecting statement indices.
1257     Nop,
1258 }
1259
1260 /// The `ValidationOp` describes what happens with each of the operands of a
1261 /// `Validate` statement.
1262 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, PartialEq, Eq)]
1263 pub enum ValidationOp {
1264     /// Recursively traverse the place following the type and validate that all type
1265     /// invariants are maintained.  Furthermore, acquire exclusive/read-only access to the
1266     /// memory reachable from the place.
1267     Acquire,
1268     /// Recursive traverse the *mutable* part of the type and relinquish all exclusive
1269     /// access.
1270     Release,
1271     /// Recursive traverse the *mutable* part of the type and relinquish all exclusive
1272     /// access *until* the given region ends.  Then, access will be recovered.
1273     Suspend(region::Scope),
1274 }
1275
1276 impl Debug for ValidationOp {
1277     fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
1278         use self::ValidationOp::*;
1279         match *self {
1280             Acquire => write!(fmt, "Acquire"),
1281             Release => write!(fmt, "Release"),
1282             // (reuse lifetime rendering policy from ppaux.)
1283             Suspend(ref ce) => write!(fmt, "Suspend({})", ty::ReScope(*ce)),
1284         }
1285     }
1286 }
1287
1288 // This is generic so that it can be reused by miri
1289 #[derive(Clone, RustcEncodable, RustcDecodable)]
1290 pub struct ValidationOperand<'tcx, T> {
1291     pub place: T,
1292     pub ty: Ty<'tcx>,
1293     pub re: Option<region::Scope>,
1294     pub mutbl: hir::Mutability,
1295 }
1296
1297 impl<'tcx, T: Debug> Debug for ValidationOperand<'tcx, T> {
1298     fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
1299         write!(fmt, "{:?}: {:?}", self.place, self.ty)?;
1300         if let Some(ce) = self.re {
1301             // (reuse lifetime rendering policy from ppaux.)
1302             write!(fmt, "/{}", ty::ReScope(ce))?;
1303         }
1304         if let hir::MutImmutable = self.mutbl {
1305             write!(fmt, " (imm)")?;
1306         }
1307         Ok(())
1308     }
1309 }
1310
1311 impl<'tcx> Debug for Statement<'tcx> {
1312     fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
1313         use self::StatementKind::*;
1314         match self.kind {
1315             Assign(ref place, ref rv) => write!(fmt, "{:?} = {:?}", place, rv),
1316             // (reuse lifetime rendering policy from ppaux.)
1317             EndRegion(ref ce) => write!(fmt, "EndRegion({})", ty::ReScope(*ce)),
1318             Validate(ref op, ref places) => write!(fmt, "Validate({:?}, {:?})", op, places),
1319             StorageLive(ref place) => write!(fmt, "StorageLive({:?})", place),
1320             StorageDead(ref place) => write!(fmt, "StorageDead({:?})", place),
1321             SetDiscriminant { ref place, variant_index } => {
1322                 write!(fmt, "discriminant({:?}) = {:?}", place, variant_index)
1323             },
1324             InlineAsm { ref asm, ref outputs, ref inputs } => {
1325                 write!(fmt, "asm!({:?} : {:?} : {:?})", asm, outputs, inputs)
1326             },
1327             Nop => write!(fmt, "nop"),
1328         }
1329     }
1330 }
1331
1332 ///////////////////////////////////////////////////////////////////////////
1333 // Places
1334
1335 /// A path to a value; something that can be evaluated without
1336 /// changing or disturbing program state.
1337 #[derive(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1338 pub enum Place<'tcx> {
1339     /// local variable
1340     Local(Local),
1341
1342     /// static or static mut variable
1343     Static(Box<Static<'tcx>>),
1344
1345     /// projection out of a place (access a field, deref a pointer, etc)
1346     Projection(Box<PlaceProjection<'tcx>>),
1347 }
1348
1349 /// The def-id of a static, along with its normalized type (which is
1350 /// stored to avoid requiring normalization when reading MIR).
1351 #[derive(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1352 pub struct Static<'tcx> {
1353     pub def_id: DefId,
1354     pub ty: Ty<'tcx>,
1355 }
1356
1357 impl_stable_hash_for!(struct Static<'tcx> {
1358     def_id,
1359     ty
1360 });
1361
1362 /// The `Projection` data structure defines things of the form `B.x`
1363 /// or `*B` or `B[index]`. Note that it is parameterized because it is
1364 /// shared between `Constant` and `Place`. See the aliases
1365 /// `PlaceProjection` etc below.
1366 #[derive(Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1367 pub struct Projection<'tcx, B, V, T> {
1368     pub base: B,
1369     pub elem: ProjectionElem<'tcx, V, T>,
1370 }
1371
1372 #[derive(Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1373 pub enum ProjectionElem<'tcx, V, T> {
1374     Deref,
1375     Field(Field, T),
1376     Index(V),
1377
1378     /// These indices are generated by slice patterns. Easiest to explain
1379     /// by example:
1380     ///
1381     /// ```
1382     /// [X, _, .._, _, _] => { offset: 0, min_length: 4, from_end: false },
1383     /// [_, X, .._, _, _] => { offset: 1, min_length: 4, from_end: false },
1384     /// [_, _, .._, X, _] => { offset: 2, min_length: 4, from_end: true },
1385     /// [_, _, .._, _, X] => { offset: 1, min_length: 4, from_end: true },
1386     /// ```
1387     ConstantIndex {
1388         /// index or -index (in Python terms), depending on from_end
1389         offset: u32,
1390         /// thing being indexed must be at least this long
1391         min_length: u32,
1392         /// counting backwards from end?
1393         from_end: bool,
1394     },
1395
1396     /// These indices are generated by slice patterns.
1397     ///
1398     /// slice[from:-to] in Python terms.
1399     Subslice {
1400         from: u32,
1401         to: u32,
1402     },
1403
1404     /// "Downcast" to a variant of an ADT. Currently, we only introduce
1405     /// this for ADTs with more than one variant. It may be better to
1406     /// just introduce it always, or always for enums.
1407     Downcast(&'tcx AdtDef, usize),
1408 }
1409
1410 /// Alias for projections as they appear in places, where the base is a place
1411 /// and the index is a local.
1412 pub type PlaceProjection<'tcx> = Projection<'tcx, Place<'tcx>, Local, Ty<'tcx>>;
1413
1414 /// Alias for projections as they appear in places, where the base is a place
1415 /// and the index is a local.
1416 pub type PlaceElem<'tcx> = ProjectionElem<'tcx, Local, Ty<'tcx>>;
1417
1418 newtype_index!(Field { DEBUG_FORMAT = "field[{}]" });
1419
1420 impl<'tcx> Place<'tcx> {
1421     pub fn field(self, f: Field, ty: Ty<'tcx>) -> Place<'tcx> {
1422         self.elem(ProjectionElem::Field(f, ty))
1423     }
1424
1425     pub fn deref(self) -> Place<'tcx> {
1426         self.elem(ProjectionElem::Deref)
1427     }
1428
1429     pub fn downcast(self, adt_def: &'tcx AdtDef, variant_index: usize) -> Place<'tcx> {
1430         self.elem(ProjectionElem::Downcast(adt_def, variant_index))
1431     }
1432
1433     pub fn index(self, index: Local) -> Place<'tcx> {
1434         self.elem(ProjectionElem::Index(index))
1435     }
1436
1437     pub fn elem(self, elem: PlaceElem<'tcx>) -> Place<'tcx> {
1438         Place::Projection(Box::new(PlaceProjection {
1439             base: self,
1440             elem,
1441         }))
1442     }
1443 }
1444
1445 impl<'tcx> Debug for Place<'tcx> {
1446     fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
1447         use self::Place::*;
1448
1449         match *self {
1450             Local(id) => write!(fmt, "{:?}", id),
1451             Static(box self::Static { def_id, ty }) =>
1452                 write!(fmt, "({}: {:?})", ty::tls::with(|tcx| tcx.item_path_str(def_id)), ty),
1453             Projection(ref data) =>
1454                 match data.elem {
1455                     ProjectionElem::Downcast(ref adt_def, index) =>
1456                         write!(fmt, "({:?} as {})", data.base, adt_def.variants[index].name),
1457                     ProjectionElem::Deref =>
1458                         write!(fmt, "(*{:?})", data.base),
1459                     ProjectionElem::Field(field, ty) =>
1460                         write!(fmt, "({:?}.{:?}: {:?})", data.base, field.index(), ty),
1461                     ProjectionElem::Index(ref index) =>
1462                         write!(fmt, "{:?}[{:?}]", data.base, index),
1463                     ProjectionElem::ConstantIndex { offset, min_length, from_end: false } =>
1464                         write!(fmt, "{:?}[{:?} of {:?}]", data.base, offset, min_length),
1465                     ProjectionElem::ConstantIndex { offset, min_length, from_end: true } =>
1466                         write!(fmt, "{:?}[-{:?} of {:?}]", data.base, offset, min_length),
1467                     ProjectionElem::Subslice { from, to } if to == 0 =>
1468                         write!(fmt, "{:?}[{:?}:]", data.base, from),
1469                     ProjectionElem::Subslice { from, to } if from == 0 =>
1470                         write!(fmt, "{:?}[:-{:?}]", data.base, to),
1471                     ProjectionElem::Subslice { from, to } =>
1472                         write!(fmt, "{:?}[{:?}:-{:?}]", data.base,
1473                                from, to),
1474
1475                 },
1476         }
1477     }
1478 }
1479
1480 ///////////////////////////////////////////////////////////////////////////
1481 // Scopes
1482
1483 newtype_index!(VisibilityScope
1484     {
1485         DEBUG_FORMAT = "scope[{}]",
1486         const ARGUMENT_VISIBILITY_SCOPE = 0,
1487     });
1488
1489 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
1490 pub struct VisibilityScopeData {
1491     pub span: Span,
1492     pub parent_scope: Option<VisibilityScope>,
1493 }
1494
1495 ///////////////////////////////////////////////////////////////////////////
1496 // Operands
1497
1498 /// These are values that can appear inside an rvalue (or an index
1499 /// place). They are intentionally limited to prevent rvalues from
1500 /// being nested in one another.
1501 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable)]
1502 pub enum Operand<'tcx> {
1503     /// Copy: The value must be available for use afterwards.
1504     ///
1505     /// This implies that the type of the place must be `Copy`; this is true
1506     /// by construction during build, but also checked by the MIR type checker.
1507     Copy(Place<'tcx>),
1508     /// Move: The value (including old borrows of it) will not be used again.
1509     ///
1510     /// Safe for values of all types (modulo future developments towards `?Move`).
1511     /// Correct usage patterns are enforced by the borrow checker for safe code.
1512     /// `Copy` may be converted to `Move` to enable "last-use" optimizations.
1513     Move(Place<'tcx>),
1514     Constant(Box<Constant<'tcx>>),
1515 }
1516
1517 impl<'tcx> Debug for Operand<'tcx> {
1518     fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
1519         use self::Operand::*;
1520         match *self {
1521             Constant(ref a) => write!(fmt, "{:?}", a),
1522             Copy(ref place) => write!(fmt, "{:?}", place),
1523             Move(ref place) => write!(fmt, "move {:?}", place),
1524         }
1525     }
1526 }
1527
1528 impl<'tcx> Operand<'tcx> {
1529     pub fn function_handle<'a>(
1530         tcx: TyCtxt<'a, 'tcx, 'tcx>,
1531         def_id: DefId,
1532         substs: &'tcx Substs<'tcx>,
1533         span: Span,
1534     ) -> Self {
1535         let ty = tcx.type_of(def_id).subst(tcx, substs);
1536         Operand::Constant(box Constant {
1537             span,
1538             ty,
1539             literal: Literal::Value {
1540                 value: tcx.mk_const(ty::Const {
1541                     // ZST function type
1542                     val: ConstVal::Value(Value::ByVal(PrimVal::Undef)),
1543                     ty
1544                 })
1545             },
1546         })
1547     }
1548
1549     pub fn to_copy(&self) -> Self {
1550         match *self {
1551             Operand::Copy(_) | Operand::Constant(_) => self.clone(),
1552             Operand::Move(ref place) => Operand::Copy(place.clone())
1553         }
1554     }
1555 }
1556
1557 ///////////////////////////////////////////////////////////////////////////
1558 /// Rvalues
1559
1560 #[derive(Clone, RustcEncodable, RustcDecodable)]
1561 pub enum Rvalue<'tcx> {
1562     /// x (either a move or copy, depending on type of x)
1563     Use(Operand<'tcx>),
1564
1565     /// [x; 32]
1566     Repeat(Operand<'tcx>, ConstUsize),
1567
1568     /// &x or &mut x
1569     Ref(Region<'tcx>, BorrowKind, Place<'tcx>),
1570
1571     /// length of a [X] or [X;n] value
1572     Len(Place<'tcx>),
1573
1574     Cast(CastKind, Operand<'tcx>, Ty<'tcx>),
1575
1576     BinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
1577     CheckedBinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
1578
1579     NullaryOp(NullOp, Ty<'tcx>),
1580     UnaryOp(UnOp, Operand<'tcx>),
1581
1582     /// Read the discriminant of an ADT.
1583     ///
1584     /// Undefined (i.e. no effort is made to make it defined, but there’s no reason why it cannot
1585     /// be defined to return, say, a 0) if ADT is not an enum.
1586     Discriminant(Place<'tcx>),
1587
1588     /// Create an aggregate value, like a tuple or struct.  This is
1589     /// only needed because we want to distinguish `dest = Foo { x:
1590     /// ..., y: ... }` from `dest.x = ...; dest.y = ...;` in the case
1591     /// that `Foo` has a destructor. These rvalues can be optimized
1592     /// away after type-checking and before lowering.
1593     Aggregate(Box<AggregateKind<'tcx>>, Vec<Operand<'tcx>>),
1594 }
1595
1596 #[derive(Clone, Copy, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
1597 pub enum CastKind {
1598     Misc,
1599
1600     /// Convert unique, zero-sized type for a fn to fn()
1601     ReifyFnPointer,
1602
1603     /// Convert non capturing closure to fn()
1604     ClosureFnPointer,
1605
1606     /// Convert safe fn() to unsafe fn()
1607     UnsafeFnPointer,
1608
1609     /// "Unsize" -- convert a thin-or-fat pointer to a fat pointer.
1610     /// trans must figure out the details once full monomorphization
1611     /// is known. For example, this could be used to cast from a
1612     /// `&[i32;N]` to a `&[i32]`, or a `Box<T>` to a `Box<Trait>`
1613     /// (presuming `T: Trait`).
1614     Unsize,
1615 }
1616
1617 #[derive(Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
1618 pub enum AggregateKind<'tcx> {
1619     /// The type is of the element
1620     Array(Ty<'tcx>),
1621     Tuple,
1622
1623     /// The second field is the variant index. It's equal to 0 for struct
1624     /// and union expressions. The fourth field is
1625     /// active field number and is present only for union expressions
1626     /// -- e.g. for a union expression `SomeUnion { c: .. }`, the
1627     /// active field index would identity the field `c`
1628     Adt(&'tcx AdtDef, usize, &'tcx Substs<'tcx>, Option<usize>),
1629
1630     Closure(DefId, ClosureSubsts<'tcx>),
1631     Generator(DefId, ClosureSubsts<'tcx>, GeneratorInterior<'tcx>),
1632 }
1633
1634 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
1635 pub enum BinOp {
1636     /// The `+` operator (addition)
1637     Add,
1638     /// The `-` operator (subtraction)
1639     Sub,
1640     /// The `*` operator (multiplication)
1641     Mul,
1642     /// The `/` operator (division)
1643     Div,
1644     /// The `%` operator (modulus)
1645     Rem,
1646     /// The `^` operator (bitwise xor)
1647     BitXor,
1648     /// The `&` operator (bitwise and)
1649     BitAnd,
1650     /// The `|` operator (bitwise or)
1651     BitOr,
1652     /// The `<<` operator (shift left)
1653     Shl,
1654     /// The `>>` operator (shift right)
1655     Shr,
1656     /// The `==` operator (equality)
1657     Eq,
1658     /// The `<` operator (less than)
1659     Lt,
1660     /// The `<=` operator (less than or equal to)
1661     Le,
1662     /// The `!=` operator (not equal to)
1663     Ne,
1664     /// The `>=` operator (greater than or equal to)
1665     Ge,
1666     /// The `>` operator (greater than)
1667     Gt,
1668     /// The `ptr.offset` operator
1669     Offset,
1670 }
1671
1672 impl BinOp {
1673     pub fn is_checkable(self) -> bool {
1674         use self::BinOp::*;
1675         match self {
1676             Add | Sub | Mul | Shl | Shr => true,
1677             _ => false
1678         }
1679     }
1680 }
1681
1682 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
1683 pub enum NullOp {
1684     /// Return the size of a value of that type
1685     SizeOf,
1686     /// Create a new uninitialized box for a value of that type
1687     Box,
1688 }
1689
1690 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
1691 pub enum UnOp {
1692     /// The `!` operator for logical inversion
1693     Not,
1694     /// The `-` operator for negation
1695     Neg,
1696 }
1697
1698 impl<'tcx> Debug for Rvalue<'tcx> {
1699     fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
1700         use self::Rvalue::*;
1701
1702         match *self {
1703             Use(ref place) => write!(fmt, "{:?}", place),
1704             Repeat(ref a, ref b) => write!(fmt, "[{:?}; {:?}]", a, b),
1705             Len(ref a) => write!(fmt, "Len({:?})", a),
1706             Cast(ref kind, ref place, ref ty) => {
1707                 write!(fmt, "{:?} as {:?} ({:?})", place, ty, kind)
1708             }
1709             BinaryOp(ref op, ref a, ref b) => write!(fmt, "{:?}({:?}, {:?})", op, a, b),
1710             CheckedBinaryOp(ref op, ref a, ref b) => {
1711                 write!(fmt, "Checked{:?}({:?}, {:?})", op, a, b)
1712             }
1713             UnaryOp(ref op, ref a) => write!(fmt, "{:?}({:?})", op, a),
1714             Discriminant(ref place) => write!(fmt, "discriminant({:?})", place),
1715             NullaryOp(ref op, ref t) => write!(fmt, "{:?}({:?})", op, t),
1716             Ref(region, borrow_kind, ref place) => {
1717                 let kind_str = match borrow_kind {
1718                     BorrowKind::Shared => "",
1719                     BorrowKind::Mut { .. } | BorrowKind::Unique => "mut ",
1720                 };
1721
1722                 // When printing regions, add trailing space if necessary.
1723                 let region = if ppaux::verbose() || ppaux::identify_regions() {
1724                     let mut region = format!("{}", region);
1725                     if region.len() > 0 { region.push(' '); }
1726                     region
1727                 } else {
1728                     // Do not even print 'static
1729                     "".to_owned()
1730                 };
1731                 write!(fmt, "&{}{}{:?}", region, kind_str, place)
1732             }
1733
1734             Aggregate(ref kind, ref places) => {
1735                 fn fmt_tuple(fmt: &mut Formatter, places: &[Operand]) -> fmt::Result {
1736                     let mut tuple_fmt = fmt.debug_tuple("");
1737                     for place in places {
1738                         tuple_fmt.field(place);
1739                     }
1740                     tuple_fmt.finish()
1741                 }
1742
1743                 match **kind {
1744                     AggregateKind::Array(_) => write!(fmt, "{:?}", places),
1745
1746                     AggregateKind::Tuple => {
1747                         match places.len() {
1748                             0 => write!(fmt, "()"),
1749                             1 => write!(fmt, "({:?},)", places[0]),
1750                             _ => fmt_tuple(fmt, places),
1751                         }
1752                     }
1753
1754                     AggregateKind::Adt(adt_def, variant, substs, _) => {
1755                         let variant_def = &adt_def.variants[variant];
1756
1757                         ppaux::parameterized(fmt, substs, variant_def.did, &[])?;
1758
1759                         match variant_def.ctor_kind {
1760                             CtorKind::Const => Ok(()),
1761                             CtorKind::Fn => fmt_tuple(fmt, places),
1762                             CtorKind::Fictive => {
1763                                 let mut struct_fmt = fmt.debug_struct("");
1764                                 for (field, place) in variant_def.fields.iter().zip(places) {
1765                                     struct_fmt.field(&field.name.as_str(), place);
1766                                 }
1767                                 struct_fmt.finish()
1768                             }
1769                         }
1770                     }
1771
1772                     AggregateKind::Closure(def_id, _) => ty::tls::with(|tcx| {
1773                         if let Some(node_id) = tcx.hir.as_local_node_id(def_id) {
1774                             let name = if tcx.sess.opts.debugging_opts.span_free_formats {
1775                                 format!("[closure@{:?}]", node_id)
1776                             } else {
1777                                 format!("[closure@{:?}]", tcx.hir.span(node_id))
1778                             };
1779                             let mut struct_fmt = fmt.debug_struct(&name);
1780
1781                             tcx.with_freevars(node_id, |freevars| {
1782                                 for (freevar, place) in freevars.iter().zip(places) {
1783                                     let var_name = tcx.hir.name(freevar.var_id());
1784                                     struct_fmt.field(&var_name.as_str(), place);
1785                                 }
1786                             });
1787
1788                             struct_fmt.finish()
1789                         } else {
1790                             write!(fmt, "[closure]")
1791                         }
1792                     }),
1793
1794                     AggregateKind::Generator(def_id, _, _) => ty::tls::with(|tcx| {
1795                         if let Some(node_id) = tcx.hir.as_local_node_id(def_id) {
1796                             let name = format!("[generator@{:?}]", tcx.hir.span(node_id));
1797                             let mut struct_fmt = fmt.debug_struct(&name);
1798
1799                             tcx.with_freevars(node_id, |freevars| {
1800                                 for (freevar, place) in freevars.iter().zip(places) {
1801                                     let var_name = tcx.hir.name(freevar.var_id());
1802                                     struct_fmt.field(&var_name.as_str(), place);
1803                                 }
1804                                 struct_fmt.field("$state", &places[freevars.len()]);
1805                                 for i in (freevars.len() + 1)..places.len() {
1806                                     struct_fmt.field(&format!("${}", i - freevars.len() - 1),
1807                                                      &places[i]);
1808                                 }
1809                             });
1810
1811                             struct_fmt.finish()
1812                         } else {
1813                             write!(fmt, "[generator]")
1814                         }
1815                     }),
1816                 }
1817             }
1818         }
1819     }
1820 }
1821
1822 ///////////////////////////////////////////////////////////////////////////
1823 /// Constants
1824 ///
1825 /// Two constants are equal if they are the same constant. Note that
1826 /// this does not necessarily mean that they are "==" in Rust -- in
1827 /// particular one must be wary of `NaN`!
1828
1829 #[derive(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1830 pub struct Constant<'tcx> {
1831     pub span: Span,
1832     pub ty: Ty<'tcx>,
1833     pub literal: Literal<'tcx>,
1834 }
1835
1836 newtype_index!(Promoted { DEBUG_FORMAT = "promoted[{}]" });
1837
1838
1839 #[derive(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1840 pub enum Literal<'tcx> {
1841     Value {
1842         value: &'tcx ty::Const<'tcx>,
1843     },
1844     Promoted {
1845         // Index into the `promoted` vector of `Mir`.
1846         index: Promoted
1847     },
1848 }
1849
1850 impl<'tcx> Debug for Constant<'tcx> {
1851     fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
1852         write!(fmt, "{:?}", self.literal)
1853     }
1854 }
1855
1856 impl<'tcx> Debug for Literal<'tcx> {
1857     fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
1858         use self::Literal::*;
1859         match *self {
1860             Value { value } => {
1861                 write!(fmt, "const ")?;
1862                 fmt_const_val(fmt, value)
1863             }
1864             Promoted { index } => {
1865                 write!(fmt, "{:?}", index)
1866             }
1867         }
1868     }
1869 }
1870
1871 /// Write a `ConstVal` in a way closer to the original source code than the `Debug` output.
1872 fn fmt_const_val<W: Write>(fmt: &mut W, const_val: &ty::Const) -> fmt::Result {
1873     use middle::const_val::ConstVal::*;
1874     match const_val.val {
1875         Unevaluated(..) => write!(fmt, "{:?}", const_val),
1876         Value(val) => print_miri_value(val, const_val.ty, fmt),
1877     }
1878 }
1879
1880 fn print_miri_value<W: Write>(value: Value, ty: Ty, f: &mut W) -> fmt::Result {
1881     use ty::TypeVariants::*;
1882     use rustc_const_math::ConstFloat;
1883     match (value, &ty.sty) {
1884         (Value::ByVal(PrimVal::Bytes(0)), &TyBool) => write!(f, "false"),
1885         (Value::ByVal(PrimVal::Bytes(1)), &TyBool) => write!(f, "true"),
1886         (Value::ByVal(PrimVal::Bytes(bits)), &TyFloat(fty)) =>
1887             write!(f, "{}", ConstFloat { bits, ty: fty }),
1888         (Value::ByVal(PrimVal::Bytes(n)), &TyUint(ui)) => write!(f, "{:?}{}", n, ui),
1889         (Value::ByVal(PrimVal::Bytes(n)), &TyInt(i)) => write!(f, "{:?}{}", n as i128, i),
1890         (Value::ByVal(PrimVal::Bytes(n)), &TyChar) =>
1891             write!(f, "{:?}", ::std::char::from_u32(n as u32).unwrap()),
1892         (Value::ByVal(PrimVal::Undef), &TyFnDef(did, _)) =>
1893             write!(f, "{}", item_path_str(did)),
1894         (Value::ByValPair(PrimVal::Ptr(ptr), PrimVal::Bytes(len)), &TyRef(_, TypeAndMut {
1895             ty: &ty::TyS { sty: TyStr, .. }, ..
1896         })) => {
1897             ty::tls::with(|tcx| {
1898                 let alloc = tcx
1899                     .interpret_interner
1900                     .borrow()
1901                     .get_alloc(ptr.alloc_id)
1902                     .expect("miri alloc not found");
1903                 assert_eq!(len as usize as u128, len);
1904                 let slice = &alloc.bytes[(ptr.offset as usize)..][..(len as usize)];
1905                 let s = ::std::str::from_utf8(slice)
1906                     .expect("non utf8 str from miri");
1907                 write!(f, "{:?}", s)
1908             })
1909         },
1910         _ => write!(f, "{:?}:{}", value, ty),
1911     }
1912 }
1913
1914 fn item_path_str(def_id: DefId) -> String {
1915     ty::tls::with(|tcx| tcx.item_path_str(def_id))
1916 }
1917
1918 impl<'tcx> ControlFlowGraph for Mir<'tcx> {
1919
1920     type Node = BasicBlock;
1921
1922     fn num_nodes(&self) -> usize { self.basic_blocks.len() }
1923
1924     fn start_node(&self) -> Self::Node { START_BLOCK }
1925
1926     fn predecessors<'graph>(&'graph self, node: Self::Node)
1927                             -> <Self as GraphPredecessors<'graph>>::Iter
1928     {
1929         self.predecessors_for(node).clone().into_iter()
1930     }
1931     fn successors<'graph>(&'graph self, node: Self::Node)
1932                           -> <Self as GraphSuccessors<'graph>>::Iter
1933     {
1934         self.basic_blocks[node].terminator().successors().into_owned().into_iter()
1935     }
1936 }
1937
1938 impl<'a, 'b> GraphPredecessors<'b> for Mir<'a> {
1939     type Item = BasicBlock;
1940     type Iter = IntoIter<BasicBlock>;
1941 }
1942
1943 impl<'a, 'b>  GraphSuccessors<'b> for Mir<'a> {
1944     type Item = BasicBlock;
1945     type Iter = IntoIter<BasicBlock>;
1946 }
1947
1948 #[derive(Copy, Clone, PartialEq, Eq, Hash, Ord, PartialOrd)]
1949 pub struct Location {
1950     /// the location is within this block
1951     pub block: BasicBlock,
1952
1953     /// the location is the start of the statement; or, if `statement_index`
1954     /// == num-statements, then the start of the terminator.
1955     pub statement_index: usize,
1956 }
1957
1958 impl fmt::Debug for Location {
1959     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1960         write!(fmt, "{:?}[{}]", self.block, self.statement_index)
1961     }
1962 }
1963
1964 impl Location {
1965     /// Returns the location immediately after this one within the enclosing block.
1966     ///
1967     /// Note that if this location represents a terminator, then the
1968     /// resulting location would be out of bounds and invalid.
1969     pub fn successor_within_block(&self) -> Location {
1970         Location { block: self.block, statement_index: self.statement_index + 1 }
1971     }
1972
1973     pub fn dominates(&self, other: &Location, dominators: &Dominators<BasicBlock>) -> bool {
1974         if self.block == other.block {
1975             self.statement_index <= other.statement_index
1976         } else {
1977             dominators.is_dominated_by(other.block, self.block)
1978         }
1979     }
1980 }
1981
1982 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1983 pub enum UnsafetyViolationKind {
1984     General,
1985     ExternStatic(ast::NodeId),
1986     BorrowPacked(ast::NodeId),
1987 }
1988
1989 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1990 pub struct UnsafetyViolation {
1991     pub source_info: SourceInfo,
1992     pub description: InternedString,
1993     pub kind: UnsafetyViolationKind,
1994 }
1995
1996 #[derive(Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1997 pub struct UnsafetyCheckResult {
1998     /// Violations that are propagated *upwards* from this function
1999     pub violations: Lrc<[UnsafetyViolation]>,
2000     /// unsafe blocks in this function, along with whether they are used. This is
2001     /// used for the "unused_unsafe" lint.
2002     pub unsafe_blocks: Lrc<[(ast::NodeId, bool)]>,
2003 }
2004
2005 /// The layout of generator state
2006 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
2007 pub struct GeneratorLayout<'tcx> {
2008     pub fields: Vec<LocalDecl<'tcx>>,
2009 }
2010
2011 /// After we borrow check a closure, we are left with various
2012 /// requirements that we have inferred between the free regions that
2013 /// appear in the closure's signature or on its field types.  These
2014 /// requirements are then verified and proved by the closure's
2015 /// creating function. This struct encodes those requirements.
2016 ///
2017 /// The requirements are listed as being between various
2018 /// `RegionVid`. The 0th region refers to `'static`; subsequent region
2019 /// vids refer to the free regions that appear in the closure (or
2020 /// generator's) type, in order of appearance. (This numbering is
2021 /// actually defined by the `UniversalRegions` struct in the NLL
2022 /// region checker. See for example
2023 /// `UniversalRegions::closure_mapping`.) Note that we treat the free
2024 /// regions in the closure's type "as if" they were erased, so their
2025 /// precise identity is not important, only their position.
2026 ///
2027 /// Example: If type check produces a closure with the closure substs:
2028 ///
2029 /// ```text
2030 /// ClosureSubsts = [
2031 ///     i8,                                  // the "closure kind"
2032 ///     for<'x> fn(&'a &'x u32) -> &'x u32,  // the "closure signature"
2033 ///     &'a String,                          // some upvar
2034 /// ]
2035 /// ```
2036 ///
2037 /// here, there is one unique free region (`'a`) but it appears
2038 /// twice. We would "renumber" each occurrence to a unique vid, as follows:
2039 ///
2040 /// ```text
2041 /// ClosureSubsts = [
2042 ///     i8,                                  // the "closure kind"
2043 ///     for<'x> fn(&'1 &'x u32) -> &'x u32,  // the "closure signature"
2044 ///     &'2 String,                          // some upvar
2045 /// ]
2046 /// ```
2047 ///
2048 /// Now the code might impose a requirement like `'1: '2`. When an
2049 /// instance of the closure is created, the corresponding free regions
2050 /// can be extracted from its type and constrained to have the given
2051 /// outlives relationship.
2052 ///
2053 /// In some cases, we have to record outlives requirements between
2054 /// types and regions as well. In that case, if those types include
2055 /// any regions, those regions are recorded as `ReClosureBound`
2056 /// instances assigned one of these same indices. Those regions will
2057 /// be substituted away by the creator. We use `ReClosureBound` in
2058 /// that case because the regions must be allocated in the global
2059 /// TyCtxt, and hence we cannot use `ReVar` (which is what we use
2060 /// internally within the rest of the NLL code).
2061 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
2062 pub struct ClosureRegionRequirements<'gcx> {
2063     /// The number of external regions defined on the closure.  In our
2064     /// example above, it would be 3 -- one for `'static`, then `'1`
2065     /// and `'2`. This is just used for a sanity check later on, to
2066     /// make sure that the number of regions we see at the callsite
2067     /// matches.
2068     pub num_external_vids: usize,
2069
2070     /// Requirements between the various free regions defined in
2071     /// indices.
2072     pub outlives_requirements: Vec<ClosureOutlivesRequirement<'gcx>>,
2073 }
2074
2075 /// Indicates an outlives constraint between a type or between two
2076 /// free-regions declared on the closure.
2077 #[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable)]
2078 pub struct ClosureOutlivesRequirement<'tcx> {
2079     // This region or type ...
2080     pub subject: ClosureOutlivesSubject<'tcx>,
2081
2082     // .. must outlive this one.
2083     pub outlived_free_region: ty::RegionVid,
2084
2085     // If not, report an error here.
2086     pub blame_span: Span,
2087 }
2088
2089 /// The subject of a ClosureOutlivesRequirement -- that is, the thing
2090 /// that must outlive some region.
2091 #[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable)]
2092 pub enum ClosureOutlivesSubject<'tcx> {
2093     /// Subject is a type, typically a type parameter, but could also
2094     /// be a projection. Indicates a requirement like `T: 'a` being
2095     /// passed to the caller, where the type here is `T`.
2096     ///
2097     /// The type here is guaranteed not to contain any free regions at
2098     /// present.
2099     Ty(Ty<'tcx>),
2100
2101     /// Subject is a free region from the closure. Indicates a requirement
2102     /// like `'a: 'b` being passed to the caller; the region here is `'a`.
2103     Region(ty::RegionVid),
2104 }
2105
2106 /*
2107  * TypeFoldable implementations for MIR types
2108  */
2109
2110 impl<'tcx> TypeFoldable<'tcx> for Mir<'tcx> {
2111     fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
2112         Mir {
2113             basic_blocks: self.basic_blocks.fold_with(folder),
2114             visibility_scopes: self.visibility_scopes.clone(),
2115             visibility_scope_info: self.visibility_scope_info.clone(),
2116             promoted: self.promoted.fold_with(folder),
2117             yield_ty: self.yield_ty.fold_with(folder),
2118             generator_drop: self.generator_drop.fold_with(folder),
2119             generator_layout: self.generator_layout.fold_with(folder),
2120             local_decls: self.local_decls.fold_with(folder),
2121             arg_count: self.arg_count,
2122             upvar_decls: self.upvar_decls.clone(),
2123             spread_arg: self.spread_arg,
2124             span: self.span,
2125             cache: cache::Cache::new()
2126         }
2127     }
2128
2129     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
2130         self.basic_blocks.visit_with(visitor) ||
2131         self.generator_drop.visit_with(visitor) ||
2132         self.generator_layout.visit_with(visitor) ||
2133         self.yield_ty.visit_with(visitor) ||
2134         self.promoted.visit_with(visitor)     ||
2135         self.local_decls.visit_with(visitor)
2136     }
2137 }
2138
2139 impl<'tcx> TypeFoldable<'tcx> for GeneratorLayout<'tcx> {
2140     fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
2141         GeneratorLayout {
2142             fields: self.fields.fold_with(folder),
2143         }
2144     }
2145
2146     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
2147         self.fields.visit_with(visitor)
2148     }
2149 }
2150
2151 impl<'tcx> TypeFoldable<'tcx> for LocalDecl<'tcx> {
2152     fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
2153         LocalDecl {
2154             ty: self.ty.fold_with(folder),
2155             ..self.clone()
2156         }
2157     }
2158
2159     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
2160         self.ty.visit_with(visitor)
2161     }
2162 }
2163
2164 impl<'tcx> TypeFoldable<'tcx> for BasicBlockData<'tcx> {
2165     fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
2166         BasicBlockData {
2167             statements: self.statements.fold_with(folder),
2168             terminator: self.terminator.fold_with(folder),
2169             is_cleanup: self.is_cleanup
2170         }
2171     }
2172
2173     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
2174         self.statements.visit_with(visitor) || self.terminator.visit_with(visitor)
2175     }
2176 }
2177
2178 impl<'tcx> TypeFoldable<'tcx> for ValidationOperand<'tcx, Place<'tcx>> {
2179     fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
2180         ValidationOperand {
2181             place: self.place.fold_with(folder),
2182             ty: self.ty.fold_with(folder),
2183             re: self.re,
2184             mutbl: self.mutbl,
2185         }
2186     }
2187
2188     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
2189         self.place.visit_with(visitor) || self.ty.visit_with(visitor)
2190     }
2191 }
2192
2193 impl<'tcx> TypeFoldable<'tcx> for Statement<'tcx> {
2194     fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
2195         use mir::StatementKind::*;
2196
2197         let kind = match self.kind {
2198             Assign(ref place, ref rval) => Assign(place.fold_with(folder), rval.fold_with(folder)),
2199             SetDiscriminant { ref place, variant_index } => SetDiscriminant {
2200                 place: place.fold_with(folder),
2201                 variant_index,
2202             },
2203             StorageLive(ref local) => StorageLive(local.fold_with(folder)),
2204             StorageDead(ref local) => StorageDead(local.fold_with(folder)),
2205             InlineAsm { ref asm, ref outputs, ref inputs } => InlineAsm {
2206                 asm: asm.clone(),
2207                 outputs: outputs.fold_with(folder),
2208                 inputs: inputs.fold_with(folder)
2209             },
2210
2211             // Note for future: If we want to expose the region scopes
2212             // during the fold, we need to either generalize EndRegion
2213             // to carry `[ty::Region]`, or extend the `TypeFolder`
2214             // trait with a `fn fold_scope`.
2215             EndRegion(ref region_scope) => EndRegion(region_scope.clone()),
2216
2217             Validate(ref op, ref places) =>
2218                 Validate(op.clone(),
2219                          places.iter().map(|operand| operand.fold_with(folder)).collect()),
2220
2221             Nop => Nop,
2222         };
2223         Statement {
2224             source_info: self.source_info,
2225             kind,
2226         }
2227     }
2228
2229     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
2230         use mir::StatementKind::*;
2231
2232         match self.kind {
2233             Assign(ref place, ref rval) => { place.visit_with(visitor) || rval.visit_with(visitor) }
2234             SetDiscriminant { ref place, .. } => place.visit_with(visitor),
2235             StorageLive(ref local) |
2236             StorageDead(ref local) => local.visit_with(visitor),
2237             InlineAsm { ref outputs, ref inputs, .. } =>
2238                 outputs.visit_with(visitor) || inputs.visit_with(visitor),
2239
2240             // Note for future: If we want to expose the region scopes
2241             // during the visit, we need to either generalize EndRegion
2242             // to carry `[ty::Region]`, or extend the `TypeVisitor`
2243             // trait with a `fn visit_scope`.
2244             EndRegion(ref _scope) => false,
2245
2246             Validate(ref _op, ref places) =>
2247                 places.iter().any(|ty_and_place| ty_and_place.visit_with(visitor)),
2248
2249             Nop => false,
2250         }
2251     }
2252 }
2253
2254 impl<'tcx> TypeFoldable<'tcx> for Terminator<'tcx> {
2255     fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
2256         use mir::TerminatorKind::*;
2257
2258         let kind = match self.kind {
2259             Goto { target } => Goto { target: target },
2260             SwitchInt { ref discr, switch_ty, ref values, ref targets } => SwitchInt {
2261                 discr: discr.fold_with(folder),
2262                 switch_ty: switch_ty.fold_with(folder),
2263                 values: values.clone(),
2264                 targets: targets.clone()
2265             },
2266             Drop { ref location, target, unwind } => Drop {
2267                 location: location.fold_with(folder),
2268                 target,
2269                 unwind,
2270             },
2271             DropAndReplace { ref location, ref value, target, unwind } => DropAndReplace {
2272                 location: location.fold_with(folder),
2273                 value: value.fold_with(folder),
2274                 target,
2275                 unwind,
2276             },
2277             Yield { ref value, resume, drop } => Yield {
2278                 value: value.fold_with(folder),
2279                 resume: resume,
2280                 drop: drop,
2281             },
2282             Call { ref func, ref args, ref destination, cleanup } => {
2283                 let dest = destination.as_ref().map(|&(ref loc, dest)| {
2284                     (loc.fold_with(folder), dest)
2285                 });
2286
2287                 Call {
2288                     func: func.fold_with(folder),
2289                     args: args.fold_with(folder),
2290                     destination: dest,
2291                     cleanup,
2292                 }
2293             },
2294             Assert { ref cond, expected, ref msg, target, cleanup } => {
2295                 let msg = if let AssertMessage::BoundsCheck { ref len, ref index } = *msg {
2296                     AssertMessage::BoundsCheck {
2297                         len: len.fold_with(folder),
2298                         index: index.fold_with(folder),
2299                     }
2300                 } else {
2301                     msg.clone()
2302                 };
2303                 Assert {
2304                     cond: cond.fold_with(folder),
2305                     expected,
2306                     msg,
2307                     target,
2308                     cleanup,
2309                 }
2310             },
2311             GeneratorDrop => GeneratorDrop,
2312             Resume => Resume,
2313             Abort => Abort,
2314             Return => Return,
2315             Unreachable => Unreachable,
2316             FalseEdges { real_target, ref imaginary_targets } =>
2317                 FalseEdges { real_target, imaginary_targets: imaginary_targets.clone() },
2318             FalseUnwind { real_target, unwind } => FalseUnwind { real_target, unwind },
2319         };
2320         Terminator {
2321             source_info: self.source_info,
2322             kind,
2323         }
2324     }
2325
2326     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
2327         use mir::TerminatorKind::*;
2328
2329         match self.kind {
2330             SwitchInt { ref discr, switch_ty, .. } =>
2331                 discr.visit_with(visitor) || switch_ty.visit_with(visitor),
2332             Drop { ref location, ..} => location.visit_with(visitor),
2333             DropAndReplace { ref location, ref value, ..} =>
2334                 location.visit_with(visitor) || value.visit_with(visitor),
2335             Yield { ref value, ..} =>
2336                 value.visit_with(visitor),
2337             Call { ref func, ref args, ref destination, .. } => {
2338                 let dest = if let Some((ref loc, _)) = *destination {
2339                     loc.visit_with(visitor)
2340                 } else { false };
2341                 dest || func.visit_with(visitor) || args.visit_with(visitor)
2342             },
2343             Assert { ref cond, ref msg, .. } => {
2344                 if cond.visit_with(visitor) {
2345                     if let AssertMessage::BoundsCheck { ref len, ref index } = *msg {
2346                         len.visit_with(visitor) || index.visit_with(visitor)
2347                     } else {
2348                         false
2349                     }
2350                 } else {
2351                     false
2352                 }
2353             },
2354             Goto { .. } |
2355             Resume |
2356             Abort |
2357             Return |
2358             GeneratorDrop |
2359             Unreachable |
2360             FalseEdges { .. } |
2361             FalseUnwind { .. } => false
2362         }
2363     }
2364 }
2365
2366 impl<'tcx> TypeFoldable<'tcx> for Place<'tcx> {
2367     fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
2368         match self {
2369             &Place::Projection(ref p) => Place::Projection(p.fold_with(folder)),
2370             _ => self.clone()
2371         }
2372     }
2373
2374     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
2375         if let &Place::Projection(ref p) = self {
2376             p.visit_with(visitor)
2377         } else {
2378             false
2379         }
2380     }
2381 }
2382
2383 impl<'tcx> TypeFoldable<'tcx> for Rvalue<'tcx> {
2384     fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
2385         use mir::Rvalue::*;
2386         match *self {
2387             Use(ref op) => Use(op.fold_with(folder)),
2388             Repeat(ref op, len) => Repeat(op.fold_with(folder), len),
2389             Ref(region, bk, ref place) =>
2390                 Ref(region.fold_with(folder), bk, place.fold_with(folder)),
2391             Len(ref place) => Len(place.fold_with(folder)),
2392             Cast(kind, ref op, ty) => Cast(kind, op.fold_with(folder), ty.fold_with(folder)),
2393             BinaryOp(op, ref rhs, ref lhs) =>
2394                 BinaryOp(op, rhs.fold_with(folder), lhs.fold_with(folder)),
2395             CheckedBinaryOp(op, ref rhs, ref lhs) =>
2396                 CheckedBinaryOp(op, rhs.fold_with(folder), lhs.fold_with(folder)),
2397             UnaryOp(op, ref val) => UnaryOp(op, val.fold_with(folder)),
2398             Discriminant(ref place) => Discriminant(place.fold_with(folder)),
2399             NullaryOp(op, ty) => NullaryOp(op, ty.fold_with(folder)),
2400             Aggregate(ref kind, ref fields) => {
2401                 let kind = box match **kind {
2402                     AggregateKind::Array(ty) => AggregateKind::Array(ty.fold_with(folder)),
2403                     AggregateKind::Tuple => AggregateKind::Tuple,
2404                     AggregateKind::Adt(def, v, substs, n) =>
2405                         AggregateKind::Adt(def, v, substs.fold_with(folder), n),
2406                     AggregateKind::Closure(id, substs) =>
2407                         AggregateKind::Closure(id, substs.fold_with(folder)),
2408                     AggregateKind::Generator(id, substs, interior) =>
2409                         AggregateKind::Generator(id,
2410                                                  substs.fold_with(folder),
2411                                                  interior.fold_with(folder)),
2412                 };
2413                 Aggregate(kind, fields.fold_with(folder))
2414             }
2415         }
2416     }
2417
2418     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
2419         use mir::Rvalue::*;
2420         match *self {
2421             Use(ref op) => op.visit_with(visitor),
2422             Repeat(ref op, _) => op.visit_with(visitor),
2423             Ref(region, _, ref place) => region.visit_with(visitor) || place.visit_with(visitor),
2424             Len(ref place) => place.visit_with(visitor),
2425             Cast(_, ref op, ty) => op.visit_with(visitor) || ty.visit_with(visitor),
2426             BinaryOp(_, ref rhs, ref lhs) |
2427             CheckedBinaryOp(_, ref rhs, ref lhs) =>
2428                 rhs.visit_with(visitor) || lhs.visit_with(visitor),
2429             UnaryOp(_, ref val) => val.visit_with(visitor),
2430             Discriminant(ref place) => place.visit_with(visitor),
2431             NullaryOp(_, ty) => ty.visit_with(visitor),
2432             Aggregate(ref kind, ref fields) => {
2433                 (match **kind {
2434                     AggregateKind::Array(ty) => ty.visit_with(visitor),
2435                     AggregateKind::Tuple => false,
2436                     AggregateKind::Adt(_, _, substs, _) => substs.visit_with(visitor),
2437                     AggregateKind::Closure(_, substs) => substs.visit_with(visitor),
2438                     AggregateKind::Generator(_, substs, interior) => substs.visit_with(visitor) ||
2439                         interior.visit_with(visitor),
2440                 }) || fields.visit_with(visitor)
2441             }
2442         }
2443     }
2444 }
2445
2446 impl<'tcx> TypeFoldable<'tcx> for Operand<'tcx> {
2447     fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
2448         match *self {
2449             Operand::Copy(ref place) => Operand::Copy(place.fold_with(folder)),
2450             Operand::Move(ref place) => Operand::Move(place.fold_with(folder)),
2451             Operand::Constant(ref c) => Operand::Constant(c.fold_with(folder)),
2452         }
2453     }
2454
2455     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
2456         match *self {
2457             Operand::Copy(ref place) |
2458             Operand::Move(ref place) => place.visit_with(visitor),
2459             Operand::Constant(ref c) => c.visit_with(visitor)
2460         }
2461     }
2462 }
2463
2464 impl<'tcx, B, V, T> TypeFoldable<'tcx> for Projection<'tcx, B, V, T>
2465     where B: TypeFoldable<'tcx>, V: TypeFoldable<'tcx>, T: TypeFoldable<'tcx>
2466 {
2467     fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
2468         use mir::ProjectionElem::*;
2469
2470         let base = self.base.fold_with(folder);
2471         let elem = match self.elem {
2472             Deref => Deref,
2473             Field(f, ref ty) => Field(f, ty.fold_with(folder)),
2474             Index(ref v) => Index(v.fold_with(folder)),
2475             ref elem => elem.clone()
2476         };
2477
2478         Projection {
2479             base,
2480             elem,
2481         }
2482     }
2483
2484     fn super_visit_with<Vs: TypeVisitor<'tcx>>(&self, visitor: &mut Vs) -> bool {
2485         use mir::ProjectionElem::*;
2486
2487         self.base.visit_with(visitor) ||
2488             match self.elem {
2489                 Field(_, ref ty) => ty.visit_with(visitor),
2490                 Index(ref v) => v.visit_with(visitor),
2491                 _ => false
2492             }
2493     }
2494 }
2495
2496 impl<'tcx> TypeFoldable<'tcx> for Field {
2497     fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, _: &mut F) -> Self {
2498         *self
2499     }
2500     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, _: &mut V) -> bool {
2501         false
2502     }
2503 }
2504
2505 impl<'tcx> TypeFoldable<'tcx> for Constant<'tcx> {
2506     fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
2507         Constant {
2508             span: self.span.clone(),
2509             ty: self.ty.fold_with(folder),
2510             literal: self.literal.fold_with(folder)
2511         }
2512     }
2513     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
2514         self.ty.visit_with(visitor) || self.literal.visit_with(visitor)
2515     }
2516 }
2517
2518 impl<'tcx> TypeFoldable<'tcx> for Literal<'tcx> {
2519     fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
2520         match *self {
2521             Literal::Value { value } => Literal::Value {
2522                 value: value.fold_with(folder)
2523             },
2524             Literal::Promoted { index } => Literal::Promoted { index }
2525         }
2526     }
2527     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
2528         match *self {
2529             Literal::Value { value } => value.visit_with(visitor),
2530             Literal::Promoted { .. } => false
2531         }
2532     }
2533 }