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