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