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