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