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