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