]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_middle/src/mir/mod.rs
Clarify how branching works in a CFG
[rust.git] / compiler / rustc_middle / src / mir / mod.rs
1 //! MIR datatypes and passes. See the [rustc dev guide] for more info.
2 //!
3 //! [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/mir/index.html
4
5 use crate::mir::coverage::{CodeRegion, CoverageKind};
6 use crate::mir::interpret::{Allocation, ConstValue, GlobalAlloc, Scalar};
7 use crate::mir::visit::MirVisitable;
8 use crate::ty::adjustment::PointerCast;
9 use crate::ty::codec::{TyDecoder, TyEncoder};
10 use crate::ty::fold::{TypeFoldable, TypeFolder, TypeVisitor};
11 use crate::ty::print::{FmtPrinter, Printer};
12 use crate::ty::subst::{Subst, SubstsRef};
13 use crate::ty::{
14     self, AdtDef, CanonicalUserTypeAnnotations, List, Region, Ty, TyCtxt, UserTypeAnnotationIndex,
15 };
16 use rustc_hir as hir;
17 use rustc_hir::def::{CtorKind, Namespace};
18 use rustc_hir::def_id::DefId;
19 use rustc_hir::{self, GeneratorKind};
20 use rustc_target::abi::VariantIdx;
21
22 use polonius_engine::Atom;
23 pub use rustc_ast::Mutability;
24 use rustc_data_structures::fx::FxHashSet;
25 use rustc_data_structures::graph::dominators::{dominators, Dominators};
26 use rustc_data_structures::graph::{self, GraphSuccessors};
27 use rustc_index::bit_set::BitMatrix;
28 use rustc_index::vec::{Idx, IndexVec};
29 use rustc_serialize::{Decodable, Encodable};
30 use rustc_span::symbol::Symbol;
31 use rustc_span::{Span, DUMMY_SP};
32 use rustc_target::abi;
33 use rustc_target::asm::InlineAsmRegOrRegClass;
34 use std::borrow::Cow;
35 use std::fmt::{self, Debug, Display, Formatter, Write};
36 use std::ops::{Index, IndexMut};
37 use std::slice;
38 use std::{iter, mem, option};
39
40 use self::predecessors::{PredecessorCache, Predecessors};
41 pub use self::query::*;
42
43 pub mod coverage;
44 pub mod interpret;
45 pub mod mono;
46 mod predecessors;
47 mod query;
48 pub mod tcx;
49 pub mod terminator;
50 pub use terminator::*;
51 pub mod traversal;
52 mod type_foldable;
53 pub mod visit;
54
55 /// Types for locals
56 type LocalDecls<'tcx> = IndexVec<Local, LocalDecl<'tcx>>;
57
58 pub trait HasLocalDecls<'tcx> {
59     fn local_decls(&self) -> &LocalDecls<'tcx>;
60 }
61
62 impl<'tcx> HasLocalDecls<'tcx> for LocalDecls<'tcx> {
63     fn local_decls(&self) -> &LocalDecls<'tcx> {
64         self
65     }
66 }
67
68 impl<'tcx> HasLocalDecls<'tcx> for Body<'tcx> {
69     fn local_decls(&self) -> &LocalDecls<'tcx> {
70         &self.local_decls
71     }
72 }
73
74 /// The various "big phases" that MIR goes through.
75 ///
76 /// These phases all describe dialects of MIR. Since all MIR uses the same datastructures, the
77 /// dialects forbid certain variants or values in certain phases.
78 ///
79 /// Note: Each phase's validation checks all invariants of the *previous* phases' dialects. A phase
80 /// that changes the dialect documents what invariants must be upheld *after* that phase finishes.
81 ///
82 /// Warning: ordering of variants is significant.
83 #[derive(Copy, Clone, TyEncodable, TyDecodable, Debug, PartialEq, Eq, PartialOrd, Ord)]
84 #[derive(HashStable)]
85 pub enum MirPhase {
86     Build = 0,
87     // FIXME(oli-obk): it's unclear whether we still need this phase (and its corresponding query).
88     // We used to have this for pre-miri MIR based const eval.
89     Const = 1,
90     /// This phase checks the MIR for promotable elements and takes them out of the main MIR body
91     /// by creating a new MIR body per promoted element. After this phase (and thus the termination
92     /// of the `mir_promoted` query), these promoted elements are available in the `promoted_mir`
93     /// query.
94     ConstPromotion = 2,
95     /// After this phase
96     /// * the only `AggregateKind`s allowed are `Array` and `Generator`,
97     /// * `DropAndReplace` is gone for good
98     /// * `Drop` now uses explicit drop flags visible in the MIR and reaching a `Drop` terminator
99     ///   means that the auto-generated drop glue will be invoked.
100     DropLowering = 3,
101     /// After this phase, generators are explicit state machines (no more `Yield`).
102     /// `AggregateKind::Generator` is gone for good.
103     GeneratorLowering = 4,
104     Optimization = 5,
105 }
106
107 impl MirPhase {
108     /// Gets the index of the current MirPhase within the set of all `MirPhase`s.
109     pub fn phase_index(&self) -> usize {
110         *self as usize
111     }
112 }
113
114 /// The lowered representation of a single function.
115 #[derive(Clone, TyEncodable, TyDecodable, Debug, HashStable, TypeFoldable)]
116 pub struct Body<'tcx> {
117     /// A list of basic blocks. References to basic block use a newtyped index type `BasicBlock`
118     /// that indexes into this vector.
119     basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
120
121     /// Records how far through the "desugaring and optimization" process this particular
122     /// MIR has traversed. This is particularly useful when inlining, since in that context
123     /// we instantiate the promoted constants and add them to our promoted vector -- but those
124     /// promoted items have already been optimized, whereas ours have not. This field allows
125     /// us to see the difference and forego optimization on the inlined promoted items.
126     pub phase: MirPhase,
127
128     /// A list of source scopes; these are referenced by statements
129     /// and used for debuginfo. Indexed by a `SourceScope`.
130     pub source_scopes: IndexVec<SourceScope, SourceScopeData>,
131
132     /// The yield type of the function, if it is a generator.
133     pub yield_ty: Option<Ty<'tcx>>,
134
135     /// Generator drop glue.
136     pub generator_drop: Option<Box<Body<'tcx>>>,
137
138     /// The layout of a generator. Produced by the state transformation.
139     pub generator_layout: Option<GeneratorLayout<'tcx>>,
140
141     /// If this is a generator then record the type of source expression that caused this generator
142     /// to be created.
143     pub generator_kind: Option<GeneratorKind>,
144
145     /// Declarations of locals.
146     ///
147     /// The first local is the return value pointer, followed by `arg_count`
148     /// locals for the function arguments, followed by any user-declared
149     /// variables and temporaries.
150     pub local_decls: LocalDecls<'tcx>,
151
152     /// User type annotations.
153     pub user_type_annotations: CanonicalUserTypeAnnotations<'tcx>,
154
155     /// The number of arguments this function takes.
156     ///
157     /// Starting at local 1, `arg_count` locals will be provided by the caller
158     /// and can be assumed to be initialized.
159     ///
160     /// If this MIR was built for a constant, this will be 0.
161     pub arg_count: usize,
162
163     /// Mark an argument local (which must be a tuple) as getting passed as
164     /// its individual components at the LLVM level.
165     ///
166     /// This is used for the "rust-call" ABI.
167     pub spread_arg: Option<Local>,
168
169     /// Debug information pertaining to user variables, including captures.
170     pub var_debug_info: Vec<VarDebugInfo<'tcx>>,
171
172     /// A span representing this MIR, for error reporting.
173     pub span: Span,
174
175     /// Constants that are required to evaluate successfully for this MIR to be well-formed.
176     /// We hold in this field all the constants we are not able to evaluate yet.
177     pub required_consts: Vec<Constant<'tcx>>,
178
179     /// The user may be writing e.g. `&[(SOME_CELL, 42)][i].1` and this would get promoted, because
180     /// we'd statically know that no thing with interior mutability will ever be available to the
181     /// user without some serious unsafe code.  Now this means that our promoted is actually
182     /// `&[(SOME_CELL, 42)]` and the MIR using it will do the `&promoted[i].1` projection because
183     /// the index may be a runtime value. Such a promoted value is illegal because it has reachable
184     /// interior mutability. This flag just makes this situation very obvious where the previous
185     /// implementation without the flag hid this situation silently.
186     /// FIXME(oli-obk): rewrite the promoted during promotion to eliminate the cell components.
187     pub ignore_interior_mut_in_const_validation: bool,
188
189     /// Does this body use generic parameters. This is used for the `ConstEvaluatable` check.
190     ///
191     /// Note that this does not actually mean that this body is not computable right now.
192     /// The repeat count in the following example is polymorphic, but can still be evaluated
193     /// without knowing anything about the type parameter `T`.
194     ///
195     /// ```rust
196     /// fn test<T>() {
197     ///     let _ = [0; std::mem::size_of::<*mut T>()];
198     /// }
199     /// ```
200     ///
201     /// **WARNING**: Do not change this flags after the MIR was originally created, even if an optimization
202     /// removed the last mention of all generic params. We do not want to rely on optimizations and
203     /// potentially allow things like `[u8; std::mem::size_of::<T>() * 0]` due to this.
204     pub is_polymorphic: bool,
205
206     predecessor_cache: PredecessorCache,
207 }
208
209 impl<'tcx> Body<'tcx> {
210     pub fn new(
211         basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
212         source_scopes: IndexVec<SourceScope, SourceScopeData>,
213         local_decls: LocalDecls<'tcx>,
214         user_type_annotations: CanonicalUserTypeAnnotations<'tcx>,
215         arg_count: usize,
216         var_debug_info: Vec<VarDebugInfo<'tcx>>,
217         span: Span,
218         generator_kind: Option<GeneratorKind>,
219     ) -> Self {
220         // We need `arg_count` locals, and one for the return place.
221         assert!(
222             local_decls.len() > arg_count,
223             "expected at least {} locals, got {}",
224             arg_count + 1,
225             local_decls.len()
226         );
227
228         let mut body = Body {
229             phase: MirPhase::Build,
230             basic_blocks,
231             source_scopes,
232             yield_ty: None,
233             generator_drop: None,
234             generator_layout: None,
235             generator_kind,
236             local_decls,
237             user_type_annotations,
238             arg_count,
239             spread_arg: None,
240             var_debug_info,
241             span,
242             required_consts: Vec::new(),
243             ignore_interior_mut_in_const_validation: false,
244             is_polymorphic: false,
245             predecessor_cache: PredecessorCache::new(),
246         };
247         body.is_polymorphic = body.has_param_types_or_consts();
248         body
249     }
250
251     /// Returns a partially initialized MIR body containing only a list of basic blocks.
252     ///
253     /// The returned MIR contains no `LocalDecl`s (even for the return place) or source scopes. It
254     /// is only useful for testing but cannot be `#[cfg(test)]` because it is used in a different
255     /// crate.
256     pub fn new_cfg_only(basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>) -> Self {
257         let mut body = Body {
258             phase: MirPhase::Build,
259             basic_blocks,
260             source_scopes: IndexVec::new(),
261             yield_ty: None,
262             generator_drop: None,
263             generator_layout: None,
264             local_decls: IndexVec::new(),
265             user_type_annotations: IndexVec::new(),
266             arg_count: 0,
267             spread_arg: None,
268             span: DUMMY_SP,
269             required_consts: Vec::new(),
270             generator_kind: None,
271             var_debug_info: Vec::new(),
272             ignore_interior_mut_in_const_validation: false,
273             is_polymorphic: false,
274             predecessor_cache: PredecessorCache::new(),
275         };
276         body.is_polymorphic = body.has_param_types_or_consts();
277         body
278     }
279
280     #[inline]
281     pub fn basic_blocks(&self) -> &IndexVec<BasicBlock, BasicBlockData<'tcx>> {
282         &self.basic_blocks
283     }
284
285     #[inline]
286     pub fn basic_blocks_mut(&mut self) -> &mut IndexVec<BasicBlock, BasicBlockData<'tcx>> {
287         // Because the user could mutate basic block terminators via this reference, we need to
288         // invalidate the predecessor cache.
289         //
290         // FIXME: Use a finer-grained API for this, so only transformations that alter terminators
291         // invalidate the predecessor cache.
292         self.predecessor_cache.invalidate();
293         &mut self.basic_blocks
294     }
295
296     #[inline]
297     pub fn basic_blocks_and_local_decls_mut(
298         &mut self,
299     ) -> (&mut IndexVec<BasicBlock, BasicBlockData<'tcx>>, &mut LocalDecls<'tcx>) {
300         self.predecessor_cache.invalidate();
301         (&mut self.basic_blocks, &mut self.local_decls)
302     }
303
304     #[inline]
305     pub fn basic_blocks_local_decls_mut_and_var_debug_info(
306         &mut self,
307     ) -> (
308         &mut IndexVec<BasicBlock, BasicBlockData<'tcx>>,
309         &mut LocalDecls<'tcx>,
310         &mut Vec<VarDebugInfo<'tcx>>,
311     ) {
312         self.predecessor_cache.invalidate();
313         (&mut self.basic_blocks, &mut self.local_decls, &mut self.var_debug_info)
314     }
315
316     /// Returns `true` if a cycle exists in the control-flow graph that is reachable from the
317     /// `START_BLOCK`.
318     pub fn is_cfg_cyclic(&self) -> bool {
319         graph::is_cyclic(self)
320     }
321
322     #[inline]
323     pub fn local_kind(&self, local: Local) -> LocalKind {
324         let index = local.as_usize();
325         if index == 0 {
326             debug_assert!(
327                 self.local_decls[local].mutability == Mutability::Mut,
328                 "return place should be mutable"
329             );
330
331             LocalKind::ReturnPointer
332         } else if index < self.arg_count + 1 {
333             LocalKind::Arg
334         } else if self.local_decls[local].is_user_variable() {
335             LocalKind::Var
336         } else {
337             LocalKind::Temp
338         }
339     }
340
341     /// Returns an iterator over all temporaries.
342     #[inline]
343     pub fn temps_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
344         (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
345             let local = Local::new(index);
346             if self.local_decls[local].is_user_variable() { None } else { Some(local) }
347         })
348     }
349
350     /// Returns an iterator over all user-declared locals.
351     #[inline]
352     pub fn vars_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
353         (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
354             let local = Local::new(index);
355             self.local_decls[local].is_user_variable().then_some(local)
356         })
357     }
358
359     /// Returns an iterator over all user-declared mutable locals.
360     #[inline]
361     pub fn mut_vars_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
362         (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
363             let local = Local::new(index);
364             let decl = &self.local_decls[local];
365             if decl.is_user_variable() && decl.mutability == Mutability::Mut {
366                 Some(local)
367             } else {
368                 None
369             }
370         })
371     }
372
373     /// Returns an iterator over all user-declared mutable arguments and locals.
374     #[inline]
375     pub fn mut_vars_and_args_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
376         (1..self.local_decls.len()).filter_map(move |index| {
377             let local = Local::new(index);
378             let decl = &self.local_decls[local];
379             if (decl.is_user_variable() || index < self.arg_count + 1)
380                 && decl.mutability == Mutability::Mut
381             {
382                 Some(local)
383             } else {
384                 None
385             }
386         })
387     }
388
389     /// Returns an iterator over all function arguments.
390     #[inline]
391     pub fn args_iter(&self) -> impl Iterator<Item = Local> + ExactSizeIterator {
392         let arg_count = self.arg_count;
393         (1..arg_count + 1).map(Local::new)
394     }
395
396     /// Returns an iterator over all user-defined variables and compiler-generated temporaries (all
397     /// locals that are neither arguments nor the return place).
398     #[inline]
399     pub fn vars_and_temps_iter(&self) -> impl Iterator<Item = Local> + ExactSizeIterator {
400         let arg_count = self.arg_count;
401         let local_count = self.local_decls.len();
402         (arg_count + 1..local_count).map(Local::new)
403     }
404
405     /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
406     /// invalidating statement indices in `Location`s.
407     pub fn make_statement_nop(&mut self, location: Location) {
408         let block = &mut self.basic_blocks[location.block];
409         debug_assert!(location.statement_index < block.statements.len());
410         block.statements[location.statement_index].make_nop()
411     }
412
413     /// Returns the source info associated with `location`.
414     pub fn source_info(&self, location: Location) -> &SourceInfo {
415         let block = &self[location.block];
416         let stmts = &block.statements;
417         let idx = location.statement_index;
418         if idx < stmts.len() {
419             &stmts[idx].source_info
420         } else {
421             assert_eq!(idx, stmts.len());
422             &block.terminator().source_info
423         }
424     }
425
426     /// Checks if `sub` is a sub scope of `sup`
427     pub fn is_sub_scope(&self, mut sub: SourceScope, sup: SourceScope) -> bool {
428         while sub != sup {
429             match self.source_scopes[sub].parent_scope {
430                 None => return false,
431                 Some(p) => sub = p,
432             }
433         }
434         true
435     }
436
437     /// Returns the return type; it always return first element from `local_decls` array.
438     #[inline]
439     pub fn return_ty(&self) -> Ty<'tcx> {
440         self.local_decls[RETURN_PLACE].ty
441     }
442
443     /// Gets the location of the terminator for the given block.
444     #[inline]
445     pub fn terminator_loc(&self, bb: BasicBlock) -> Location {
446         Location { block: bb, statement_index: self[bb].statements.len() }
447     }
448
449     #[inline]
450     pub fn predecessors(&self) -> impl std::ops::Deref<Target = Predecessors> + '_ {
451         self.predecessor_cache.compute(&self.basic_blocks)
452     }
453
454     #[inline]
455     pub fn dominators(&self) -> Dominators<BasicBlock> {
456         dominators(self)
457     }
458 }
459
460 #[derive(Copy, Clone, PartialEq, Eq, Debug, TyEncodable, TyDecodable, HashStable)]
461 pub enum Safety {
462     Safe,
463     /// Unsafe because of a PushUnsafeBlock
464     BuiltinUnsafe,
465     /// Unsafe because of an unsafe fn
466     FnUnsafe,
467     /// Unsafe because of an `unsafe` block
468     ExplicitUnsafe(hir::HirId),
469 }
470
471 impl<'tcx> Index<BasicBlock> for Body<'tcx> {
472     type Output = BasicBlockData<'tcx>;
473
474     #[inline]
475     fn index(&self, index: BasicBlock) -> &BasicBlockData<'tcx> {
476         &self.basic_blocks()[index]
477     }
478 }
479
480 impl<'tcx> IndexMut<BasicBlock> for Body<'tcx> {
481     #[inline]
482     fn index_mut(&mut self, index: BasicBlock) -> &mut BasicBlockData<'tcx> {
483         &mut self.basic_blocks_mut()[index]
484     }
485 }
486
487 #[derive(Copy, Clone, Debug, HashStable, TypeFoldable)]
488 pub enum ClearCrossCrate<T> {
489     Clear,
490     Set(T),
491 }
492
493 impl<T> ClearCrossCrate<T> {
494     pub fn as_ref(&self) -> ClearCrossCrate<&T> {
495         match self {
496             ClearCrossCrate::Clear => ClearCrossCrate::Clear,
497             ClearCrossCrate::Set(v) => ClearCrossCrate::Set(v),
498         }
499     }
500
501     pub fn assert_crate_local(self) -> T {
502         match self {
503             ClearCrossCrate::Clear => bug!("unwrapping cross-crate data"),
504             ClearCrossCrate::Set(v) => v,
505         }
506     }
507 }
508
509 const TAG_CLEAR_CROSS_CRATE_CLEAR: u8 = 0;
510 const TAG_CLEAR_CROSS_CRATE_SET: u8 = 1;
511
512 impl<'tcx, E: TyEncoder<'tcx>, T: Encodable<E>> Encodable<E> for ClearCrossCrate<T> {
513     #[inline]
514     fn encode(&self, e: &mut E) -> Result<(), E::Error> {
515         if E::CLEAR_CROSS_CRATE {
516             return Ok(());
517         }
518
519         match *self {
520             ClearCrossCrate::Clear => TAG_CLEAR_CROSS_CRATE_CLEAR.encode(e),
521             ClearCrossCrate::Set(ref val) => {
522                 TAG_CLEAR_CROSS_CRATE_SET.encode(e)?;
523                 val.encode(e)
524             }
525         }
526     }
527 }
528 impl<'tcx, D: TyDecoder<'tcx>, T: Decodable<D>> Decodable<D> for ClearCrossCrate<T> {
529     #[inline]
530     fn decode(d: &mut D) -> Result<ClearCrossCrate<T>, D::Error> {
531         if D::CLEAR_CROSS_CRATE {
532             return Ok(ClearCrossCrate::Clear);
533         }
534
535         let discr = u8::decode(d)?;
536
537         match discr {
538             TAG_CLEAR_CROSS_CRATE_CLEAR => Ok(ClearCrossCrate::Clear),
539             TAG_CLEAR_CROSS_CRATE_SET => {
540                 let val = T::decode(d)?;
541                 Ok(ClearCrossCrate::Set(val))
542             }
543             tag => Err(d.error(&format!("Invalid tag for ClearCrossCrate: {:?}", tag))),
544         }
545     }
546 }
547
548 /// Grouped information about the source code origin of a MIR entity.
549 /// Intended to be inspected by diagnostics and debuginfo.
550 /// Most passes can work with it as a whole, within a single function.
551 // The unofficial Cranelift backend, at least as of #65828, needs `SourceInfo` to implement `Eq` and
552 // `Hash`. Please ping @bjorn3 if removing them.
553 #[derive(Copy, Clone, Debug, Eq, PartialEq, TyEncodable, TyDecodable, Hash, HashStable)]
554 pub struct SourceInfo {
555     /// The source span for the AST pertaining to this MIR entity.
556     pub span: Span,
557
558     /// The source scope, keeping track of which bindings can be
559     /// seen by debuginfo, active lint levels, `unsafe {...}`, etc.
560     pub scope: SourceScope,
561 }
562
563 impl SourceInfo {
564     #[inline]
565     pub fn outermost(span: Span) -> Self {
566         SourceInfo { span, scope: OUTERMOST_SOURCE_SCOPE }
567     }
568 }
569
570 ///////////////////////////////////////////////////////////////////////////
571 // Borrow kinds
572
573 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, TyEncodable, TyDecodable)]
574 #[derive(HashStable)]
575 pub enum BorrowKind {
576     /// Data must be immutable and is aliasable.
577     Shared,
578
579     /// The immediately borrowed place must be immutable, but projections from
580     /// it don't need to be. For example, a shallow borrow of `a.b` doesn't
581     /// conflict with a mutable borrow of `a.b.c`.
582     ///
583     /// This is used when lowering matches: when matching on a place we want to
584     /// ensure that place have the same value from the start of the match until
585     /// an arm is selected. This prevents this code from compiling:
586     ///
587     ///     let mut x = &Some(0);
588     ///     match *x {
589     ///         None => (),
590     ///         Some(_) if { x = &None; false } => (),
591     ///         Some(_) => (),
592     ///     }
593     ///
594     /// This can't be a shared borrow because mutably borrowing (*x as Some).0
595     /// should not prevent `if let None = x { ... }`, for example, because the
596     /// mutating `(*x as Some).0` can't affect the discriminant of `x`.
597     /// We can also report errors with this kind of borrow differently.
598     Shallow,
599
600     /// Data must be immutable but not aliasable. This kind of borrow
601     /// cannot currently be expressed by the user and is used only in
602     /// implicit closure bindings. It is needed when the closure is
603     /// borrowing or mutating a mutable referent, e.g.:
604     ///
605     ///     let x: &mut isize = ...;
606     ///     let y = || *x += 5;
607     ///
608     /// If we were to try to translate this closure into a more explicit
609     /// form, we'd encounter an error with the code as written:
610     ///
611     ///     struct Env { x: & &mut isize }
612     ///     let x: &mut isize = ...;
613     ///     let y = (&mut Env { &x }, fn_ptr);  // Closure is pair of env and fn
614     ///     fn fn_ptr(env: &mut Env) { **env.x += 5; }
615     ///
616     /// This is then illegal because you cannot mutate an `&mut` found
617     /// in an aliasable location. To solve, you'd have to translate with
618     /// an `&mut` borrow:
619     ///
620     ///     struct Env { x: & &mut isize }
621     ///     let x: &mut isize = ...;
622     ///     let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
623     ///     fn fn_ptr(env: &mut Env) { **env.x += 5; }
624     ///
625     /// Now the assignment to `**env.x` is legal, but creating a
626     /// mutable pointer to `x` is not because `x` is not mutable. We
627     /// could fix this by declaring `x` as `let mut x`. This is ok in
628     /// user code, if awkward, but extra weird for closures, since the
629     /// borrow is hidden.
630     ///
631     /// So we introduce a "unique imm" borrow -- the referent is
632     /// immutable, but not aliasable. This solves the problem. For
633     /// simplicity, we don't give users the way to express this
634     /// borrow, it's just used when translating closures.
635     Unique,
636
637     /// Data is mutable and not aliasable.
638     Mut {
639         /// `true` if this borrow arose from method-call auto-ref
640         /// (i.e., `adjustment::Adjust::Borrow`).
641         allow_two_phase_borrow: bool,
642     },
643 }
644
645 impl BorrowKind {
646     pub fn allows_two_phase_borrow(&self) -> bool {
647         match *self {
648             BorrowKind::Shared | BorrowKind::Shallow | BorrowKind::Unique => false,
649             BorrowKind::Mut { allow_two_phase_borrow } => allow_two_phase_borrow,
650         }
651     }
652 }
653
654 ///////////////////////////////////////////////////////////////////////////
655 // Variables and temps
656
657 rustc_index::newtype_index! {
658     pub struct Local {
659         derive [HashStable]
660         DEBUG_FORMAT = "_{}",
661         const RETURN_PLACE = 0,
662     }
663 }
664
665 impl Atom for Local {
666     fn index(self) -> usize {
667         Idx::index(self)
668     }
669 }
670
671 /// Classifies locals into categories. See `Body::local_kind`.
672 #[derive(PartialEq, Eq, Debug, HashStable)]
673 pub enum LocalKind {
674     /// User-declared variable binding.
675     Var,
676     /// Compiler-introduced temporary.
677     Temp,
678     /// Function argument.
679     Arg,
680     /// Location of function's return value.
681     ReturnPointer,
682 }
683
684 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable)]
685 pub struct VarBindingForm<'tcx> {
686     /// Is variable bound via `x`, `mut x`, `ref x`, or `ref mut x`?
687     pub binding_mode: ty::BindingMode,
688     /// If an explicit type was provided for this variable binding,
689     /// this holds the source Span of that type.
690     ///
691     /// NOTE: if you want to change this to a `HirId`, be wary that
692     /// doing so breaks incremental compilation (as of this writing),
693     /// while a `Span` does not cause our tests to fail.
694     pub opt_ty_info: Option<Span>,
695     /// Place of the RHS of the =, or the subject of the `match` where this
696     /// variable is initialized. None in the case of `let PATTERN;`.
697     /// Some((None, ..)) in the case of and `let [mut] x = ...` because
698     /// (a) the right-hand side isn't evaluated as a place expression.
699     /// (b) it gives a way to separate this case from the remaining cases
700     ///     for diagnostics.
701     pub opt_match_place: Option<(Option<Place<'tcx>>, Span)>,
702     /// The span of the pattern in which this variable was bound.
703     pub pat_span: Span,
704 }
705
706 #[derive(Clone, Debug, TyEncodable, TyDecodable)]
707 pub enum BindingForm<'tcx> {
708     /// This is a binding for a non-`self` binding, or a `self` that has an explicit type.
709     Var(VarBindingForm<'tcx>),
710     /// Binding for a `self`/`&self`/`&mut self` binding where the type is implicit.
711     ImplicitSelf(ImplicitSelfKind),
712     /// Reference used in a guard expression to ensure immutability.
713     RefForGuard,
714 }
715
716 /// Represents what type of implicit self a function has, if any.
717 #[derive(Clone, Copy, PartialEq, Debug, TyEncodable, TyDecodable, HashStable)]
718 pub enum ImplicitSelfKind {
719     /// Represents a `fn x(self);`.
720     Imm,
721     /// Represents a `fn x(mut self);`.
722     Mut,
723     /// Represents a `fn x(&self);`.
724     ImmRef,
725     /// Represents a `fn x(&mut self);`.
726     MutRef,
727     /// Represents when a function does not have a self argument or
728     /// when a function has a `self: X` argument.
729     None,
730 }
731
732 CloneTypeFoldableAndLiftImpls! { BindingForm<'tcx>, }
733
734 mod binding_form_impl {
735     use crate::ich::StableHashingContext;
736     use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
737
738     impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for super::BindingForm<'tcx> {
739         fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
740             use super::BindingForm::*;
741             ::std::mem::discriminant(self).hash_stable(hcx, hasher);
742
743             match self {
744                 Var(binding) => binding.hash_stable(hcx, hasher),
745                 ImplicitSelf(kind) => kind.hash_stable(hcx, hasher),
746                 RefForGuard => (),
747             }
748         }
749     }
750 }
751
752 /// `BlockTailInfo` is attached to the `LocalDecl` for temporaries
753 /// created during evaluation of expressions in a block tail
754 /// expression; that is, a block like `{ STMT_1; STMT_2; EXPR }`.
755 ///
756 /// It is used to improve diagnostics when such temporaries are
757 /// involved in borrow_check errors, e.g., explanations of where the
758 /// temporaries come from, when their destructors are run, and/or how
759 /// one might revise the code to satisfy the borrow checker's rules.
760 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable)]
761 pub struct BlockTailInfo {
762     /// If `true`, then the value resulting from evaluating this tail
763     /// expression is ignored by the block's expression context.
764     ///
765     /// Examples include `{ ...; tail };` and `let _ = { ...; tail };`
766     /// but not e.g., `let _x = { ...; tail };`
767     pub tail_result_is_ignored: bool,
768
769     /// `Span` of the tail expression.
770     pub span: Span,
771 }
772
773 /// A MIR local.
774 ///
775 /// This can be a binding declared by the user, a temporary inserted by the compiler, a function
776 /// argument, or the return place.
777 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
778 pub struct LocalDecl<'tcx> {
779     /// Whether this is a mutable minding (i.e., `let x` or `let mut x`).
780     ///
781     /// Temporaries and the return place are always mutable.
782     pub mutability: Mutability,
783
784     // FIXME(matthewjasper) Don't store in this in `Body`
785     pub local_info: Option<Box<LocalInfo<'tcx>>>,
786
787     /// `true` if this is an internal local.
788     ///
789     /// These locals are not based on types in the source code and are only used
790     /// for a few desugarings at the moment.
791     ///
792     /// The generator transformation will sanity check the locals which are live
793     /// across a suspension point against the type components of the generator
794     /// which type checking knows are live across a suspension point. We need to
795     /// flag drop flags to avoid triggering this check as they are introduced
796     /// after typeck.
797     ///
798     /// Unsafety checking will also ignore dereferences of these locals,
799     /// so they can be used for raw pointers only used in a desugaring.
800     ///
801     /// This should be sound because the drop flags are fully algebraic, and
802     /// therefore don't affect the OIBIT or outlives properties of the
803     /// generator.
804     pub internal: bool,
805
806     /// If this local is a temporary and `is_block_tail` is `Some`,
807     /// then it is a temporary created for evaluation of some
808     /// subexpression of some block's tail expression (with no
809     /// intervening statement context).
810     // FIXME(matthewjasper) Don't store in this in `Body`
811     pub is_block_tail: Option<BlockTailInfo>,
812
813     /// The type of this local.
814     pub ty: Ty<'tcx>,
815
816     /// If the user manually ascribed a type to this variable,
817     /// e.g., via `let x: T`, then we carry that type here. The MIR
818     /// borrow checker needs this information since it can affect
819     /// region inference.
820     // FIXME(matthewjasper) Don't store in this in `Body`
821     pub user_ty: Option<Box<UserTypeProjections>>,
822
823     /// The *syntactic* (i.e., not visibility) source scope the local is defined
824     /// in. If the local was defined in a let-statement, this
825     /// is *within* the let-statement, rather than outside
826     /// of it.
827     ///
828     /// This is needed because the visibility source scope of locals within
829     /// a let-statement is weird.
830     ///
831     /// The reason is that we want the local to be *within* the let-statement
832     /// for lint purposes, but we want the local to be *after* the let-statement
833     /// for names-in-scope purposes.
834     ///
835     /// That's it, if we have a let-statement like the one in this
836     /// function:
837     ///
838     /// ```
839     /// fn foo(x: &str) {
840     ///     #[allow(unused_mut)]
841     ///     let mut x: u32 = { // <- one unused mut
842     ///         let mut y: u32 = x.parse().unwrap();
843     ///         y + 2
844     ///     };
845     ///     drop(x);
846     /// }
847     /// ```
848     ///
849     /// Then, from a lint point of view, the declaration of `x: u32`
850     /// (and `y: u32`) are within the `#[allow(unused_mut)]` scope - the
851     /// lint scopes are the same as the AST/HIR nesting.
852     ///
853     /// However, from a name lookup point of view, the scopes look more like
854     /// as if the let-statements were `match` expressions:
855     ///
856     /// ```
857     /// fn foo(x: &str) {
858     ///     match {
859     ///         match x.parse().unwrap() {
860     ///             y => y + 2
861     ///         }
862     ///     } {
863     ///         x => drop(x)
864     ///     };
865     /// }
866     /// ```
867     ///
868     /// We care about the name-lookup scopes for debuginfo - if the
869     /// debuginfo instruction pointer is at the call to `x.parse()`, we
870     /// want `x` to refer to `x: &str`, but if it is at the call to
871     /// `drop(x)`, we want it to refer to `x: u32`.
872     ///
873     /// To allow both uses to work, we need to have more than a single scope
874     /// for a local. We have the `source_info.scope` represent the "syntactic"
875     /// lint scope (with a variable being under its let block) while the
876     /// `var_debug_info.source_info.scope` represents the "local variable"
877     /// scope (where the "rest" of a block is under all prior let-statements).
878     ///
879     /// The end result looks like this:
880     ///
881     /// ```text
882     /// ROOT SCOPE
883     ///  │{ argument x: &str }
884     ///  │
885     ///  │ │{ #[allow(unused_mut)] } // This is actually split into 2 scopes
886     ///  │ │                         // in practice because I'm lazy.
887     ///  │ │
888     ///  │ │← x.source_info.scope
889     ///  │ │← `x.parse().unwrap()`
890     ///  │ │
891     ///  │ │ │← y.source_info.scope
892     ///  │ │
893     ///  │ │ │{ let y: u32 }
894     ///  │ │ │
895     ///  │ │ │← y.var_debug_info.source_info.scope
896     ///  │ │ │← `y + 2`
897     ///  │
898     ///  │ │{ let x: u32 }
899     ///  │ │← x.var_debug_info.source_info.scope
900     ///  │ │← `drop(x)` // This accesses `x: u32`.
901     /// ```
902     pub source_info: SourceInfo,
903 }
904
905 // `LocalDecl` is used a lot. Make sure it doesn't unintentionally get bigger.
906 #[cfg(target_arch = "x86_64")]
907 static_assert_size!(LocalDecl<'_>, 56);
908
909 /// Extra information about a some locals that's used for diagnostics and for
910 /// classifying variables into local variables, statics, etc, which is needed e.g.
911 /// for unsafety checking.
912 ///
913 /// Not used for non-StaticRef temporaries, the return place, or anonymous
914 /// function parameters.
915 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
916 pub enum LocalInfo<'tcx> {
917     /// A user-defined local variable or function parameter
918     ///
919     /// The `BindingForm` is solely used for local diagnostics when generating
920     /// warnings/errors when compiling the current crate, and therefore it need
921     /// not be visible across crates.
922     User(ClearCrossCrate<BindingForm<'tcx>>),
923     /// A temporary created that references the static with the given `DefId`.
924     StaticRef { def_id: DefId, is_thread_local: bool },
925     /// A temporary created that references the const with the given `DefId`
926     ConstRef { def_id: DefId },
927 }
928
929 impl<'tcx> LocalDecl<'tcx> {
930     /// Returns `true` only if local is a binding that can itself be
931     /// made mutable via the addition of the `mut` keyword, namely
932     /// something like the occurrences of `x` in:
933     /// - `fn foo(x: Type) { ... }`,
934     /// - `let x = ...`,
935     /// - or `match ... { C(x) => ... }`
936     pub fn can_be_made_mutable(&self) -> bool {
937         match self.local_info {
938             Some(box LocalInfo::User(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
939                 binding_mode: ty::BindingMode::BindByValue(_),
940                 opt_ty_info: _,
941                 opt_match_place: _,
942                 pat_span: _,
943             })))) => true,
944
945             Some(box LocalInfo::User(ClearCrossCrate::Set(BindingForm::ImplicitSelf(
946                 ImplicitSelfKind::Imm,
947             )))) => true,
948
949             _ => false,
950         }
951     }
952
953     /// Returns `true` if local is definitely not a `ref ident` or
954     /// `ref mut ident` binding. (Such bindings cannot be made into
955     /// mutable bindings, but the inverse does not necessarily hold).
956     pub fn is_nonref_binding(&self) -> bool {
957         match self.local_info {
958             Some(box LocalInfo::User(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
959                 binding_mode: ty::BindingMode::BindByValue(_),
960                 opt_ty_info: _,
961                 opt_match_place: _,
962                 pat_span: _,
963             })))) => true,
964
965             Some(box LocalInfo::User(ClearCrossCrate::Set(BindingForm::ImplicitSelf(_)))) => true,
966
967             _ => false,
968         }
969     }
970
971     /// Returns `true` if this variable is a named variable or function
972     /// parameter declared by the user.
973     #[inline]
974     pub fn is_user_variable(&self) -> bool {
975         match self.local_info {
976             Some(box LocalInfo::User(_)) => true,
977             _ => false,
978         }
979     }
980
981     /// Returns `true` if this is a reference to a variable bound in a `match`
982     /// expression that is used to access said variable for the guard of the
983     /// match arm.
984     pub fn is_ref_for_guard(&self) -> bool {
985         match self.local_info {
986             Some(box LocalInfo::User(ClearCrossCrate::Set(BindingForm::RefForGuard))) => true,
987             _ => false,
988         }
989     }
990
991     /// Returns `Some` if this is a reference to a static item that is used to
992     /// access that static
993     pub fn is_ref_to_static(&self) -> bool {
994         match self.local_info {
995             Some(box LocalInfo::StaticRef { .. }) => true,
996             _ => false,
997         }
998     }
999
1000     /// Returns `Some` if this is a reference to a static item that is used to
1001     /// access that static
1002     pub fn is_ref_to_thread_local(&self) -> bool {
1003         match self.local_info {
1004             Some(box LocalInfo::StaticRef { is_thread_local, .. }) => is_thread_local,
1005             _ => false,
1006         }
1007     }
1008
1009     /// Returns `true` is the local is from a compiler desugaring, e.g.,
1010     /// `__next` from a `for` loop.
1011     #[inline]
1012     pub fn from_compiler_desugaring(&self) -> bool {
1013         self.source_info.span.desugaring_kind().is_some()
1014     }
1015
1016     /// Creates a new `LocalDecl` for a temporary: mutable, non-internal.
1017     #[inline]
1018     pub fn new(ty: Ty<'tcx>, span: Span) -> Self {
1019         Self::with_source_info(ty, SourceInfo::outermost(span))
1020     }
1021
1022     /// Like `LocalDecl::new`, but takes a `SourceInfo` instead of a `Span`.
1023     #[inline]
1024     pub fn with_source_info(ty: Ty<'tcx>, source_info: SourceInfo) -> Self {
1025         LocalDecl {
1026             mutability: Mutability::Mut,
1027             local_info: None,
1028             internal: false,
1029             is_block_tail: None,
1030             ty,
1031             user_ty: None,
1032             source_info,
1033         }
1034     }
1035
1036     /// Converts `self` into same `LocalDecl` except tagged as internal.
1037     #[inline]
1038     pub fn internal(mut self) -> Self {
1039         self.internal = true;
1040         self
1041     }
1042
1043     /// Converts `self` into same `LocalDecl` except tagged as immutable.
1044     #[inline]
1045     pub fn immutable(mut self) -> Self {
1046         self.mutability = Mutability::Not;
1047         self
1048     }
1049
1050     /// Converts `self` into same `LocalDecl` except tagged as internal temporary.
1051     #[inline]
1052     pub fn block_tail(mut self, info: BlockTailInfo) -> Self {
1053         assert!(self.is_block_tail.is_none());
1054         self.is_block_tail = Some(info);
1055         self
1056     }
1057 }
1058
1059 /// Debug information pertaining to a user variable.
1060 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
1061 pub struct VarDebugInfo<'tcx> {
1062     pub name: Symbol,
1063
1064     /// Source info of the user variable, including the scope
1065     /// within which the variable is visible (to debuginfo)
1066     /// (see `LocalDecl`'s `source_info` field for more details).
1067     pub source_info: SourceInfo,
1068
1069     /// Where the data for this user variable is to be found.
1070     /// NOTE(eddyb) There's an unenforced invariant that this `Place` is
1071     /// based on a `Local`, not a `Static`, and contains no indexing.
1072     pub place: Place<'tcx>,
1073 }
1074
1075 ///////////////////////////////////////////////////////////////////////////
1076 // BasicBlock
1077
1078 rustc_index::newtype_index! {
1079     /// The unit of the MIR [control-flow graph][CFG].
1080     ///
1081     /// There is no branching (e.g., `if`s, function calls, etc.) within a basic block, which makes
1082     /// it easier to do [data-flow analyses] and optimizations. Instead, branches are represented
1083     /// as an edge in a graph between basic blocks.
1084     ///
1085     /// Basic blocks consist of a series of [statements][`Statement`], ending with a
1086     /// [terminator][`Terminator`]. Basic blocks can have multiple predecessors and successors.
1087     ///
1088     /// Read more about basic blocks in the [rustc-dev-guide][guide-mir].
1089     ///
1090     /// [CFG]: https://rustc-dev-guide.rust-lang.org/appendix/background.html#cfg
1091     /// [data-flow analyses]:
1092     ///     https://rustc-dev-guide.rust-lang.org/appendix/background.html#what-is-a-dataflow-analysis
1093     /// [guide-mir]: https://rustc-dev-guide.rust-lang.org/mir/
1094     pub struct BasicBlock {
1095         derive [HashStable]
1096         DEBUG_FORMAT = "bb{}",
1097         const START_BLOCK = 0,
1098     }
1099 }
1100
1101 impl BasicBlock {
1102     pub fn start_location(self) -> Location {
1103         Location { block: self, statement_index: 0 }
1104     }
1105 }
1106
1107 ///////////////////////////////////////////////////////////////////////////
1108 // BasicBlockData and Terminator
1109
1110 /// See [`BasicBlock`] for documentation on what basic blocks are at a high level.
1111 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
1112 pub struct BasicBlockData<'tcx> {
1113     /// List of statements in this block.
1114     pub statements: Vec<Statement<'tcx>>,
1115
1116     /// Terminator for this block.
1117     ///
1118     /// N.B., this should generally ONLY be `None` during construction.
1119     /// Therefore, you should generally access it via the
1120     /// `terminator()` or `terminator_mut()` methods. The only
1121     /// exception is that certain passes, such as `simplify_cfg`, swap
1122     /// out the terminator temporarily with `None` while they continue
1123     /// to recurse over the set of basic blocks.
1124     pub terminator: Option<Terminator<'tcx>>,
1125
1126     /// If true, this block lies on an unwind path. This is used
1127     /// during codegen where distinct kinds of basic blocks may be
1128     /// generated (particularly for MSVC cleanup). Unwind blocks must
1129     /// only branch to other unwind blocks.
1130     pub is_cleanup: bool,
1131 }
1132
1133 /// Information about an assertion failure.
1134 #[derive(Clone, TyEncodable, TyDecodable, HashStable, PartialEq)]
1135 pub enum AssertKind<O> {
1136     BoundsCheck { len: O, index: O },
1137     Overflow(BinOp, O, O),
1138     OverflowNeg(O),
1139     DivisionByZero(O),
1140     RemainderByZero(O),
1141     ResumedAfterReturn(GeneratorKind),
1142     ResumedAfterPanic(GeneratorKind),
1143 }
1144
1145 #[derive(Clone, Debug, PartialEq, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
1146 pub enum InlineAsmOperand<'tcx> {
1147     In {
1148         reg: InlineAsmRegOrRegClass,
1149         value: Operand<'tcx>,
1150     },
1151     Out {
1152         reg: InlineAsmRegOrRegClass,
1153         late: bool,
1154         place: Option<Place<'tcx>>,
1155     },
1156     InOut {
1157         reg: InlineAsmRegOrRegClass,
1158         late: bool,
1159         in_value: Operand<'tcx>,
1160         out_place: Option<Place<'tcx>>,
1161     },
1162     Const {
1163         value: Operand<'tcx>,
1164     },
1165     SymFn {
1166         value: Box<Constant<'tcx>>,
1167     },
1168     SymStatic {
1169         def_id: DefId,
1170     },
1171 }
1172
1173 /// Type for MIR `Assert` terminator error messages.
1174 pub type AssertMessage<'tcx> = AssertKind<Operand<'tcx>>;
1175
1176 pub type Successors<'a> =
1177     iter::Chain<option::IntoIter<&'a BasicBlock>, slice::Iter<'a, BasicBlock>>;
1178 pub type SuccessorsMut<'a> =
1179     iter::Chain<option::IntoIter<&'a mut BasicBlock>, slice::IterMut<'a, BasicBlock>>;
1180
1181 impl<'tcx> BasicBlockData<'tcx> {
1182     pub fn new(terminator: Option<Terminator<'tcx>>) -> BasicBlockData<'tcx> {
1183         BasicBlockData { statements: vec![], terminator, is_cleanup: false }
1184     }
1185
1186     /// Accessor for terminator.
1187     ///
1188     /// Terminator may not be None after construction of the basic block is complete. This accessor
1189     /// provides a convenience way to reach the terminator.
1190     pub fn terminator(&self) -> &Terminator<'tcx> {
1191         self.terminator.as_ref().expect("invalid terminator state")
1192     }
1193
1194     pub fn terminator_mut(&mut self) -> &mut Terminator<'tcx> {
1195         self.terminator.as_mut().expect("invalid terminator state")
1196     }
1197
1198     pub fn retain_statements<F>(&mut self, mut f: F)
1199     where
1200         F: FnMut(&mut Statement<'_>) -> bool,
1201     {
1202         for s in &mut self.statements {
1203             if !f(s) {
1204                 s.make_nop();
1205             }
1206         }
1207     }
1208
1209     pub fn expand_statements<F, I>(&mut self, mut f: F)
1210     where
1211         F: FnMut(&mut Statement<'tcx>) -> Option<I>,
1212         I: iter::TrustedLen<Item = Statement<'tcx>>,
1213     {
1214         // Gather all the iterators we'll need to splice in, and their positions.
1215         let mut splices: Vec<(usize, I)> = vec![];
1216         let mut extra_stmts = 0;
1217         for (i, s) in self.statements.iter_mut().enumerate() {
1218             if let Some(mut new_stmts) = f(s) {
1219                 if let Some(first) = new_stmts.next() {
1220                     // We can already store the first new statement.
1221                     *s = first;
1222
1223                     // Save the other statements for optimized splicing.
1224                     let remaining = new_stmts.size_hint().0;
1225                     if remaining > 0 {
1226                         splices.push((i + 1 + extra_stmts, new_stmts));
1227                         extra_stmts += remaining;
1228                     }
1229                 } else {
1230                     s.make_nop();
1231                 }
1232             }
1233         }
1234
1235         // Splice in the new statements, from the end of the block.
1236         // FIXME(eddyb) This could be more efficient with a "gap buffer"
1237         // where a range of elements ("gap") is left uninitialized, with
1238         // splicing adding new elements to the end of that gap and moving
1239         // existing elements from before the gap to the end of the gap.
1240         // For now, this is safe code, emulating a gap but initializing it.
1241         let mut gap = self.statements.len()..self.statements.len() + extra_stmts;
1242         self.statements.resize(
1243             gap.end,
1244             Statement { source_info: SourceInfo::outermost(DUMMY_SP), kind: StatementKind::Nop },
1245         );
1246         for (splice_start, new_stmts) in splices.into_iter().rev() {
1247             let splice_end = splice_start + new_stmts.size_hint().0;
1248             while gap.end > splice_end {
1249                 gap.start -= 1;
1250                 gap.end -= 1;
1251                 self.statements.swap(gap.start, gap.end);
1252             }
1253             self.statements.splice(splice_start..splice_end, new_stmts);
1254             gap.end = splice_start;
1255         }
1256     }
1257
1258     pub fn visitable(&self, index: usize) -> &dyn MirVisitable<'tcx> {
1259         if index < self.statements.len() { &self.statements[index] } else { &self.terminator }
1260     }
1261 }
1262
1263 impl<O> AssertKind<O> {
1264     /// Getting a description does not require `O` to be printable, and does not
1265     /// require allocation.
1266     /// The caller is expected to handle `BoundsCheck` separately.
1267     pub fn description(&self) -> &'static str {
1268         use AssertKind::*;
1269         match self {
1270             Overflow(BinOp::Add, _, _) => "attempt to add with overflow",
1271             Overflow(BinOp::Sub, _, _) => "attempt to subtract with overflow",
1272             Overflow(BinOp::Mul, _, _) => "attempt to multiply with overflow",
1273             Overflow(BinOp::Div, _, _) => "attempt to divide with overflow",
1274             Overflow(BinOp::Rem, _, _) => "attempt to calculate the remainder with overflow",
1275             OverflowNeg(_) => "attempt to negate with overflow",
1276             Overflow(BinOp::Shr, _, _) => "attempt to shift right with overflow",
1277             Overflow(BinOp::Shl, _, _) => "attempt to shift left with overflow",
1278             Overflow(op, _, _) => bug!("{:?} cannot overflow", op),
1279             DivisionByZero(_) => "attempt to divide by zero",
1280             RemainderByZero(_) => "attempt to calculate the remainder with a divisor of zero",
1281             ResumedAfterReturn(GeneratorKind::Gen) => "generator resumed after completion",
1282             ResumedAfterReturn(GeneratorKind::Async(_)) => "`async fn` resumed after completion",
1283             ResumedAfterPanic(GeneratorKind::Gen) => "generator resumed after panicking",
1284             ResumedAfterPanic(GeneratorKind::Async(_)) => "`async fn` resumed after panicking",
1285             BoundsCheck { .. } => bug!("Unexpected AssertKind"),
1286         }
1287     }
1288
1289     /// Format the message arguments for the `assert(cond, msg..)` terminator in MIR printing.
1290     fn fmt_assert_args<W: Write>(&self, f: &mut W) -> fmt::Result
1291     where
1292         O: Debug,
1293     {
1294         use AssertKind::*;
1295         match self {
1296             BoundsCheck { ref len, ref index } => write!(
1297                 f,
1298                 "\"index out of bounds: the len is {{}} but the index is {{}}\", {:?}, {:?}",
1299                 len, index
1300             ),
1301
1302             OverflowNeg(op) => {
1303                 write!(f, "\"attempt to negate {{}} which would overflow\", {:?}", op)
1304             }
1305             DivisionByZero(op) => write!(f, "\"attempt to divide {{}} by zero\", {:?}", op),
1306             RemainderByZero(op) => write!(
1307                 f,
1308                 "\"attempt to calculate the remainder of {{}} with a divisor of zero\", {:?}",
1309                 op
1310             ),
1311             Overflow(BinOp::Add, l, r) => write!(
1312                 f,
1313                 "\"attempt to compute `{{}} + {{}}` which would overflow\", {:?}, {:?}",
1314                 l, r
1315             ),
1316             Overflow(BinOp::Sub, l, r) => write!(
1317                 f,
1318                 "\"attempt to compute `{{}} - {{}}` which would overflow\", {:?}, {:?}",
1319                 l, r
1320             ),
1321             Overflow(BinOp::Mul, l, r) => write!(
1322                 f,
1323                 "\"attempt to compute `{{}} * {{}}` which would overflow\", {:?}, {:?}",
1324                 l, r
1325             ),
1326             Overflow(BinOp::Div, l, r) => write!(
1327                 f,
1328                 "\"attempt to compute `{{}} / {{}}` which would overflow\", {:?}, {:?}",
1329                 l, r
1330             ),
1331             Overflow(BinOp::Rem, l, r) => write!(
1332                 f,
1333                 "\"attempt to compute the remainder of `{{}} % {{}}` which would overflow\", {:?}, {:?}",
1334                 l, r
1335             ),
1336             Overflow(BinOp::Shr, _, r) => {
1337                 write!(f, "\"attempt to shift right by {{}} which would overflow\", {:?}", r)
1338             }
1339             Overflow(BinOp::Shl, _, r) => {
1340                 write!(f, "\"attempt to shift left by {{}} which would overflow\", {:?}", r)
1341             }
1342             _ => write!(f, "\"{}\"", self.description()),
1343         }
1344     }
1345 }
1346
1347 impl<O: fmt::Debug> fmt::Debug for AssertKind<O> {
1348     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1349         use AssertKind::*;
1350         match self {
1351             BoundsCheck { ref len, ref index } => {
1352                 write!(f, "index out of bounds: the len is {:?} but the index is {:?}", len, index)
1353             }
1354             OverflowNeg(op) => write!(f, "attempt to negate {:#?} which would overflow", op),
1355             DivisionByZero(op) => write!(f, "attempt to divide {:#?} by zero", op),
1356             RemainderByZero(op) => {
1357                 write!(f, "attempt to calculate the remainder of {:#?} with a divisor of zero", op)
1358             }
1359             Overflow(BinOp::Add, l, r) => {
1360                 write!(f, "attempt to compute `{:#?} + {:#?}` which would overflow", l, r)
1361             }
1362             Overflow(BinOp::Sub, l, r) => {
1363                 write!(f, "attempt to compute `{:#?} - {:#?}` which would overflow", l, r)
1364             }
1365             Overflow(BinOp::Mul, l, r) => {
1366                 write!(f, "attempt to compute `{:#?} * {:#?}` which would overflow", l, r)
1367             }
1368             Overflow(BinOp::Div, l, r) => {
1369                 write!(f, "attempt to compute `{:#?} / {:#?}` which would overflow", l, r)
1370             }
1371             Overflow(BinOp::Rem, l, r) => write!(
1372                 f,
1373                 "attempt to compute the remainder of `{:#?} % {:#?}` which would overflow",
1374                 l, r
1375             ),
1376             Overflow(BinOp::Shr, _, r) => {
1377                 write!(f, "attempt to shift right by {:#?} which would overflow", r)
1378             }
1379             Overflow(BinOp::Shl, _, r) => {
1380                 write!(f, "attempt to shift left by {:#?} which would overflow", r)
1381             }
1382             _ => write!(f, "{}", self.description()),
1383         }
1384     }
1385 }
1386
1387 ///////////////////////////////////////////////////////////////////////////
1388 // Statements
1389
1390 #[derive(Clone, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
1391 pub struct Statement<'tcx> {
1392     pub source_info: SourceInfo,
1393     pub kind: StatementKind<'tcx>,
1394 }
1395
1396 // `Statement` is used a lot. Make sure it doesn't unintentionally get bigger.
1397 #[cfg(target_arch = "x86_64")]
1398 static_assert_size!(Statement<'_>, 32);
1399
1400 impl Statement<'_> {
1401     /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
1402     /// invalidating statement indices in `Location`s.
1403     pub fn make_nop(&mut self) {
1404         self.kind = StatementKind::Nop
1405     }
1406
1407     /// Changes a statement to a nop and returns the original statement.
1408     pub fn replace_nop(&mut self) -> Self {
1409         Statement {
1410             source_info: self.source_info,
1411             kind: mem::replace(&mut self.kind, StatementKind::Nop),
1412         }
1413     }
1414 }
1415
1416 #[derive(Clone, Debug, PartialEq, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
1417 pub enum StatementKind<'tcx> {
1418     /// Write the RHS Rvalue to the LHS Place.
1419     Assign(Box<(Place<'tcx>, Rvalue<'tcx>)>),
1420
1421     /// This represents all the reading that a pattern match may do
1422     /// (e.g., inspecting constants and discriminant values), and the
1423     /// kind of pattern it comes from. This is in order to adapt potential
1424     /// error messages to these specific patterns.
1425     ///
1426     /// Note that this also is emitted for regular `let` bindings to ensure that locals that are
1427     /// never accessed still get some sanity checks for, e.g., `let x: ! = ..;`
1428     FakeRead(FakeReadCause, Box<Place<'tcx>>),
1429
1430     /// Write the discriminant for a variant to the enum Place.
1431     SetDiscriminant { place: Box<Place<'tcx>>, variant_index: VariantIdx },
1432
1433     /// Start a live range for the storage of the local.
1434     StorageLive(Local),
1435
1436     /// End the current live range for the storage of the local.
1437     StorageDead(Local),
1438
1439     /// Executes a piece of inline Assembly. Stored in a Box to keep the size
1440     /// of `StatementKind` low.
1441     LlvmInlineAsm(Box<LlvmInlineAsm<'tcx>>),
1442
1443     /// Retag references in the given place, ensuring they got fresh tags. This is
1444     /// part of the Stacked Borrows model. These statements are currently only interpreted
1445     /// by miri and only generated when "-Z mir-emit-retag" is passed.
1446     /// See <https://internals.rust-lang.org/t/stacked-borrows-an-aliasing-model-for-rust/8153/>
1447     /// for more details.
1448     Retag(RetagKind, Box<Place<'tcx>>),
1449
1450     /// Encodes a user's type ascription. These need to be preserved
1451     /// intact so that NLL can respect them. For example:
1452     ///
1453     ///     let a: T = y;
1454     ///
1455     /// The effect of this annotation is to relate the type `T_y` of the place `y`
1456     /// to the user-given type `T`. The effect depends on the specified variance:
1457     ///
1458     /// - `Covariant` -- requires that `T_y <: T`
1459     /// - `Contravariant` -- requires that `T_y :> T`
1460     /// - `Invariant` -- requires that `T_y == T`
1461     /// - `Bivariant` -- no effect
1462     AscribeUserType(Box<(Place<'tcx>, UserTypeProjection)>, ty::Variance),
1463
1464     /// Marks the start of a "coverage region", injected with '-Zinstrument-coverage'. A
1465     /// `CoverageInfo` statement carries metadata about the coverage region, used to inject a coverage
1466     /// map into the binary. The `Counter` kind also generates executable code, to increment a
1467     /// counter varible at runtime, each time the code region is executed.
1468     Coverage(Box<Coverage>),
1469
1470     /// No-op. Useful for deleting instructions without affecting statement indices.
1471     Nop,
1472 }
1473
1474 impl<'tcx> StatementKind<'tcx> {
1475     pub fn as_assign_mut(&mut self) -> Option<&mut Box<(Place<'tcx>, Rvalue<'tcx>)>> {
1476         match self {
1477             StatementKind::Assign(x) => Some(x),
1478             _ => None,
1479         }
1480     }
1481 }
1482
1483 /// Describes what kind of retag is to be performed.
1484 #[derive(Copy, Clone, TyEncodable, TyDecodable, Debug, PartialEq, Eq, HashStable)]
1485 pub enum RetagKind {
1486     /// The initial retag when entering a function.
1487     FnEntry,
1488     /// Retag preparing for a two-phase borrow.
1489     TwoPhase,
1490     /// Retagging raw pointers.
1491     Raw,
1492     /// A "normal" retag.
1493     Default,
1494 }
1495
1496 /// The `FakeReadCause` describes the type of pattern why a FakeRead statement exists.
1497 #[derive(Copy, Clone, TyEncodable, TyDecodable, Debug, HashStable, PartialEq)]
1498 pub enum FakeReadCause {
1499     /// Inject a fake read of the borrowed input at the end of each guards
1500     /// code.
1501     ///
1502     /// This should ensure that you cannot change the variant for an enum while
1503     /// you are in the midst of matching on it.
1504     ForMatchGuard,
1505
1506     /// `let x: !; match x {}` doesn't generate any read of x so we need to
1507     /// generate a read of x to check that it is initialized and safe.
1508     ForMatchedPlace,
1509
1510     /// A fake read of the RefWithinGuard version of a bind-by-value variable
1511     /// in a match guard to ensure that it's value hasn't change by the time
1512     /// we create the OutsideGuard version.
1513     ForGuardBinding,
1514
1515     /// Officially, the semantics of
1516     ///
1517     /// `let pattern = <expr>;`
1518     ///
1519     /// is that `<expr>` is evaluated into a temporary and then this temporary is
1520     /// into the pattern.
1521     ///
1522     /// However, if we see the simple pattern `let var = <expr>`, we optimize this to
1523     /// evaluate `<expr>` directly into the variable `var`. This is mostly unobservable,
1524     /// but in some cases it can affect the borrow checker, as in #53695.
1525     /// Therefore, we insert a "fake read" here to ensure that we get
1526     /// appropriate errors.
1527     ForLet,
1528
1529     /// If we have an index expression like
1530     ///
1531     /// (*x)[1][{ x = y; 4}]
1532     ///
1533     /// then the first bounds check is invalidated when we evaluate the second
1534     /// index expression. Thus we create a fake borrow of `x` across the second
1535     /// indexer, which will cause a borrow check error.
1536     ForIndex,
1537 }
1538
1539 #[derive(Clone, Debug, PartialEq, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
1540 pub struct LlvmInlineAsm<'tcx> {
1541     pub asm: hir::LlvmInlineAsmInner,
1542     pub outputs: Box<[Place<'tcx>]>,
1543     pub inputs: Box<[(Span, Operand<'tcx>)]>,
1544 }
1545
1546 impl Debug for Statement<'_> {
1547     fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1548         use self::StatementKind::*;
1549         match self.kind {
1550             Assign(box (ref place, ref rv)) => write!(fmt, "{:?} = {:?}", place, rv),
1551             FakeRead(ref cause, ref place) => write!(fmt, "FakeRead({:?}, {:?})", cause, place),
1552             Retag(ref kind, ref place) => write!(
1553                 fmt,
1554                 "Retag({}{:?})",
1555                 match kind {
1556                     RetagKind::FnEntry => "[fn entry] ",
1557                     RetagKind::TwoPhase => "[2phase] ",
1558                     RetagKind::Raw => "[raw] ",
1559                     RetagKind::Default => "",
1560                 },
1561                 place,
1562             ),
1563             StorageLive(ref place) => write!(fmt, "StorageLive({:?})", place),
1564             StorageDead(ref place) => write!(fmt, "StorageDead({:?})", place),
1565             SetDiscriminant { ref place, variant_index } => {
1566                 write!(fmt, "discriminant({:?}) = {:?}", place, variant_index)
1567             }
1568             LlvmInlineAsm(ref asm) => {
1569                 write!(fmt, "llvm_asm!({:?} : {:?} : {:?})", asm.asm, asm.outputs, asm.inputs)
1570             }
1571             AscribeUserType(box (ref place, ref c_ty), ref variance) => {
1572                 write!(fmt, "AscribeUserType({:?}, {:?}, {:?})", place, variance, c_ty)
1573             }
1574             Coverage(box ref coverage) => {
1575                 let rgn = &coverage.code_region;
1576                 match coverage.kind {
1577                     CoverageKind::Counter { id, .. } => {
1578                         write!(fmt, "Coverage::Counter({:?}) for {:?}", id.index(), rgn)
1579                     }
1580                     CoverageKind::Expression { id, lhs, op, rhs } => write!(
1581                         fmt,
1582                         "Coverage::Expression({:?}) = {} {} {} for {:?}",
1583                         id.index(),
1584                         lhs.index(),
1585                         if op == coverage::Op::Add { "+" } else { "-" },
1586                         rhs.index(),
1587                         rgn
1588                     ),
1589                     CoverageKind::Unreachable => write!(fmt, "Coverage::Unreachable for {:?}", rgn),
1590                 }
1591             }
1592             Nop => write!(fmt, "nop"),
1593         }
1594     }
1595 }
1596
1597 #[derive(Clone, Debug, PartialEq, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
1598 pub struct Coverage {
1599     pub kind: CoverageKind,
1600     pub code_region: CodeRegion,
1601 }
1602
1603 ///////////////////////////////////////////////////////////////////////////
1604 // Places
1605
1606 /// A path to a value; something that can be evaluated without
1607 /// changing or disturbing program state.
1608 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, HashStable)]
1609 pub struct Place<'tcx> {
1610     pub local: Local,
1611
1612     /// projection out of a place (access a field, deref a pointer, etc)
1613     pub projection: &'tcx List<PlaceElem<'tcx>>,
1614 }
1615
1616 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
1617 #[derive(TyEncodable, TyDecodable, HashStable)]
1618 pub enum ProjectionElem<V, T> {
1619     Deref,
1620     Field(Field, T),
1621     Index(V),
1622
1623     /// These indices are generated by slice patterns. Easiest to explain
1624     /// by example:
1625     ///
1626     /// ```
1627     /// [X, _, .._, _, _] => { offset: 0, min_length: 4, from_end: false },
1628     /// [_, X, .._, _, _] => { offset: 1, min_length: 4, from_end: false },
1629     /// [_, _, .._, X, _] => { offset: 2, min_length: 4, from_end: true },
1630     /// [_, _, .._, _, X] => { offset: 1, min_length: 4, from_end: true },
1631     /// ```
1632     ConstantIndex {
1633         /// index or -index (in Python terms), depending on from_end
1634         offset: u64,
1635         /// The thing being indexed must be at least this long. For arrays this
1636         /// is always the exact length.
1637         min_length: u64,
1638         /// Counting backwards from end? This is always false when indexing an
1639         /// array.
1640         from_end: bool,
1641     },
1642
1643     /// These indices are generated by slice patterns.
1644     ///
1645     /// If `from_end` is true `slice[from..slice.len() - to]`.
1646     /// Otherwise `array[from..to]`.
1647     Subslice {
1648         from: u64,
1649         to: u64,
1650         /// Whether `to` counts from the start or end of the array/slice.
1651         /// For `PlaceElem`s this is `true` if and only if the base is a slice.
1652         /// For `ProjectionKind`, this can also be `true` for arrays.
1653         from_end: bool,
1654     },
1655
1656     /// "Downcast" to a variant of an ADT. Currently, we only introduce
1657     /// this for ADTs with more than one variant. It may be better to
1658     /// just introduce it always, or always for enums.
1659     ///
1660     /// The included Symbol is the name of the variant, used for printing MIR.
1661     Downcast(Option<Symbol>, VariantIdx),
1662 }
1663
1664 impl<V, T> ProjectionElem<V, T> {
1665     /// Returns `true` if the target of this projection may refer to a different region of memory
1666     /// than the base.
1667     fn is_indirect(&self) -> bool {
1668         match self {
1669             Self::Deref => true,
1670
1671             Self::Field(_, _)
1672             | Self::Index(_)
1673             | Self::ConstantIndex { .. }
1674             | Self::Subslice { .. }
1675             | Self::Downcast(_, _) => false,
1676         }
1677     }
1678 }
1679
1680 /// Alias for projections as they appear in places, where the base is a place
1681 /// and the index is a local.
1682 pub type PlaceElem<'tcx> = ProjectionElem<Local, Ty<'tcx>>;
1683
1684 // At least on 64 bit systems, `PlaceElem` should not be larger than two pointers.
1685 #[cfg(target_arch = "x86_64")]
1686 static_assert_size!(PlaceElem<'_>, 24);
1687
1688 /// Alias for projections as they appear in `UserTypeProjection`, where we
1689 /// need neither the `V` parameter for `Index` nor the `T` for `Field`.
1690 pub type ProjectionKind = ProjectionElem<(), ()>;
1691
1692 rustc_index::newtype_index! {
1693     pub struct Field {
1694         derive [HashStable]
1695         DEBUG_FORMAT = "field[{}]"
1696     }
1697 }
1698
1699 #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
1700 pub struct PlaceRef<'tcx> {
1701     pub local: Local,
1702     pub projection: &'tcx [PlaceElem<'tcx>],
1703 }
1704
1705 impl<'tcx> Place<'tcx> {
1706     // FIXME change this to a const fn by also making List::empty a const fn.
1707     pub fn return_place() -> Place<'tcx> {
1708         Place { local: RETURN_PLACE, projection: List::empty() }
1709     }
1710
1711     /// Returns `true` if this `Place` contains a `Deref` projection.
1712     ///
1713     /// If `Place::is_indirect` returns false, the caller knows that the `Place` refers to the
1714     /// same region of memory as its base.
1715     pub fn is_indirect(&self) -> bool {
1716         self.projection.iter().any(|elem| elem.is_indirect())
1717     }
1718
1719     /// Finds the innermost `Local` from this `Place`, *if* it is either a local itself or
1720     /// a single deref of a local.
1721     //
1722     // FIXME: can we safely swap the semantics of `fn base_local` below in here instead?
1723     pub fn local_or_deref_local(&self) -> Option<Local> {
1724         match self.as_ref() {
1725             PlaceRef { local, projection: [] }
1726             | PlaceRef { local, projection: [ProjectionElem::Deref] } => Some(local),
1727             _ => None,
1728         }
1729     }
1730
1731     /// If this place represents a local variable like `_X` with no
1732     /// projections, return `Some(_X)`.
1733     pub fn as_local(&self) -> Option<Local> {
1734         self.as_ref().as_local()
1735     }
1736
1737     pub fn as_ref(&self) -> PlaceRef<'tcx> {
1738         PlaceRef { local: self.local, projection: &self.projection }
1739     }
1740 }
1741
1742 impl From<Local> for Place<'_> {
1743     fn from(local: Local) -> Self {
1744         Place { local, projection: List::empty() }
1745     }
1746 }
1747
1748 impl<'tcx> PlaceRef<'tcx> {
1749     /// Finds the innermost `Local` from this `Place`, *if* it is either a local itself or
1750     /// a single deref of a local.
1751     //
1752     // FIXME: can we safely swap the semantics of `fn base_local` below in here instead?
1753     pub fn local_or_deref_local(&self) -> Option<Local> {
1754         match *self {
1755             PlaceRef { local, projection: [] }
1756             | PlaceRef { local, projection: [ProjectionElem::Deref] } => Some(local),
1757             _ => None,
1758         }
1759     }
1760
1761     /// If this place represents a local variable like `_X` with no
1762     /// projections, return `Some(_X)`.
1763     pub fn as_local(&self) -> Option<Local> {
1764         match *self {
1765             PlaceRef { local, projection: [] } => Some(local),
1766             _ => None,
1767         }
1768     }
1769 }
1770
1771 impl Debug for Place<'_> {
1772     fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1773         for elem in self.projection.iter().rev() {
1774             match elem {
1775                 ProjectionElem::Downcast(_, _) | ProjectionElem::Field(_, _) => {
1776                     write!(fmt, "(").unwrap();
1777                 }
1778                 ProjectionElem::Deref => {
1779                     write!(fmt, "(*").unwrap();
1780                 }
1781                 ProjectionElem::Index(_)
1782                 | ProjectionElem::ConstantIndex { .. }
1783                 | ProjectionElem::Subslice { .. } => {}
1784             }
1785         }
1786
1787         write!(fmt, "{:?}", self.local)?;
1788
1789         for elem in self.projection.iter() {
1790             match elem {
1791                 ProjectionElem::Downcast(Some(name), _index) => {
1792                     write!(fmt, " as {})", name)?;
1793                 }
1794                 ProjectionElem::Downcast(None, index) => {
1795                     write!(fmt, " as variant#{:?})", index)?;
1796                 }
1797                 ProjectionElem::Deref => {
1798                     write!(fmt, ")")?;
1799                 }
1800                 ProjectionElem::Field(field, ty) => {
1801                     write!(fmt, ".{:?}: {:?})", field.index(), ty)?;
1802                 }
1803                 ProjectionElem::Index(ref index) => {
1804                     write!(fmt, "[{:?}]", index)?;
1805                 }
1806                 ProjectionElem::ConstantIndex { offset, min_length, from_end: false } => {
1807                     write!(fmt, "[{:?} of {:?}]", offset, min_length)?;
1808                 }
1809                 ProjectionElem::ConstantIndex { offset, min_length, from_end: true } => {
1810                     write!(fmt, "[-{:?} of {:?}]", offset, min_length)?;
1811                 }
1812                 ProjectionElem::Subslice { from, to, from_end: true } if to == 0 => {
1813                     write!(fmt, "[{:?}:]", from)?;
1814                 }
1815                 ProjectionElem::Subslice { from, to, from_end: true } if from == 0 => {
1816                     write!(fmt, "[:-{:?}]", to)?;
1817                 }
1818                 ProjectionElem::Subslice { from, to, from_end: true } => {
1819                     write!(fmt, "[{:?}:-{:?}]", from, to)?;
1820                 }
1821                 ProjectionElem::Subslice { from, to, from_end: false } => {
1822                     write!(fmt, "[{:?}..{:?}]", from, to)?;
1823                 }
1824             }
1825         }
1826
1827         Ok(())
1828     }
1829 }
1830
1831 ///////////////////////////////////////////////////////////////////////////
1832 // Scopes
1833
1834 rustc_index::newtype_index! {
1835     pub struct SourceScope {
1836         derive [HashStable]
1837         DEBUG_FORMAT = "scope[{}]",
1838         const OUTERMOST_SOURCE_SCOPE = 0,
1839     }
1840 }
1841
1842 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable)]
1843 pub struct SourceScopeData {
1844     pub span: Span,
1845     pub parent_scope: Option<SourceScope>,
1846
1847     /// Crate-local information for this source scope, that can't (and
1848     /// needn't) be tracked across crates.
1849     pub local_data: ClearCrossCrate<SourceScopeLocalData>,
1850 }
1851
1852 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable)]
1853 pub struct SourceScopeLocalData {
1854     /// An `HirId` with lint levels equivalent to this scope's lint levels.
1855     pub lint_root: hir::HirId,
1856     /// The unsafe block that contains this node.
1857     pub safety: Safety,
1858 }
1859
1860 ///////////////////////////////////////////////////////////////////////////
1861 // Operands
1862
1863 /// These are values that can appear inside an rvalue. They are intentionally
1864 /// limited to prevent rvalues from being nested in one another.
1865 #[derive(Clone, PartialEq, TyEncodable, TyDecodable, HashStable)]
1866 pub enum Operand<'tcx> {
1867     /// Copy: The value must be available for use afterwards.
1868     ///
1869     /// This implies that the type of the place must be `Copy`; this is true
1870     /// by construction during build, but also checked by the MIR type checker.
1871     Copy(Place<'tcx>),
1872
1873     /// Move: The value (including old borrows of it) will not be used again.
1874     ///
1875     /// Safe for values of all types (modulo future developments towards `?Move`).
1876     /// Correct usage patterns are enforced by the borrow checker for safe code.
1877     /// `Copy` may be converted to `Move` to enable "last-use" optimizations.
1878     Move(Place<'tcx>),
1879
1880     /// Synthesizes a constant value.
1881     Constant(Box<Constant<'tcx>>),
1882 }
1883
1884 impl<'tcx> Debug for Operand<'tcx> {
1885     fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1886         use self::Operand::*;
1887         match *self {
1888             Constant(ref a) => write!(fmt, "{:?}", a),
1889             Copy(ref place) => write!(fmt, "{:?}", place),
1890             Move(ref place) => write!(fmt, "move {:?}", place),
1891         }
1892     }
1893 }
1894
1895 impl<'tcx> Operand<'tcx> {
1896     /// Convenience helper to make a constant that refers to the fn
1897     /// with given `DefId` and substs. Since this is used to synthesize
1898     /// MIR, assumes `user_ty` is None.
1899     pub fn function_handle(
1900         tcx: TyCtxt<'tcx>,
1901         def_id: DefId,
1902         substs: SubstsRef<'tcx>,
1903         span: Span,
1904     ) -> Self {
1905         let ty = tcx.type_of(def_id).subst(tcx, substs);
1906         Operand::Constant(box Constant {
1907             span,
1908             user_ty: None,
1909             literal: ty::Const::zero_sized(tcx, ty),
1910         })
1911     }
1912
1913     pub fn is_move(&self) -> bool {
1914         matches!(self, Operand::Move(..))
1915     }
1916
1917     /// Convenience helper to make a literal-like constant from a given scalar value.
1918     /// Since this is used to synthesize MIR, assumes `user_ty` is None.
1919     pub fn const_from_scalar(
1920         tcx: TyCtxt<'tcx>,
1921         ty: Ty<'tcx>,
1922         val: Scalar,
1923         span: Span,
1924     ) -> Operand<'tcx> {
1925         debug_assert!({
1926             let param_env_and_ty = ty::ParamEnv::empty().and(ty);
1927             let type_size = tcx
1928                 .layout_of(param_env_and_ty)
1929                 .unwrap_or_else(|e| panic!("could not compute layout for {:?}: {:?}", ty, e))
1930                 .size;
1931             let scalar_size = abi::Size::from_bytes(match val {
1932                 Scalar::Raw { size, .. } => size,
1933                 _ => panic!("Invalid scalar type {:?}", val),
1934             });
1935             scalar_size == type_size
1936         });
1937         Operand::Constant(box Constant {
1938             span,
1939             user_ty: None,
1940             literal: ty::Const::from_scalar(tcx, val, ty),
1941         })
1942     }
1943
1944     /// Convenience helper to make a `Scalar` from the given `Operand`, assuming that `Operand`
1945     /// wraps a constant literal value. Panics if this is not the case.
1946     pub fn scalar_from_const(operand: &Operand<'tcx>) -> Scalar {
1947         match operand {
1948             Operand::Constant(constant) => match constant.literal.val.try_to_scalar() {
1949                 Some(scalar) => scalar,
1950                 _ => panic!("{:?}: Scalar value expected", constant.literal.val),
1951             },
1952             _ => panic!("{:?}: Constant expected", operand),
1953         }
1954     }
1955
1956     /// Convenience helper to make a literal-like constant from a given `&str` slice.
1957     /// Since this is used to synthesize MIR, assumes `user_ty` is None.
1958     pub fn const_from_str(tcx: TyCtxt<'tcx>, val: &str, span: Span) -> Operand<'tcx> {
1959         let tcx = tcx;
1960         let allocation = Allocation::from_byte_aligned_bytes(val.as_bytes());
1961         let allocation = tcx.intern_const_alloc(allocation);
1962         let const_val = ConstValue::Slice { data: allocation, start: 0, end: val.len() };
1963         let ty = tcx.mk_imm_ref(tcx.lifetimes.re_erased, tcx.types.str_);
1964         Operand::Constant(box Constant {
1965             span,
1966             user_ty: None,
1967             literal: ty::Const::from_value(tcx, const_val, ty),
1968         })
1969     }
1970
1971     /// Convenience helper to make a `ConstValue` from the given `Operand`, assuming that `Operand`
1972     /// wraps a constant value (such as a `&str` slice). Panics if this is not the case.
1973     pub fn value_from_const(operand: &Operand<'tcx>) -> ConstValue<'tcx> {
1974         match operand {
1975             Operand::Constant(constant) => match constant.literal.val.try_to_value() {
1976                 Some(const_value) => const_value,
1977                 _ => panic!("{:?}: ConstValue expected", constant.literal.val),
1978             },
1979             _ => panic!("{:?}: Constant expected", operand),
1980         }
1981     }
1982
1983     pub fn to_copy(&self) -> Self {
1984         match *self {
1985             Operand::Copy(_) | Operand::Constant(_) => self.clone(),
1986             Operand::Move(place) => Operand::Copy(place),
1987         }
1988     }
1989
1990     /// Returns the `Place` that is the target of this `Operand`, or `None` if this `Operand` is a
1991     /// constant.
1992     pub fn place(&self) -> Option<Place<'tcx>> {
1993         match self {
1994             Operand::Copy(place) | Operand::Move(place) => Some(*place),
1995             Operand::Constant(_) => None,
1996         }
1997     }
1998
1999     /// Returns the `Constant` that is the target of this `Operand`, or `None` if this `Operand` is a
2000     /// place.
2001     pub fn constant(&self) -> Option<&Constant<'tcx>> {
2002         match self {
2003             Operand::Constant(x) => Some(&**x),
2004             Operand::Copy(_) | Operand::Move(_) => None,
2005         }
2006     }
2007 }
2008
2009 ///////////////////////////////////////////////////////////////////////////
2010 /// Rvalues
2011
2012 #[derive(Clone, TyEncodable, TyDecodable, HashStable, PartialEq)]
2013 pub enum Rvalue<'tcx> {
2014     /// x (either a move or copy, depending on type of x)
2015     Use(Operand<'tcx>),
2016
2017     /// [x; 32]
2018     Repeat(Operand<'tcx>, &'tcx ty::Const<'tcx>),
2019
2020     /// &x or &mut x
2021     Ref(Region<'tcx>, BorrowKind, Place<'tcx>),
2022
2023     /// Accessing a thread local static. This is inherently a runtime operation, even if llvm
2024     /// treats it as an access to a static. This `Rvalue` yields a reference to the thread local
2025     /// static.
2026     ThreadLocalRef(DefId),
2027
2028     /// Create a raw pointer to the given place
2029     /// Can be generated by raw address of expressions (`&raw const x`),
2030     /// or when casting a reference to a raw pointer.
2031     AddressOf(Mutability, Place<'tcx>),
2032
2033     /// length of a `[X]` or `[X;n]` value
2034     Len(Place<'tcx>),
2035
2036     Cast(CastKind, Operand<'tcx>, Ty<'tcx>),
2037
2038     BinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
2039     CheckedBinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
2040
2041     NullaryOp(NullOp, Ty<'tcx>),
2042     UnaryOp(UnOp, Operand<'tcx>),
2043
2044     /// Read the discriminant of an ADT.
2045     ///
2046     /// Undefined (i.e., no effort is made to make it defined, but there’s no reason why it cannot
2047     /// be defined to return, say, a 0) if ADT is not an enum.
2048     Discriminant(Place<'tcx>),
2049
2050     /// Creates an aggregate value, like a tuple or struct. This is
2051     /// only needed because we want to distinguish `dest = Foo { x:
2052     /// ..., y: ... }` from `dest.x = ...; dest.y = ...;` in the case
2053     /// that `Foo` has a destructor. These rvalues can be optimized
2054     /// away after type-checking and before lowering.
2055     Aggregate(Box<AggregateKind<'tcx>>, Vec<Operand<'tcx>>),
2056 }
2057
2058 #[derive(Clone, Copy, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
2059 pub enum CastKind {
2060     Misc,
2061     Pointer(PointerCast),
2062 }
2063
2064 #[derive(Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
2065 pub enum AggregateKind<'tcx> {
2066     /// The type is of the element
2067     Array(Ty<'tcx>),
2068     Tuple,
2069
2070     /// The second field is the variant index. It's equal to 0 for struct
2071     /// and union expressions. The fourth field is
2072     /// active field number and is present only for union expressions
2073     /// -- e.g., for a union expression `SomeUnion { c: .. }`, the
2074     /// active field index would identity the field `c`
2075     Adt(&'tcx AdtDef, VariantIdx, SubstsRef<'tcx>, Option<UserTypeAnnotationIndex>, Option<usize>),
2076
2077     Closure(DefId, SubstsRef<'tcx>),
2078     Generator(DefId, SubstsRef<'tcx>, hir::Movability),
2079 }
2080
2081 #[derive(Copy, Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
2082 pub enum BinOp {
2083     /// The `+` operator (addition)
2084     Add,
2085     /// The `-` operator (subtraction)
2086     Sub,
2087     /// The `*` operator (multiplication)
2088     Mul,
2089     /// The `/` operator (division)
2090     Div,
2091     /// The `%` operator (modulus)
2092     Rem,
2093     /// The `^` operator (bitwise xor)
2094     BitXor,
2095     /// The `&` operator (bitwise and)
2096     BitAnd,
2097     /// The `|` operator (bitwise or)
2098     BitOr,
2099     /// The `<<` operator (shift left)
2100     Shl,
2101     /// The `>>` operator (shift right)
2102     Shr,
2103     /// The `==` operator (equality)
2104     Eq,
2105     /// The `<` operator (less than)
2106     Lt,
2107     /// The `<=` operator (less than or equal to)
2108     Le,
2109     /// The `!=` operator (not equal to)
2110     Ne,
2111     /// The `>=` operator (greater than or equal to)
2112     Ge,
2113     /// The `>` operator (greater than)
2114     Gt,
2115     /// The `ptr.offset` operator
2116     Offset,
2117 }
2118
2119 impl BinOp {
2120     pub fn is_checkable(self) -> bool {
2121         use self::BinOp::*;
2122         match self {
2123             Add | Sub | Mul | Shl | Shr => true,
2124             _ => false,
2125         }
2126     }
2127 }
2128
2129 #[derive(Copy, Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
2130 pub enum NullOp {
2131     /// Returns the size of a value of that type
2132     SizeOf,
2133     /// Creates a new uninitialized box for a value of that type
2134     Box,
2135 }
2136
2137 #[derive(Copy, Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
2138 pub enum UnOp {
2139     /// The `!` operator for logical inversion
2140     Not,
2141     /// The `-` operator for negation
2142     Neg,
2143 }
2144
2145 impl<'tcx> Debug for Rvalue<'tcx> {
2146     fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2147         use self::Rvalue::*;
2148
2149         match *self {
2150             Use(ref place) => write!(fmt, "{:?}", place),
2151             Repeat(ref a, ref b) => {
2152                 write!(fmt, "[{:?}; ", a)?;
2153                 pretty_print_const(b, fmt, false)?;
2154                 write!(fmt, "]")
2155             }
2156             Len(ref a) => write!(fmt, "Len({:?})", a),
2157             Cast(ref kind, ref place, ref ty) => {
2158                 write!(fmt, "{:?} as {:?} ({:?})", place, ty, kind)
2159             }
2160             BinaryOp(ref op, ref a, ref b) => write!(fmt, "{:?}({:?}, {:?})", op, a, b),
2161             CheckedBinaryOp(ref op, ref a, ref b) => {
2162                 write!(fmt, "Checked{:?}({:?}, {:?})", op, a, b)
2163             }
2164             UnaryOp(ref op, ref a) => write!(fmt, "{:?}({:?})", op, a),
2165             Discriminant(ref place) => write!(fmt, "discriminant({:?})", place),
2166             NullaryOp(ref op, ref t) => write!(fmt, "{:?}({:?})", op, t),
2167             ThreadLocalRef(did) => ty::tls::with(|tcx| {
2168                 let muta = tcx.static_mutability(did).unwrap().prefix_str();
2169                 write!(fmt, "&/*tls*/ {}{}", muta, tcx.def_path_str(did))
2170             }),
2171             Ref(region, borrow_kind, ref place) => {
2172                 let kind_str = match borrow_kind {
2173                     BorrowKind::Shared => "",
2174                     BorrowKind::Shallow => "shallow ",
2175                     BorrowKind::Mut { .. } | BorrowKind::Unique => "mut ",
2176                 };
2177
2178                 // When printing regions, add trailing space if necessary.
2179                 let print_region = ty::tls::with(|tcx| {
2180                     tcx.sess.verbose() || tcx.sess.opts.debugging_opts.identify_regions
2181                 });
2182                 let region = if print_region {
2183                     let mut region = region.to_string();
2184                     if !region.is_empty() {
2185                         region.push(' ');
2186                     }
2187                     region
2188                 } else {
2189                     // Do not even print 'static
2190                     String::new()
2191                 };
2192                 write!(fmt, "&{}{}{:?}", region, kind_str, place)
2193             }
2194
2195             AddressOf(mutability, ref place) => {
2196                 let kind_str = match mutability {
2197                     Mutability::Mut => "mut",
2198                     Mutability::Not => "const",
2199                 };
2200
2201                 write!(fmt, "&raw {} {:?}", kind_str, place)
2202             }
2203
2204             Aggregate(ref kind, ref places) => {
2205                 let fmt_tuple = |fmt: &mut Formatter<'_>, name: &str| {
2206                     let mut tuple_fmt = fmt.debug_tuple(name);
2207                     for place in places {
2208                         tuple_fmt.field(place);
2209                     }
2210                     tuple_fmt.finish()
2211                 };
2212
2213                 match **kind {
2214                     AggregateKind::Array(_) => write!(fmt, "{:?}", places),
2215
2216                     AggregateKind::Tuple => {
2217                         if places.is_empty() {
2218                             write!(fmt, "()")
2219                         } else {
2220                             fmt_tuple(fmt, "")
2221                         }
2222                     }
2223
2224                     AggregateKind::Adt(adt_def, variant, substs, _user_ty, _) => {
2225                         let variant_def = &adt_def.variants[variant];
2226
2227                         let name = ty::tls::with(|tcx| {
2228                             let mut name = String::new();
2229                             let substs = tcx.lift(&substs).expect("could not lift for printing");
2230                             FmtPrinter::new(tcx, &mut name, Namespace::ValueNS)
2231                                 .print_def_path(variant_def.def_id, substs)?;
2232                             Ok(name)
2233                         })?;
2234
2235                         match variant_def.ctor_kind {
2236                             CtorKind::Const => fmt.write_str(&name),
2237                             CtorKind::Fn => fmt_tuple(fmt, &name),
2238                             CtorKind::Fictive => {
2239                                 let mut struct_fmt = fmt.debug_struct(&name);
2240                                 for (field, place) in variant_def.fields.iter().zip(places) {
2241                                     struct_fmt.field(&field.ident.as_str(), place);
2242                                 }
2243                                 struct_fmt.finish()
2244                             }
2245                         }
2246                     }
2247
2248                     AggregateKind::Closure(def_id, substs) => ty::tls::with(|tcx| {
2249                         if let Some(def_id) = def_id.as_local() {
2250                             let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
2251                             let name = if tcx.sess.opts.debugging_opts.span_free_formats {
2252                                 let substs = tcx.lift(&substs).unwrap();
2253                                 format!(
2254                                     "[closure@{}]",
2255                                     tcx.def_path_str_with_substs(def_id.to_def_id(), substs),
2256                                 )
2257                             } else {
2258                                 let span = tcx.hir().span(hir_id);
2259                                 format!("[closure@{}]", tcx.sess.source_map().span_to_string(span))
2260                             };
2261                             let mut struct_fmt = fmt.debug_struct(&name);
2262
2263                             if let Some(upvars) = tcx.upvars_mentioned(def_id) {
2264                                 for (&var_id, place) in upvars.keys().zip(places) {
2265                                     let var_name = tcx.hir().name(var_id);
2266                                     struct_fmt.field(&var_name.as_str(), place);
2267                                 }
2268                             }
2269
2270                             struct_fmt.finish()
2271                         } else {
2272                             write!(fmt, "[closure]")
2273                         }
2274                     }),
2275
2276                     AggregateKind::Generator(def_id, _, _) => ty::tls::with(|tcx| {
2277                         if let Some(def_id) = def_id.as_local() {
2278                             let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
2279                             let name = format!("[generator@{:?}]", tcx.hir().span(hir_id));
2280                             let mut struct_fmt = fmt.debug_struct(&name);
2281
2282                             if let Some(upvars) = tcx.upvars_mentioned(def_id) {
2283                                 for (&var_id, place) in upvars.keys().zip(places) {
2284                                     let var_name = tcx.hir().name(var_id);
2285                                     struct_fmt.field(&var_name.as_str(), place);
2286                                 }
2287                             }
2288
2289                             struct_fmt.finish()
2290                         } else {
2291                             write!(fmt, "[generator]")
2292                         }
2293                     }),
2294                 }
2295             }
2296         }
2297     }
2298 }
2299
2300 ///////////////////////////////////////////////////////////////////////////
2301 /// Constants
2302 ///
2303 /// Two constants are equal if they are the same constant. Note that
2304 /// this does not necessarily mean that they are "==" in Rust -- in
2305 /// particular one must be wary of `NaN`!
2306
2307 #[derive(Clone, Copy, PartialEq, TyEncodable, TyDecodable, HashStable)]
2308 pub struct Constant<'tcx> {
2309     pub span: Span,
2310
2311     /// Optional user-given type: for something like
2312     /// `collect::<Vec<_>>`, this would be present and would
2313     /// indicate that `Vec<_>` was explicitly specified.
2314     ///
2315     /// Needed for NLL to impose user-given type constraints.
2316     pub user_ty: Option<UserTypeAnnotationIndex>,
2317
2318     pub literal: &'tcx ty::Const<'tcx>,
2319 }
2320
2321 impl Constant<'tcx> {
2322     pub fn check_static_ptr(&self, tcx: TyCtxt<'_>) -> Option<DefId> {
2323         match self.literal.val.try_to_scalar() {
2324             Some(Scalar::Ptr(ptr)) => match tcx.global_alloc(ptr.alloc_id) {
2325                 GlobalAlloc::Static(def_id) => {
2326                     assert!(!tcx.is_thread_local_static(def_id));
2327                     Some(def_id)
2328                 }
2329                 _ => None,
2330             },
2331             _ => None,
2332         }
2333     }
2334 }
2335
2336 /// A collection of projections into user types.
2337 ///
2338 /// They are projections because a binding can occur a part of a
2339 /// parent pattern that has been ascribed a type.
2340 ///
2341 /// Its a collection because there can be multiple type ascriptions on
2342 /// the path from the root of the pattern down to the binding itself.
2343 ///
2344 /// An example:
2345 ///
2346 /// ```rust
2347 /// struct S<'a>((i32, &'a str), String);
2348 /// let S((_, w): (i32, &'static str), _): S = ...;
2349 /// //    ------  ^^^^^^^^^^^^^^^^^^^ (1)
2350 /// //  ---------------------------------  ^ (2)
2351 /// ```
2352 ///
2353 /// The highlights labelled `(1)` show the subpattern `(_, w)` being
2354 /// ascribed the type `(i32, &'static str)`.
2355 ///
2356 /// The highlights labelled `(2)` show the whole pattern being
2357 /// ascribed the type `S`.
2358 ///
2359 /// In this example, when we descend to `w`, we will have built up the
2360 /// following two projected types:
2361 ///
2362 ///   * base: `S`,                   projection: `(base.0).1`
2363 ///   * base: `(i32, &'static str)`, projection: `base.1`
2364 ///
2365 /// The first will lead to the constraint `w: &'1 str` (for some
2366 /// inferred region `'1`). The second will lead to the constraint `w:
2367 /// &'static str`.
2368 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
2369 pub struct UserTypeProjections {
2370     pub contents: Vec<(UserTypeProjection, Span)>,
2371 }
2372
2373 impl<'tcx> UserTypeProjections {
2374     pub fn none() -> Self {
2375         UserTypeProjections { contents: vec![] }
2376     }
2377
2378     pub fn is_empty(&self) -> bool {
2379         self.contents.is_empty()
2380     }
2381
2382     pub fn from_projections(projs: impl Iterator<Item = (UserTypeProjection, Span)>) -> Self {
2383         UserTypeProjections { contents: projs.collect() }
2384     }
2385
2386     pub fn projections_and_spans(
2387         &self,
2388     ) -> impl Iterator<Item = &(UserTypeProjection, Span)> + ExactSizeIterator {
2389         self.contents.iter()
2390     }
2391
2392     pub fn projections(&self) -> impl Iterator<Item = &UserTypeProjection> + ExactSizeIterator {
2393         self.contents.iter().map(|&(ref user_type, _span)| user_type)
2394     }
2395
2396     pub fn push_projection(mut self, user_ty: &UserTypeProjection, span: Span) -> Self {
2397         self.contents.push((user_ty.clone(), span));
2398         self
2399     }
2400
2401     fn map_projections(
2402         mut self,
2403         mut f: impl FnMut(UserTypeProjection) -> UserTypeProjection,
2404     ) -> Self {
2405         self.contents = self.contents.drain(..).map(|(proj, span)| (f(proj), span)).collect();
2406         self
2407     }
2408
2409     pub fn index(self) -> Self {
2410         self.map_projections(|pat_ty_proj| pat_ty_proj.index())
2411     }
2412
2413     pub fn subslice(self, from: u64, to: u64) -> Self {
2414         self.map_projections(|pat_ty_proj| pat_ty_proj.subslice(from, to))
2415     }
2416
2417     pub fn deref(self) -> Self {
2418         self.map_projections(|pat_ty_proj| pat_ty_proj.deref())
2419     }
2420
2421     pub fn leaf(self, field: Field) -> Self {
2422         self.map_projections(|pat_ty_proj| pat_ty_proj.leaf(field))
2423     }
2424
2425     pub fn variant(self, adt_def: &'tcx AdtDef, variant_index: VariantIdx, field: Field) -> Self {
2426         self.map_projections(|pat_ty_proj| pat_ty_proj.variant(adt_def, variant_index, field))
2427     }
2428 }
2429
2430 /// Encodes the effect of a user-supplied type annotation on the
2431 /// subcomponents of a pattern. The effect is determined by applying the
2432 /// given list of proejctions to some underlying base type. Often,
2433 /// the projection element list `projs` is empty, in which case this
2434 /// directly encodes a type in `base`. But in the case of complex patterns with
2435 /// subpatterns and bindings, we want to apply only a *part* of the type to a variable,
2436 /// in which case the `projs` vector is used.
2437 ///
2438 /// Examples:
2439 ///
2440 /// * `let x: T = ...` -- here, the `projs` vector is empty.
2441 ///
2442 /// * `let (x, _): T = ...` -- here, the `projs` vector would contain
2443 ///   `field[0]` (aka `.0`), indicating that the type of `s` is
2444 ///   determined by finding the type of the `.0` field from `T`.
2445 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, PartialEq)]
2446 pub struct UserTypeProjection {
2447     pub base: UserTypeAnnotationIndex,
2448     pub projs: Vec<ProjectionKind>,
2449 }
2450
2451 impl Copy for ProjectionKind {}
2452
2453 impl UserTypeProjection {
2454     pub(crate) fn index(mut self) -> Self {
2455         self.projs.push(ProjectionElem::Index(()));
2456         self
2457     }
2458
2459     pub(crate) fn subslice(mut self, from: u64, to: u64) -> Self {
2460         self.projs.push(ProjectionElem::Subslice { from, to, from_end: true });
2461         self
2462     }
2463
2464     pub(crate) fn deref(mut self) -> Self {
2465         self.projs.push(ProjectionElem::Deref);
2466         self
2467     }
2468
2469     pub(crate) fn leaf(mut self, field: Field) -> Self {
2470         self.projs.push(ProjectionElem::Field(field, ()));
2471         self
2472     }
2473
2474     pub(crate) fn variant(
2475         mut self,
2476         adt_def: &AdtDef,
2477         variant_index: VariantIdx,
2478         field: Field,
2479     ) -> Self {
2480         self.projs.push(ProjectionElem::Downcast(
2481             Some(adt_def.variants[variant_index].ident.name),
2482             variant_index,
2483         ));
2484         self.projs.push(ProjectionElem::Field(field, ()));
2485         self
2486     }
2487 }
2488
2489 CloneTypeFoldableAndLiftImpls! { ProjectionKind, }
2490
2491 impl<'tcx> TypeFoldable<'tcx> for UserTypeProjection {
2492     fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
2493         use crate::mir::ProjectionElem::*;
2494
2495         let base = self.base.fold_with(folder);
2496         let projs: Vec<_> = self
2497             .projs
2498             .iter()
2499             .map(|&elem| match elem {
2500                 Deref => Deref,
2501                 Field(f, ()) => Field(f, ()),
2502                 Index(()) => Index(()),
2503                 Downcast(symbol, variantidx) => Downcast(symbol, variantidx),
2504                 ConstantIndex { offset, min_length, from_end } => {
2505                     ConstantIndex { offset, min_length, from_end }
2506                 }
2507                 Subslice { from, to, from_end } => Subslice { from, to, from_end },
2508             })
2509             .collect();
2510
2511         UserTypeProjection { base, projs }
2512     }
2513
2514     fn super_visit_with<Vs: TypeVisitor<'tcx>>(&self, visitor: &mut Vs) -> bool {
2515         self.base.visit_with(visitor)
2516         // Note: there's nothing in `self.proj` to visit.
2517     }
2518 }
2519
2520 rustc_index::newtype_index! {
2521     pub struct Promoted {
2522         derive [HashStable]
2523         DEBUG_FORMAT = "promoted[{}]"
2524     }
2525 }
2526
2527 impl<'tcx> Debug for Constant<'tcx> {
2528     fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2529         write!(fmt, "{}", self)
2530     }
2531 }
2532
2533 impl<'tcx> Display for Constant<'tcx> {
2534     fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2535         match self.literal.ty.kind() {
2536             ty::FnDef(..) => {}
2537             _ => write!(fmt, "const ")?,
2538         }
2539         pretty_print_const(self.literal, fmt, true)
2540     }
2541 }
2542
2543 fn pretty_print_const(
2544     c: &ty::Const<'tcx>,
2545     fmt: &mut Formatter<'_>,
2546     print_types: bool,
2547 ) -> fmt::Result {
2548     use crate::ty::print::PrettyPrinter;
2549     ty::tls::with(|tcx| {
2550         let literal = tcx.lift(&c).unwrap();
2551         let mut cx = FmtPrinter::new(tcx, fmt, Namespace::ValueNS);
2552         cx.print_alloc_ids = true;
2553         cx.pretty_print_const(literal, print_types)?;
2554         Ok(())
2555     })
2556 }
2557
2558 impl<'tcx> graph::DirectedGraph for Body<'tcx> {
2559     type Node = BasicBlock;
2560 }
2561
2562 impl<'tcx> graph::WithNumNodes for Body<'tcx> {
2563     #[inline]
2564     fn num_nodes(&self) -> usize {
2565         self.basic_blocks.len()
2566     }
2567 }
2568
2569 impl<'tcx> graph::WithStartNode for Body<'tcx> {
2570     #[inline]
2571     fn start_node(&self) -> Self::Node {
2572         START_BLOCK
2573     }
2574 }
2575
2576 impl<'tcx> graph::WithSuccessors for Body<'tcx> {
2577     #[inline]
2578     fn successors(&self, node: Self::Node) -> <Self as GraphSuccessors<'_>>::Iter {
2579         self.basic_blocks[node].terminator().successors().cloned()
2580     }
2581 }
2582
2583 impl<'a, 'b> graph::GraphSuccessors<'b> for Body<'a> {
2584     type Item = BasicBlock;
2585     type Iter = iter::Cloned<Successors<'b>>;
2586 }
2587
2588 impl graph::GraphPredecessors<'graph> for Body<'tcx> {
2589     type Item = BasicBlock;
2590     type Iter = smallvec::IntoIter<[BasicBlock; 4]>;
2591 }
2592
2593 impl graph::WithPredecessors for Body<'tcx> {
2594     #[inline]
2595     fn predecessors(&self, node: Self::Node) -> <Self as graph::GraphPredecessors<'_>>::Iter {
2596         self.predecessors()[node].clone().into_iter()
2597     }
2598 }
2599
2600 /// `Location` represents the position of the start of the statement; or, if
2601 /// `statement_index` equals the number of statements, then the start of the
2602 /// terminator.
2603 #[derive(Copy, Clone, PartialEq, Eq, Hash, Ord, PartialOrd, HashStable)]
2604 pub struct Location {
2605     /// The block that the location is within.
2606     pub block: BasicBlock,
2607
2608     pub statement_index: usize,
2609 }
2610
2611 impl fmt::Debug for Location {
2612     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2613         write!(fmt, "{:?}[{}]", self.block, self.statement_index)
2614     }
2615 }
2616
2617 impl Location {
2618     pub const START: Location = Location { block: START_BLOCK, statement_index: 0 };
2619
2620     /// Returns the location immediately after this one within the enclosing block.
2621     ///
2622     /// Note that if this location represents a terminator, then the
2623     /// resulting location would be out of bounds and invalid.
2624     pub fn successor_within_block(&self) -> Location {
2625         Location { block: self.block, statement_index: self.statement_index + 1 }
2626     }
2627
2628     /// Returns `true` if `other` is earlier in the control flow graph than `self`.
2629     pub fn is_predecessor_of<'tcx>(&self, other: Location, body: &Body<'tcx>) -> bool {
2630         // If we are in the same block as the other location and are an earlier statement
2631         // then we are a predecessor of `other`.
2632         if self.block == other.block && self.statement_index < other.statement_index {
2633             return true;
2634         }
2635
2636         let predecessors = body.predecessors();
2637
2638         // If we're in another block, then we want to check that block is a predecessor of `other`.
2639         let mut queue: Vec<BasicBlock> = predecessors[other.block].to_vec();
2640         let mut visited = FxHashSet::default();
2641
2642         while let Some(block) = queue.pop() {
2643             // If we haven't visited this block before, then make sure we visit it's predecessors.
2644             if visited.insert(block) {
2645                 queue.extend(predecessors[block].iter().cloned());
2646             } else {
2647                 continue;
2648             }
2649
2650             // If we found the block that `self` is in, then we are a predecessor of `other` (since
2651             // we found that block by looking at the predecessors of `other`).
2652             if self.block == block {
2653                 return true;
2654             }
2655         }
2656
2657         false
2658     }
2659
2660     pub fn dominates(&self, other: Location, dominators: &Dominators<BasicBlock>) -> bool {
2661         if self.block == other.block {
2662             self.statement_index <= other.statement_index
2663         } else {
2664             dominators.is_dominated_by(other.block, self.block)
2665         }
2666     }
2667 }