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