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