1 // ignore-tidy-filelength
3 //! MIR datatypes and passes. See the [rustc guide] for more info.
5 //! [rustc guide]: https://rust-lang.github.io/rustc-guide/mir/index.html
7 use crate::hir::def::{CtorKind, Namespace};
8 use crate::hir::def_id::DefId;
9 use crate::hir::{self, InlineAsm as HirInlineAsm};
10 use crate::mir::interpret::{ConstValue, PanicInfo, Scalar};
11 use crate::mir::visit::MirVisitable;
12 use crate::ty::adjustment::PointerCast;
13 use crate::ty::fold::{TypeFoldable, TypeFolder, TypeVisitor};
14 use crate::ty::layout::VariantIdx;
15 use crate::ty::print::{FmtPrinter, Printer};
16 use crate::ty::subst::{Subst, SubstsRef};
18 self, AdtDef, CanonicalUserTypeAnnotations, ClosureSubsts, GeneratorSubsts, Region, Ty, TyCtxt,
19 UserTypeAnnotationIndex,
21 use polonius_engine::Atom;
22 use rustc_data_structures::bit_set::BitMatrix;
23 use rustc_data_structures::fx::FxHashSet;
24 use rustc_data_structures::graph::dominators::{dominators, Dominators};
25 use rustc_data_structures::graph::{self, GraphPredecessors, GraphSuccessors};
26 use rustc_data_structures::indexed_vec::{Idx, IndexVec};
27 use rustc_data_structures::sync::Lrc;
28 use rustc_data_structures::sync::MappedReadGuard;
29 use rustc_macros::HashStable;
30 use rustc_serialize::{Encodable, Decodable};
31 use smallvec::SmallVec;
33 use std::fmt::{self, Debug, Display, Formatter, Write};
34 use std::iter::FusedIterator;
35 use std::ops::{Index, IndexMut};
37 use std::vec::IntoIter;
38 use std::{iter, mem, option, u32};
39 use syntax::ast::Name;
40 use syntax::symbol::{InternedString, Symbol};
41 use syntax_pos::{Span, DUMMY_SP};
43 pub use crate::mir::interpret::AssertMessage;
53 type LocalDecls<'tcx> = IndexVec<Local, LocalDecl<'tcx>>;
55 pub trait HasLocalDecls<'tcx> {
56 fn local_decls(&self) -> &LocalDecls<'tcx>;
59 impl<'tcx> HasLocalDecls<'tcx> for LocalDecls<'tcx> {
60 fn local_decls(&self) -> &LocalDecls<'tcx> {
65 impl<'tcx> HasLocalDecls<'tcx> for Body<'tcx> {
66 fn local_decls(&self) -> &LocalDecls<'tcx> {
71 /// The various "big phases" that MIR goes through.
73 /// Warning: ordering of variants is significant
74 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, PartialEq, Eq, PartialOrd, Ord)]
83 /// Gets the index of the current MirPhase within the set of all MirPhases.
84 pub fn phase_index(&self) -> usize {
89 /// Lowered representation of a single function.
90 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
91 pub struct Body<'tcx> {
92 /// List of basic blocks. References to basic block use a newtyped index type `BasicBlock`
93 /// that indexes into this vector.
94 basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
96 /// Records how far through the "desugaring and optimization" process this particular
97 /// MIR has traversed. This is particularly useful when inlining, since in that context
98 /// we instantiate the promoted constants and add them to our promoted vector -- but those
99 /// promoted items have already been optimized, whereas ours have not. This field allows
100 /// us to see the difference and forego optimization on the inlined promoted items.
103 /// List of source scopes; these are referenced by statements
104 /// and used for debuginfo. Indexed by a `SourceScope`.
105 pub source_scopes: IndexVec<SourceScope, SourceScopeData>,
107 /// Crate-local information for each source scope, that can't (and
108 /// needn't) be tracked across crates.
109 pub source_scope_local_data: ClearCrossCrate<IndexVec<SourceScope, SourceScopeLocalData>>,
111 /// Yields type of the function, if it is a generator.
112 pub yield_ty: Option<Ty<'tcx>>,
114 /// Generator drop glue
115 pub generator_drop: Option<Box<Body<'tcx>>>,
117 /// The layout of a generator. Produced by the state transformation.
118 pub generator_layout: Option<GeneratorLayout<'tcx>>,
120 /// Declarations of locals.
122 /// The first local is the return value pointer, followed by `arg_count`
123 /// locals for the function arguments, followed by any user-declared
124 /// variables and temporaries.
125 pub local_decls: LocalDecls<'tcx>,
127 /// User type annotations
128 pub user_type_annotations: CanonicalUserTypeAnnotations<'tcx>,
130 /// Number of arguments this function takes.
132 /// Starting at local 1, `arg_count` locals will be provided by the caller
133 /// and can be assumed to be initialized.
135 /// If this MIR was built for a constant, this will be 0.
136 pub arg_count: usize,
138 /// Mark an argument local (which must be a tuple) as getting passed as
139 /// its individual components at the LLVM level.
141 /// This is used for the "rust-call" ABI.
142 pub spread_arg: Option<Local>,
144 /// Names and capture modes of all the closure upvars, assuming
145 /// the first argument is either the closure or a reference to it.
146 // NOTE(eddyb) This is *strictly* a temporary hack for codegen
147 // debuginfo generation, and will be removed at some point.
148 // Do **NOT** use it for anything else, upvar information should not be
149 // in the MIR, please rely on local crate HIR or other side-channels.
150 pub __upvar_debuginfo_codegen_only_do_not_use: Vec<UpvarDebuginfo>,
152 /// Mark this MIR of a const context other than const functions as having converted a `&&` or
153 /// `||` expression into `&` or `|` respectively. This is problematic because if we ever stop
154 /// this conversion from happening and use short circuiting, we will cause the following code
155 /// to change the value of `x`: `let mut x = 42; false && { x = 55; true };`
157 /// List of places where control flow was destroyed. Used for error reporting.
158 pub control_flow_destroyed: Vec<(Span, String)>,
160 /// A span representing this MIR, for error reporting
163 /// A cache for various calculations
167 impl<'tcx> Body<'tcx> {
169 basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
170 source_scopes: IndexVec<SourceScope, SourceScopeData>,
171 source_scope_local_data: ClearCrossCrate<IndexVec<SourceScope, SourceScopeLocalData>>,
172 yield_ty: Option<Ty<'tcx>>,
173 local_decls: LocalDecls<'tcx>,
174 user_type_annotations: CanonicalUserTypeAnnotations<'tcx>,
176 __upvar_debuginfo_codegen_only_do_not_use: Vec<UpvarDebuginfo>,
178 control_flow_destroyed: Vec<(Span, String)>,
180 // We need `arg_count` locals, and one for the return place
182 local_decls.len() >= arg_count + 1,
183 "expected at least {} locals, got {}",
189 phase: MirPhase::Build,
192 source_scope_local_data,
194 generator_drop: None,
195 generator_layout: None,
197 user_type_annotations,
199 __upvar_debuginfo_codegen_only_do_not_use,
202 cache: cache::Cache::new(),
203 control_flow_destroyed,
208 pub fn basic_blocks(&self) -> &IndexVec<BasicBlock, BasicBlockData<'tcx>> {
213 pub fn basic_blocks_mut(&mut self) -> &mut IndexVec<BasicBlock, BasicBlockData<'tcx>> {
214 self.cache.invalidate();
215 &mut self.basic_blocks
219 pub fn basic_blocks_and_local_decls_mut(
221 ) -> (&mut IndexVec<BasicBlock, BasicBlockData<'tcx>>, &mut LocalDecls<'tcx>) {
222 self.cache.invalidate();
223 (&mut self.basic_blocks, &mut self.local_decls)
227 pub fn predecessors(&self) -> MappedReadGuard<'_, IndexVec<BasicBlock, Vec<BasicBlock>>> {
228 self.cache.predecessors(self)
232 pub fn predecessors_for(&self, bb: BasicBlock) -> MappedReadGuard<'_, Vec<BasicBlock>> {
233 MappedReadGuard::map(self.predecessors(), |p| &p[bb])
237 pub fn predecessor_locations(&self, loc: Location) -> impl Iterator<Item = Location> + '_ {
238 let if_zero_locations = if loc.statement_index == 0 {
239 let predecessor_blocks = self.predecessors_for(loc.block);
240 let num_predecessor_blocks = predecessor_blocks.len();
242 (0..num_predecessor_blocks)
243 .map(move |i| predecessor_blocks[i])
244 .map(move |bb| self.terminator_loc(bb)),
250 let if_not_zero_locations = if loc.statement_index == 0 {
253 Some(Location { block: loc.block, statement_index: loc.statement_index - 1 })
256 if_zero_locations.into_iter().flatten().chain(if_not_zero_locations)
260 pub fn dominators(&self) -> Dominators<BasicBlock> {
265 pub fn local_kind(&self, local: Local) -> LocalKind {
266 let index = local.as_usize();
269 self.local_decls[local].mutability == Mutability::Mut,
270 "return place should be mutable"
273 LocalKind::ReturnPointer
274 } else if index < self.arg_count + 1 {
276 } else if self.local_decls[local].name.is_some() {
283 /// Returns an iterator over all temporaries.
285 pub fn temps_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
286 (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
287 let local = Local::new(index);
288 if self.local_decls[local].is_user_variable.is_some() {
296 /// Returns an iterator over all user-declared locals.
298 pub fn vars_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
299 (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
300 let local = Local::new(index);
301 if self.local_decls[local].is_user_variable.is_some() {
309 /// Returns an iterator over all user-declared mutable locals.
311 pub fn mut_vars_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
312 (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
313 let local = Local::new(index);
314 let decl = &self.local_decls[local];
315 if decl.is_user_variable.is_some() && decl.mutability == Mutability::Mut {
323 /// Returns an iterator over all user-declared mutable arguments and locals.
325 pub fn mut_vars_and_args_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
326 (1..self.local_decls.len()).filter_map(move |index| {
327 let local = Local::new(index);
328 let decl = &self.local_decls[local];
329 if (decl.is_user_variable.is_some() || index < self.arg_count + 1)
330 && decl.mutability == Mutability::Mut
339 /// Returns an iterator over all function arguments.
341 pub fn args_iter(&self) -> impl Iterator<Item = Local> {
342 let arg_count = self.arg_count;
343 (1..=arg_count).map(Local::new)
346 /// Returns an iterator over all user-defined variables and compiler-generated temporaries (all
347 /// locals that are neither arguments nor the return place).
349 pub fn vars_and_temps_iter(&self) -> impl Iterator<Item = Local> {
350 let arg_count = self.arg_count;
351 let local_count = self.local_decls.len();
352 (arg_count + 1..local_count).map(Local::new)
355 /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
356 /// invalidating statement indices in `Location`s.
357 pub fn make_statement_nop(&mut self, location: Location) {
358 let block = &mut self[location.block];
359 debug_assert!(location.statement_index < block.statements.len());
360 block.statements[location.statement_index].make_nop()
363 /// Returns the source info associated with `location`.
364 pub fn source_info(&self, location: Location) -> &SourceInfo {
365 let block = &self[location.block];
366 let stmts = &block.statements;
367 let idx = location.statement_index;
368 if idx < stmts.len() {
369 &stmts[idx].source_info
371 assert_eq!(idx, stmts.len());
372 &block.terminator().source_info
376 /// Checks if `sub` is a sub scope of `sup`
377 pub fn is_sub_scope(&self, mut sub: SourceScope, sup: SourceScope) -> bool {
379 match self.source_scopes[sub].parent_scope {
380 None => return false,
387 /// Returns the return type, it always return first element from `local_decls` array
388 pub fn return_ty(&self) -> Ty<'tcx> {
389 self.local_decls[RETURN_PLACE].ty
392 /// Gets the location of the terminator for the given block
393 pub fn terminator_loc(&self, bb: BasicBlock) -> Location {
394 Location { block: bb, statement_index: self[bb].statements.len() }
398 #[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
401 /// Unsafe because of a PushUnsafeBlock
403 /// Unsafe because of an unsafe fn
405 /// Unsafe because of an `unsafe` block
406 ExplicitUnsafe(hir::HirId),
409 impl_stable_hash_for!(struct Body<'tcx> {
413 source_scope_local_data,
418 user_type_annotations,
420 __upvar_debuginfo_codegen_only_do_not_use,
422 control_flow_destroyed,
427 impl<'tcx> Index<BasicBlock> for Body<'tcx> {
428 type Output = BasicBlockData<'tcx>;
431 fn index(&self, index: BasicBlock) -> &BasicBlockData<'tcx> {
432 &self.basic_blocks()[index]
436 impl<'tcx> IndexMut<BasicBlock> for Body<'tcx> {
438 fn index_mut(&mut self, index: BasicBlock) -> &mut BasicBlockData<'tcx> {
439 &mut self.basic_blocks_mut()[index]
443 #[derive(Copy, Clone, Debug, HashStable)]
444 pub enum ClearCrossCrate<T> {
449 impl<T> ClearCrossCrate<T> {
450 pub fn assert_crate_local(self) -> T {
452 ClearCrossCrate::Clear => bug!("unwrapping cross-crate data"),
453 ClearCrossCrate::Set(v) => v,
458 impl<T: Encodable> rustc_serialize::UseSpecializedEncodable for ClearCrossCrate<T> {}
459 impl<T: Decodable> rustc_serialize::UseSpecializedDecodable for ClearCrossCrate<T> {}
461 /// Grouped information about the source code origin of a MIR entity.
462 /// Intended to be inspected by diagnostics and debuginfo.
463 /// Most passes can work with it as a whole, within a single function.
464 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, HashStable)]
465 pub struct SourceInfo {
466 /// Source span for the AST pertaining to this MIR entity.
469 /// The source scope, keeping track of which bindings can be
470 /// seen by debuginfo, active lint levels, `unsafe {...}`, etc.
471 pub scope: SourceScope,
474 ///////////////////////////////////////////////////////////////////////////
475 // Mutability and borrow kinds
477 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
478 pub enum Mutability {
483 impl From<Mutability> for hir::Mutability {
484 fn from(m: Mutability) -> Self {
486 Mutability::Mut => hir::MutMutable,
487 Mutability::Not => hir::MutImmutable,
493 Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, HashStable,
495 pub enum BorrowKind {
496 /// Data must be immutable and is aliasable.
499 /// The immediately borrowed place must be immutable, but projections from
500 /// it don't need to be. For example, a shallow borrow of `a.b` doesn't
501 /// conflict with a mutable borrow of `a.b.c`.
503 /// This is used when lowering matches: when matching on a place we want to
504 /// ensure that place have the same value from the start of the match until
505 /// an arm is selected. This prevents this code from compiling:
507 /// let mut x = &Some(0);
510 /// Some(_) if { x = &None; false } => (),
514 /// This can't be a shared borrow because mutably borrowing (*x as Some).0
515 /// should not prevent `if let None = x { ... }`, for example, because the
516 /// mutating `(*x as Some).0` can't affect the discriminant of `x`.
517 /// We can also report errors with this kind of borrow differently.
520 /// Data must be immutable but not aliasable. This kind of borrow
521 /// cannot currently be expressed by the user and is used only in
522 /// implicit closure bindings. It is needed when the closure is
523 /// borrowing or mutating a mutable referent, e.g.:
525 /// let x: &mut isize = ...;
526 /// let y = || *x += 5;
528 /// If we were to try to translate this closure into a more explicit
529 /// form, we'd encounter an error with the code as written:
531 /// struct Env { x: & &mut isize }
532 /// let x: &mut isize = ...;
533 /// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn
534 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
536 /// This is then illegal because you cannot mutate an `&mut` found
537 /// in an aliasable location. To solve, you'd have to translate with
538 /// an `&mut` borrow:
540 /// struct Env { x: & &mut isize }
541 /// let x: &mut isize = ...;
542 /// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
543 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
545 /// Now the assignment to `**env.x` is legal, but creating a
546 /// mutable pointer to `x` is not because `x` is not mutable. We
547 /// could fix this by declaring `x` as `let mut x`. This is ok in
548 /// user code, if awkward, but extra weird for closures, since the
549 /// borrow is hidden.
551 /// So we introduce a "unique imm" borrow -- the referent is
552 /// immutable, but not aliasable. This solves the problem. For
553 /// simplicity, we don't give users the way to express this
554 /// borrow, it's just used when translating closures.
557 /// Data is mutable and not aliasable.
559 /// `true` if this borrow arose from method-call auto-ref
560 /// (i.e., `adjustment::Adjust::Borrow`).
561 allow_two_phase_borrow: bool,
566 pub fn allows_two_phase_borrow(&self) -> bool {
568 BorrowKind::Shared | BorrowKind::Shallow | BorrowKind::Unique => false,
569 BorrowKind::Mut { allow_two_phase_borrow } => allow_two_phase_borrow,
574 ///////////////////////////////////////////////////////////////////////////
575 // Variables and temps
580 DEBUG_FORMAT = "_{}",
581 const RETURN_PLACE = 0,
585 impl Atom for Local {
586 fn index(self) -> usize {
591 /// Classifies locals into categories. See `Body::local_kind`.
592 #[derive(PartialEq, Eq, Debug, HashStable)]
594 /// User-declared variable binding
596 /// Compiler-introduced temporary
598 /// Function argument
600 /// Location of function's return value
604 #[derive(Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
605 pub struct VarBindingForm<'tcx> {
606 /// Is variable bound via `x`, `mut x`, `ref x`, or `ref mut x`?
607 pub binding_mode: ty::BindingMode,
608 /// If an explicit type was provided for this variable binding,
609 /// this holds the source Span of that type.
611 /// NOTE: if you want to change this to a `HirId`, be wary that
612 /// doing so breaks incremental compilation (as of this writing),
613 /// while a `Span` does not cause our tests to fail.
614 pub opt_ty_info: Option<Span>,
615 /// Place of the RHS of the =, or the subject of the `match` where this
616 /// variable is initialized. None in the case of `let PATTERN;`.
617 /// Some((None, ..)) in the case of and `let [mut] x = ...` because
618 /// (a) the right-hand side isn't evaluated as a place expression.
619 /// (b) it gives a way to separate this case from the remaining cases
621 pub opt_match_place: Option<(Option<Place<'tcx>>, Span)>,
622 /// Span of the pattern in which this variable was bound.
626 #[derive(Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
627 pub enum BindingForm<'tcx> {
628 /// This is a binding for a non-`self` binding, or a `self` that has an explicit type.
629 Var(VarBindingForm<'tcx>),
630 /// Binding for a `self`/`&self`/`&mut self` binding where the type is implicit.
631 ImplicitSelf(ImplicitSelfKind),
632 /// Reference used in a guard expression to ensure immutability.
636 /// Represents what type of implicit self a function has, if any.
637 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
638 pub enum ImplicitSelfKind {
639 /// Represents a `fn x(self);`.
641 /// Represents a `fn x(mut self);`.
643 /// Represents a `fn x(&self);`.
645 /// Represents a `fn x(&mut self);`.
647 /// Represents when a function does not have a self argument or
648 /// when a function has a `self: X` argument.
652 CloneTypeFoldableAndLiftImpls! { BindingForm<'tcx>, }
654 impl_stable_hash_for!(struct self::VarBindingForm<'tcx> {
661 impl_stable_hash_for!(enum self::ImplicitSelfKind {
669 impl_stable_hash_for!(enum self::MirPhase {
676 mod binding_form_impl {
677 use crate::ich::StableHashingContext;
678 use rustc_data_structures::stable_hasher::{HashStable, StableHasher, StableHasherResult};
680 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for super::BindingForm<'tcx> {
681 fn hash_stable<W: StableHasherResult>(
683 hcx: &mut StableHashingContext<'a>,
684 hasher: &mut StableHasher<W>,
686 use super::BindingForm::*;
687 ::std::mem::discriminant(self).hash_stable(hcx, hasher);
690 Var(binding) => binding.hash_stable(hcx, hasher),
691 ImplicitSelf(kind) => kind.hash_stable(hcx, hasher),
698 /// `BlockTailInfo` is attached to the `LocalDecl` for temporaries
699 /// created during evaluation of expressions in a block tail
700 /// expression; that is, a block like `{ STMT_1; STMT_2; EXPR }`.
702 /// It is used to improve diagnostics when such temporaries are
703 /// involved in borrow_check errors, e.g., explanations of where the
704 /// temporaries come from, when their destructors are run, and/or how
705 /// one might revise the code to satisfy the borrow checker's rules.
706 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
707 pub struct BlockTailInfo {
708 /// If `true`, then the value resulting from evaluating this tail
709 /// expression is ignored by the block's expression context.
711 /// Examples include `{ ...; tail };` and `let _ = { ...; tail };`
712 /// but not e.g., `let _x = { ...; tail };`
713 pub tail_result_is_ignored: bool,
716 impl_stable_hash_for!(struct BlockTailInfo { tail_result_is_ignored });
720 /// This can be a binding declared by the user, a temporary inserted by the compiler, a function
721 /// argument, or the return place.
722 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
723 pub struct LocalDecl<'tcx> {
724 /// `let mut x` vs `let x`.
726 /// Temporaries and the return place are always mutable.
727 pub mutability: Mutability,
729 /// Some(binding_mode) if this corresponds to a user-declared local variable.
731 /// This is solely used for local diagnostics when generating
732 /// warnings/errors when compiling the current crate, and
733 /// therefore it need not be visible across crates. pnkfelix
734 /// currently hypothesized we *need* to wrap this in a
735 /// `ClearCrossCrate` as long as it carries as `HirId`.
736 pub is_user_variable: Option<ClearCrossCrate<BindingForm<'tcx>>>,
738 /// `true` if this is an internal local.
740 /// These locals are not based on types in the source code and are only used
741 /// for a few desugarings at the moment.
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
749 /// Unsafety checking will also ignore dereferences of these locals,
750 /// so they can be used for raw pointers only used in a desugaring.
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
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 pub is_block_tail: Option<BlockTailInfo>,
763 /// Type of this local.
766 /// If the user manually ascribed a type to this variable,
767 /// e.g., via `let x: T`, then we carry that type here. The MIR
768 /// borrow checker needs this information since it can affect
769 /// region inference.
770 pub user_ty: UserTypeProjections,
772 /// Name of the local, used in debuginfo and pretty-printing.
774 /// Note that function arguments can also have this set to `Some(_)`
775 /// to generate better debuginfo.
776 pub name: Option<Name>,
778 /// The *syntactic* (i.e., not visibility) source scope the local is defined
779 /// in. If the local was defined in a let-statement, this
780 /// is *within* the let-statement, rather than outside
783 /// This is needed because the visibility source scope of locals within
784 /// a let-statement is weird.
786 /// The reason is that we want the local to be *within* the let-statement
787 /// for lint purposes, but we want the local to be *after* the let-statement
788 /// for names-in-scope purposes.
790 /// That's it, if we have a let-statement like the one in this
794 /// fn foo(x: &str) {
795 /// #[allow(unused_mut)]
796 /// let mut x: u32 = { // <- one unused mut
797 /// let mut y: u32 = x.parse().unwrap();
804 /// Then, from a lint point of view, the declaration of `x: u32`
805 /// (and `y: u32`) are within the `#[allow(unused_mut)]` scope - the
806 /// lint scopes are the same as the AST/HIR nesting.
808 /// However, from a name lookup point of view, the scopes look more like
809 /// as if the let-statements were `match` expressions:
812 /// fn foo(x: &str) {
814 /// match x.parse().unwrap() {
823 /// We care about the name-lookup scopes for debuginfo - if the
824 /// debuginfo instruction pointer is at the call to `x.parse()`, we
825 /// want `x` to refer to `x: &str`, but if it is at the call to
826 /// `drop(x)`, we want it to refer to `x: u32`.
828 /// To allow both uses to work, we need to have more than a single scope
829 /// for a local. We have the `source_info.scope` represent the
830 /// "syntactic" lint scope (with a variable being under its let
831 /// block) while the `visibility_scope` represents the "local variable"
832 /// scope (where the "rest" of a block is under all prior let-statements).
834 /// The end result looks like this:
838 /// │{ argument x: &str }
840 /// │ │{ #[allow(unused_mut)] } // this is actually split into 2 scopes
841 /// │ │ // in practice because I'm lazy.
843 /// │ │← x.source_info.scope
844 /// │ │← `x.parse().unwrap()`
846 /// │ │ │← y.source_info.scope
848 /// │ │ │{ let y: u32 }
850 /// │ │ │← y.visibility_scope
853 /// │ │{ let x: u32 }
854 /// │ │← x.visibility_scope
855 /// │ │← `drop(x)` // this accesses `x: u32`
857 pub source_info: SourceInfo,
859 /// Source scope within which the local is visible (for debuginfo)
860 /// (see `source_info` for more details).
861 pub visibility_scope: SourceScope,
864 impl<'tcx> LocalDecl<'tcx> {
865 /// Returns `true` only if local is a binding that can itself be
866 /// made mutable via the addition of the `mut` keyword, namely
867 /// something like the occurrences of `x` in:
868 /// - `fn foo(x: Type) { ... }`,
870 /// - or `match ... { C(x) => ... }`
871 pub fn can_be_made_mutable(&self) -> bool {
872 match self.is_user_variable {
873 Some(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
874 binding_mode: ty::BindingMode::BindByValue(_),
880 Some(ClearCrossCrate::Set(BindingForm::ImplicitSelf(ImplicitSelfKind::Imm))) => true,
886 /// Returns `true` if local is definitely not a `ref ident` or
887 /// `ref mut ident` binding. (Such bindings cannot be made into
888 /// mutable bindings, but the inverse does not necessarily hold).
889 pub fn is_nonref_binding(&self) -> bool {
890 match self.is_user_variable {
891 Some(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
892 binding_mode: ty::BindingMode::BindByValue(_),
898 Some(ClearCrossCrate::Set(BindingForm::ImplicitSelf(_))) => true,
904 /// Returns `true` if this is a reference to a variable bound in a `match`
905 /// expression that is used to access said variable for the guard of the
907 pub fn is_ref_for_guard(&self) -> bool {
908 match self.is_user_variable {
909 Some(ClearCrossCrate::Set(BindingForm::RefForGuard)) => true,
914 /// Returns `true` is the local is from a compiler desugaring, e.g.,
915 /// `__next` from a `for` loop.
917 pub fn from_compiler_desugaring(&self) -> bool {
918 self.source_info.span.desugaring_kind().is_some()
921 /// Creates a new `LocalDecl` for a temporary.
923 pub fn new_temp(ty: Ty<'tcx>, span: Span) -> Self {
924 Self::new_local(ty, Mutability::Mut, false, span)
927 /// Converts `self` into same `LocalDecl` except tagged as immutable.
929 pub fn immutable(mut self) -> Self {
930 self.mutability = Mutability::Not;
934 /// Converts `self` into same `LocalDecl` except tagged as internal temporary.
936 pub fn block_tail(mut self, info: BlockTailInfo) -> Self {
937 assert!(self.is_block_tail.is_none());
938 self.is_block_tail = Some(info);
942 /// Creates a new `LocalDecl` for a internal temporary.
944 pub fn new_internal(ty: Ty<'tcx>, span: Span) -> Self {
945 Self::new_local(ty, Mutability::Mut, true, span)
949 fn new_local(ty: Ty<'tcx>, mutability: Mutability, internal: bool, span: Span) -> Self {
953 user_ty: UserTypeProjections::none(),
955 source_info: SourceInfo { span, scope: OUTERMOST_SOURCE_SCOPE },
956 visibility_scope: OUTERMOST_SOURCE_SCOPE,
958 is_user_variable: None,
963 /// Builds a `LocalDecl` for the return place.
965 /// This must be inserted into the `local_decls` list as the first local.
967 pub fn new_return_place(return_ty: Ty<'_>, span: Span) -> LocalDecl<'_> {
969 mutability: Mutability::Mut,
971 user_ty: UserTypeProjections::none(),
972 source_info: SourceInfo { span, scope: OUTERMOST_SOURCE_SCOPE },
973 visibility_scope: OUTERMOST_SOURCE_SCOPE,
976 name: None, // FIXME maybe we do want some name here?
977 is_user_variable: None,
982 /// A closure capture, with its name and mode.
983 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
984 pub struct UpvarDebuginfo {
985 pub debug_name: Name,
987 /// If true, the capture is behind a reference.
991 ///////////////////////////////////////////////////////////////////////////
995 pub struct BasicBlock {
997 DEBUG_FORMAT = "bb{}",
998 const START_BLOCK = 0,
1003 pub fn start_location(self) -> Location {
1004 Location { block: self, statement_index: 0 }
1008 ///////////////////////////////////////////////////////////////////////////
1009 // BasicBlockData and Terminator
1011 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
1012 pub struct BasicBlockData<'tcx> {
1013 /// List of statements in this block.
1014 pub statements: Vec<Statement<'tcx>>,
1016 /// Terminator for this block.
1018 /// N.B., this should generally ONLY be `None` during construction.
1019 /// Therefore, you should generally access it via the
1020 /// `terminator()` or `terminator_mut()` methods. The only
1021 /// exception is that certain passes, such as `simplify_cfg`, swap
1022 /// out the terminator temporarily with `None` while they continue
1023 /// to recurse over the set of basic blocks.
1024 pub terminator: Option<Terminator<'tcx>>,
1026 /// If true, this block lies on an unwind path. This is used
1027 /// during codegen where distinct kinds of basic blocks may be
1028 /// generated (particularly for MSVC cleanup). Unwind blocks must
1029 /// only branch to other unwind blocks.
1030 pub is_cleanup: bool,
1033 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
1034 pub struct Terminator<'tcx> {
1035 pub source_info: SourceInfo,
1036 pub kind: TerminatorKind<'tcx>,
1039 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable)]
1040 pub enum TerminatorKind<'tcx> {
1041 /// block should have one successor in the graph; we jump there
1042 Goto { target: BasicBlock },
1044 /// operand evaluates to an integer; jump depending on its value
1045 /// to one of the targets, and otherwise fallback to `otherwise`
1047 /// discriminant value being tested
1048 discr: Operand<'tcx>,
1050 /// type of value being tested
1051 switch_ty: Ty<'tcx>,
1053 /// Possible values. The locations to branch to in each case
1054 /// are found in the corresponding indices from the `targets` vector.
1055 values: Cow<'tcx, [u128]>,
1057 /// Possible branch sites. The last element of this vector is used
1058 /// for the otherwise branch, so targets.len() == values.len() + 1
1060 // This invariant is quite non-obvious and also could be improved.
1061 // One way to make this invariant is to have something like this instead:
1063 // branches: Vec<(ConstInt, BasicBlock)>,
1064 // otherwise: Option<BasicBlock> // exhaustive if None
1066 // However we’ve decided to keep this as-is until we figure a case
1067 // where some other approach seems to be strictly better than other.
1068 targets: Vec<BasicBlock>,
1071 /// Indicates that the landing pad is finished and unwinding should
1072 /// continue. Emitted by build::scope::diverge_cleanup.
1075 /// Indicates that the landing pad is finished and that the process
1076 /// should abort. Used to prevent unwinding for foreign items.
1079 /// Indicates a normal return. The return place should have
1080 /// been filled in by now. This should occur at most once.
1083 /// Indicates a terminator that can never be reached.
1087 Drop { location: Place<'tcx>, target: BasicBlock, unwind: Option<BasicBlock> },
1089 /// Drop the Place and assign the new value over it. This ensures
1090 /// that the assignment to `P` occurs *even if* the destructor for
1091 /// place unwinds. Its semantics are best explained by the
1096 /// DropAndReplace(P <- V, goto BB1, unwind BB2)
1104 /// Drop(P, goto BB1, unwind BB2)
1107 /// // P is now uninitialized
1111 /// // P is now uninitialized -- its dtor panicked
1116 location: Place<'tcx>,
1117 value: Operand<'tcx>,
1119 unwind: Option<BasicBlock>,
1122 /// Block ends with a call of a converging function
1124 /// The function that’s being called
1125 func: Operand<'tcx>,
1126 /// Arguments the function is called with.
1127 /// These are owned by the callee, which is free to modify them.
1128 /// This allows the memory occupied by "by-value" arguments to be
1129 /// reused across function calls without duplicating the contents.
1130 args: Vec<Operand<'tcx>>,
1131 /// Destination for the return value. If some, the call is converging.
1132 destination: Option<(Place<'tcx>, BasicBlock)>,
1133 /// Cleanups to be done if the call unwinds.
1134 cleanup: Option<BasicBlock>,
1135 /// Whether this is from a call in HIR, rather than from an overloaded
1136 /// operator. True for overloaded function call.
1137 from_hir_call: bool,
1140 /// Jump to the target if the condition has the expected value,
1141 /// otherwise panic with a message and a cleanup target.
1143 cond: Operand<'tcx>,
1145 msg: AssertMessage<'tcx>,
1147 cleanup: Option<BasicBlock>,
1152 /// The value to return
1153 value: Operand<'tcx>,
1154 /// Where to resume to
1156 /// Cleanup to be done if the generator is dropped at this suspend point
1157 drop: Option<BasicBlock>,
1160 /// Indicates the end of the dropping of a generator
1163 /// A block where control flow only ever takes one real path, but borrowck
1164 /// needs to be more conservative.
1166 /// The target normal control flow will take
1167 real_target: BasicBlock,
1168 /// A block control flow could conceptually jump to, but won't in
1170 imaginary_target: BasicBlock,
1172 /// A terminator for blocks that only take one path in reality, but where we
1173 /// reserve the right to unwind in borrowck, even if it won't happen in practice.
1174 /// This can arise in infinite loops with no function calls for example.
1176 /// The target normal control flow will take
1177 real_target: BasicBlock,
1178 /// The imaginary cleanup block link. This particular path will never be taken
1179 /// in practice, but in order to avoid fragility we want to always
1180 /// consider it in borrowck. We don't want to accept programs which
1181 /// pass borrowck only when panic=abort or some assertions are disabled
1182 /// due to release vs. debug mode builds. This needs to be an Option because
1183 /// of the remove_noop_landing_pads and no_landing_pads passes
1184 unwind: Option<BasicBlock>,
1188 pub type Successors<'a> =
1189 iter::Chain<option::IntoIter<&'a BasicBlock>, slice::Iter<'a, BasicBlock>>;
1190 pub type SuccessorsMut<'a> =
1191 iter::Chain<option::IntoIter<&'a mut BasicBlock>, slice::IterMut<'a, BasicBlock>>;
1193 impl<'tcx> Terminator<'tcx> {
1194 pub fn successors(&self) -> Successors<'_> {
1195 self.kind.successors()
1198 pub fn successors_mut(&mut self) -> SuccessorsMut<'_> {
1199 self.kind.successors_mut()
1202 pub fn unwind(&self) -> Option<&Option<BasicBlock>> {
1206 pub fn unwind_mut(&mut self) -> Option<&mut Option<BasicBlock>> {
1207 self.kind.unwind_mut()
1211 impl<'tcx> TerminatorKind<'tcx> {
1214 cond: Operand<'tcx>,
1217 ) -> TerminatorKind<'tcx> {
1218 static BOOL_SWITCH_FALSE: &'static [u128] = &[0];
1219 TerminatorKind::SwitchInt {
1221 switch_ty: tcx.types.bool,
1222 values: From::from(BOOL_SWITCH_FALSE),
1223 targets: vec![f, t],
1227 pub fn successors(&self) -> Successors<'_> {
1228 use self::TerminatorKind::*;
1235 | Call { destination: None, cleanup: None, .. } => None.into_iter().chain(&[]),
1236 Goto { target: ref t }
1237 | Call { destination: None, cleanup: Some(ref t), .. }
1238 | Call { destination: Some((_, ref t)), cleanup: None, .. }
1239 | Yield { resume: ref t, drop: None, .. }
1240 | DropAndReplace { target: ref t, unwind: None, .. }
1241 | Drop { target: ref t, unwind: None, .. }
1242 | Assert { target: ref t, cleanup: None, .. }
1243 | FalseUnwind { real_target: ref t, unwind: None } => Some(t).into_iter().chain(&[]),
1244 Call { destination: Some((_, ref t)), cleanup: Some(ref u), .. }
1245 | Yield { resume: ref t, drop: Some(ref u), .. }
1246 | DropAndReplace { target: ref t, unwind: Some(ref u), .. }
1247 | Drop { target: ref t, unwind: Some(ref u), .. }
1248 | Assert { target: ref t, cleanup: Some(ref u), .. }
1249 | FalseUnwind { real_target: ref t, unwind: Some(ref u) } => {
1250 Some(t).into_iter().chain(slice::from_ref(u))
1252 SwitchInt { ref targets, .. } => None.into_iter().chain(&targets[..]),
1253 FalseEdges { ref real_target, ref imaginary_target } => {
1254 Some(real_target).into_iter().chain(slice::from_ref(imaginary_target))
1259 pub fn successors_mut(&mut self) -> SuccessorsMut<'_> {
1260 use self::TerminatorKind::*;
1267 | Call { destination: None, cleanup: None, .. } => None.into_iter().chain(&mut []),
1268 Goto { target: ref mut t }
1269 | Call { destination: None, cleanup: Some(ref mut t), .. }
1270 | Call { destination: Some((_, ref mut t)), cleanup: None, .. }
1271 | Yield { resume: ref mut t, drop: None, .. }
1272 | DropAndReplace { target: ref mut t, unwind: None, .. }
1273 | Drop { target: ref mut t, unwind: None, .. }
1274 | Assert { target: ref mut t, cleanup: None, .. }
1275 | FalseUnwind { real_target: ref mut t, unwind: None } => {
1276 Some(t).into_iter().chain(&mut [])
1278 Call { destination: Some((_, ref mut t)), cleanup: Some(ref mut u), .. }
1279 | Yield { resume: ref mut t, drop: Some(ref mut u), .. }
1280 | DropAndReplace { target: ref mut t, unwind: Some(ref mut u), .. }
1281 | Drop { target: ref mut t, unwind: Some(ref mut u), .. }
1282 | Assert { target: ref mut t, cleanup: Some(ref mut u), .. }
1283 | FalseUnwind { real_target: ref mut t, unwind: Some(ref mut u) } => {
1284 Some(t).into_iter().chain(slice::from_mut(u))
1286 SwitchInt { ref mut targets, .. } => None.into_iter().chain(&mut targets[..]),
1287 FalseEdges { ref mut real_target, ref mut imaginary_target } => {
1288 Some(real_target).into_iter().chain(slice::from_mut(imaginary_target))
1293 pub fn unwind(&self) -> Option<&Option<BasicBlock>> {
1295 TerminatorKind::Goto { .. }
1296 | TerminatorKind::Resume
1297 | TerminatorKind::Abort
1298 | TerminatorKind::Return
1299 | TerminatorKind::Unreachable
1300 | TerminatorKind::GeneratorDrop
1301 | TerminatorKind::Yield { .. }
1302 | TerminatorKind::SwitchInt { .. }
1303 | TerminatorKind::FalseEdges { .. } => None,
1304 TerminatorKind::Call { cleanup: ref unwind, .. }
1305 | TerminatorKind::Assert { cleanup: ref unwind, .. }
1306 | TerminatorKind::DropAndReplace { ref unwind, .. }
1307 | TerminatorKind::Drop { ref unwind, .. }
1308 | TerminatorKind::FalseUnwind { ref unwind, .. } => Some(unwind),
1312 pub fn unwind_mut(&mut self) -> Option<&mut Option<BasicBlock>> {
1314 TerminatorKind::Goto { .. }
1315 | TerminatorKind::Resume
1316 | TerminatorKind::Abort
1317 | TerminatorKind::Return
1318 | TerminatorKind::Unreachable
1319 | TerminatorKind::GeneratorDrop
1320 | TerminatorKind::Yield { .. }
1321 | TerminatorKind::SwitchInt { .. }
1322 | TerminatorKind::FalseEdges { .. } => None,
1323 TerminatorKind::Call { cleanup: ref mut unwind, .. }
1324 | TerminatorKind::Assert { cleanup: ref mut unwind, .. }
1325 | TerminatorKind::DropAndReplace { ref mut unwind, .. }
1326 | TerminatorKind::Drop { ref mut unwind, .. }
1327 | TerminatorKind::FalseUnwind { ref mut unwind, .. } => Some(unwind),
1332 impl<'tcx> BasicBlockData<'tcx> {
1333 pub fn new(terminator: Option<Terminator<'tcx>>) -> BasicBlockData<'tcx> {
1334 BasicBlockData { statements: vec![], terminator, is_cleanup: false }
1337 /// Accessor for terminator.
1339 /// Terminator may not be None after construction of the basic block is complete. This accessor
1340 /// provides a convenience way to reach the terminator.
1341 pub fn terminator(&self) -> &Terminator<'tcx> {
1342 self.terminator.as_ref().expect("invalid terminator state")
1345 pub fn terminator_mut(&mut self) -> &mut Terminator<'tcx> {
1346 self.terminator.as_mut().expect("invalid terminator state")
1349 pub fn retain_statements<F>(&mut self, mut f: F)
1351 F: FnMut(&mut Statement<'_>) -> bool,
1353 for s in &mut self.statements {
1360 pub fn expand_statements<F, I>(&mut self, mut f: F)
1362 F: FnMut(&mut Statement<'tcx>) -> Option<I>,
1363 I: iter::TrustedLen<Item = Statement<'tcx>>,
1365 // Gather all the iterators we'll need to splice in, and their positions.
1366 let mut splices: Vec<(usize, I)> = vec![];
1367 let mut extra_stmts = 0;
1368 for (i, s) in self.statements.iter_mut().enumerate() {
1369 if let Some(mut new_stmts) = f(s) {
1370 if let Some(first) = new_stmts.next() {
1371 // We can already store the first new statement.
1374 // Save the other statements for optimized splicing.
1375 let remaining = new_stmts.size_hint().0;
1377 splices.push((i + 1 + extra_stmts, new_stmts));
1378 extra_stmts += remaining;
1386 // Splice in the new statements, from the end of the block.
1387 // FIXME(eddyb) This could be more efficient with a "gap buffer"
1388 // where a range of elements ("gap") is left uninitialized, with
1389 // splicing adding new elements to the end of that gap and moving
1390 // existing elements from before the gap to the end of the gap.
1391 // For now, this is safe code, emulating a gap but initializing it.
1392 let mut gap = self.statements.len()..self.statements.len() + extra_stmts;
1393 self.statements.resize(
1396 source_info: SourceInfo { span: DUMMY_SP, scope: OUTERMOST_SOURCE_SCOPE },
1397 kind: StatementKind::Nop,
1400 for (splice_start, new_stmts) in splices.into_iter().rev() {
1401 let splice_end = splice_start + new_stmts.size_hint().0;
1402 while gap.end > splice_end {
1405 self.statements.swap(gap.start, gap.end);
1407 self.statements.splice(splice_start..splice_end, new_stmts);
1408 gap.end = splice_start;
1412 pub fn visitable(&self, index: usize) -> &dyn MirVisitable<'tcx> {
1413 if index < self.statements.len() {
1414 &self.statements[index]
1421 impl<'tcx> Debug for TerminatorKind<'tcx> {
1422 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1423 self.fmt_head(fmt)?;
1424 let successor_count = self.successors().count();
1425 let labels = self.fmt_successor_labels();
1426 assert_eq!(successor_count, labels.len());
1428 match successor_count {
1431 1 => write!(fmt, " -> {:?}", self.successors().nth(0).unwrap()),
1434 write!(fmt, " -> [")?;
1435 for (i, target) in self.successors().enumerate() {
1439 write!(fmt, "{}: {:?}", labels[i], target)?;
1447 impl<'tcx> TerminatorKind<'tcx> {
1448 /// Write the "head" part of the terminator; that is, its name and the data it uses to pick the
1449 /// successor basic block, if any. The only information not included is the list of possible
1450 /// successors, which may be rendered differently between the text and the graphviz format.
1451 pub fn fmt_head<W: Write>(&self, fmt: &mut W) -> fmt::Result {
1452 use self::TerminatorKind::*;
1454 Goto { .. } => write!(fmt, "goto"),
1455 SwitchInt { discr: ref place, .. } => write!(fmt, "switchInt({:?})", place),
1456 Return => write!(fmt, "return"),
1457 GeneratorDrop => write!(fmt, "generator_drop"),
1458 Resume => write!(fmt, "resume"),
1459 Abort => write!(fmt, "abort"),
1460 Yield { ref value, .. } => write!(fmt, "_1 = suspend({:?})", value),
1461 Unreachable => write!(fmt, "unreachable"),
1462 Drop { ref location, .. } => write!(fmt, "drop({:?})", location),
1463 DropAndReplace { ref location, ref value, .. } => {
1464 write!(fmt, "replace({:?} <- {:?})", location, value)
1466 Call { ref func, ref args, ref destination, .. } => {
1467 if let Some((ref destination, _)) = *destination {
1468 write!(fmt, "{:?} = ", destination)?;
1470 write!(fmt, "{:?}(", func)?;
1471 for (index, arg) in args.iter().enumerate() {
1475 write!(fmt, "{:?}", arg)?;
1479 Assert { ref cond, expected, ref msg, .. } => {
1480 write!(fmt, "assert(")?;
1484 write!(fmt, "{:?}, \"{:?}\")", cond, msg)
1486 FalseEdges { .. } => write!(fmt, "falseEdges"),
1487 FalseUnwind { .. } => write!(fmt, "falseUnwind"),
1491 /// Returns the list of labels for the edges to the successor basic blocks.
1492 pub fn fmt_successor_labels(&self) -> Vec<Cow<'static, str>> {
1493 use self::TerminatorKind::*;
1495 Return | Resume | Abort | Unreachable | GeneratorDrop => vec![],
1496 Goto { .. } => vec!["".into()],
1497 SwitchInt { ref values, switch_ty, .. } => ty::tls::with(|tcx| {
1498 let param_env = ty::ParamEnv::empty();
1499 let switch_ty = tcx.lift_to_global(&switch_ty).unwrap();
1500 let size = tcx.layout_of(param_env.and(switch_ty)).unwrap().size;
1504 tcx.mk_const(ty::Const {
1505 val: ConstValue::Scalar(Scalar::from_uint(u, size).into()),
1511 .chain(iter::once("otherwise".into()))
1514 Call { destination: Some(_), cleanup: Some(_), .. } => {
1515 vec!["return".into(), "unwind".into()]
1517 Call { destination: Some(_), cleanup: None, .. } => vec!["return".into()],
1518 Call { destination: None, cleanup: Some(_), .. } => vec!["unwind".into()],
1519 Call { destination: None, cleanup: None, .. } => vec![],
1520 Yield { drop: Some(_), .. } => vec!["resume".into(), "drop".into()],
1521 Yield { drop: None, .. } => vec!["resume".into()],
1522 DropAndReplace { unwind: None, .. } | Drop { unwind: None, .. } => {
1523 vec!["return".into()]
1525 DropAndReplace { unwind: Some(_), .. } | Drop { unwind: Some(_), .. } => {
1526 vec!["return".into(), "unwind".into()]
1528 Assert { cleanup: None, .. } => vec!["".into()],
1529 Assert { .. } => vec!["success".into(), "unwind".into()],
1530 FalseEdges { .. } => vec!["real".into(), "imaginary".into()],
1531 FalseUnwind { unwind: Some(_), .. } => vec!["real".into(), "cleanup".into()],
1532 FalseUnwind { unwind: None, .. } => vec!["real".into()],
1537 ///////////////////////////////////////////////////////////////////////////
1540 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable)]
1541 pub struct Statement<'tcx> {
1542 pub source_info: SourceInfo,
1543 pub kind: StatementKind<'tcx>,
1546 // `Statement` is used a lot. Make sure it doesn't unintentionally get bigger.
1547 #[cfg(target_arch = "x86_64")]
1548 static_assert_size!(Statement<'_>, 56);
1550 impl<'tcx> Statement<'tcx> {
1551 /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
1552 /// invalidating statement indices in `Location`s.
1553 pub fn make_nop(&mut self) {
1554 self.kind = StatementKind::Nop
1557 /// Changes a statement to a nop and returns the original statement.
1558 pub fn replace_nop(&mut self) -> Self {
1560 source_info: self.source_info,
1561 kind: mem::replace(&mut self.kind, StatementKind::Nop),
1566 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
1567 pub enum StatementKind<'tcx> {
1568 /// Write the RHS Rvalue to the LHS Place.
1569 Assign(Place<'tcx>, Box<Rvalue<'tcx>>),
1571 /// This represents all the reading that a pattern match may do
1572 /// (e.g., inspecting constants and discriminant values), and the
1573 /// kind of pattern it comes from. This is in order to adapt potential
1574 /// error messages to these specific patterns.
1576 /// Note that this also is emitted for regular `let` bindings to ensure that locals that are
1577 /// never accessed still get some sanity checks for, e.g., `let x: ! = ..;`
1578 FakeRead(FakeReadCause, Place<'tcx>),
1580 /// Write the discriminant for a variant to the enum Place.
1581 SetDiscriminant { place: Place<'tcx>, variant_index: VariantIdx },
1583 /// Start a live range for the storage of the local.
1586 /// End the current live range for the storage of the local.
1589 /// Executes a piece of inline Assembly. Stored in a Box to keep the size
1590 /// of `StatementKind` low.
1591 InlineAsm(Box<InlineAsm<'tcx>>),
1593 /// Retag references in the given place, ensuring they got fresh tags. This is
1594 /// part of the Stacked Borrows model. These statements are currently only interpreted
1595 /// by miri and only generated when "-Z mir-emit-retag" is passed.
1596 /// See <https://internals.rust-lang.org/t/stacked-borrows-an-aliasing-model-for-rust/8153/>
1597 /// for more details.
1598 Retag(RetagKind, Place<'tcx>),
1600 /// Encodes a user's type ascription. These need to be preserved
1601 /// intact so that NLL can respect them. For example:
1605 /// The effect of this annotation is to relate the type `T_y` of the place `y`
1606 /// to the user-given type `T`. The effect depends on the specified variance:
1608 /// - `Covariant` -- requires that `T_y <: T`
1609 /// - `Contravariant` -- requires that `T_y :> T`
1610 /// - `Invariant` -- requires that `T_y == T`
1611 /// - `Bivariant` -- no effect
1612 AscribeUserType(Place<'tcx>, ty::Variance, Box<UserTypeProjection>),
1614 /// No-op. Useful for deleting instructions without affecting statement indices.
1618 /// `RetagKind` describes what kind of retag is to be performed.
1619 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, PartialEq, Eq, HashStable)]
1620 pub enum RetagKind {
1621 /// The initial retag when entering a function
1623 /// Retag preparing for a two-phase borrow
1625 /// Retagging raw pointers
1627 /// A "normal" retag
1631 /// The `FakeReadCause` describes the type of pattern why a `FakeRead` statement exists.
1632 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1633 pub enum FakeReadCause {
1634 /// Inject a fake read of the borrowed input at the end of each guards
1637 /// This should ensure that you cannot change the variant for an enum while
1638 /// you are in the midst of matching on it.
1641 /// `let x: !; match x {}` doesn't generate any read of x so we need to
1642 /// generate a read of x to check that it is initialized and safe.
1645 /// A fake read of the RefWithinGuard version of a bind-by-value variable
1646 /// in a match guard to ensure that it's value hasn't change by the time
1647 /// we create the OutsideGuard version.
1650 /// Officially, the semantics of
1652 /// `let pattern = <expr>;`
1654 /// is that `<expr>` is evaluated into a temporary and then this temporary is
1655 /// into the pattern.
1657 /// However, if we see the simple pattern `let var = <expr>`, we optimize this to
1658 /// evaluate `<expr>` directly into the variable `var`. This is mostly unobservable,
1659 /// but in some cases it can affect the borrow checker, as in #53695.
1660 /// Therefore, we insert a "fake read" here to ensure that we get
1661 /// appropriate errors.
1665 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
1666 pub struct InlineAsm<'tcx> {
1667 pub asm: HirInlineAsm,
1668 pub outputs: Box<[Place<'tcx>]>,
1669 pub inputs: Box<[(Span, Operand<'tcx>)]>,
1672 impl<'tcx> Debug for Statement<'tcx> {
1673 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1674 use self::StatementKind::*;
1676 Assign(ref place, ref rv) => write!(fmt, "{:?} = {:?}", place, rv),
1677 FakeRead(ref cause, ref place) => write!(fmt, "FakeRead({:?}, {:?})", cause, place),
1678 Retag(ref kind, ref place) => write!(
1682 RetagKind::FnEntry => "[fn entry] ",
1683 RetagKind::TwoPhase => "[2phase] ",
1684 RetagKind::Raw => "[raw] ",
1685 RetagKind::Default => "",
1689 StorageLive(ref place) => write!(fmt, "StorageLive({:?})", place),
1690 StorageDead(ref place) => write!(fmt, "StorageDead({:?})", place),
1691 SetDiscriminant { ref place, variant_index } => {
1692 write!(fmt, "discriminant({:?}) = {:?}", place, variant_index)
1694 InlineAsm(ref asm) => {
1695 write!(fmt, "asm!({:?} : {:?} : {:?})", asm.asm, asm.outputs, asm.inputs)
1697 AscribeUserType(ref place, ref variance, ref c_ty) => {
1698 write!(fmt, "AscribeUserType({:?}, {:?}, {:?})", place, variance, c_ty)
1700 Nop => write!(fmt, "nop"),
1705 ///////////////////////////////////////////////////////////////////////////
1708 /// A path to a value; something that can be evaluated without
1709 /// changing or disturbing program state.
1711 Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, HashStable,
1713 pub struct Place<'tcx> {
1714 pub base: PlaceBase<'tcx>,
1716 /// projection out of a place (access a field, deref a pointer, etc)
1717 pub projection: Option<Box<Projection<'tcx>>>,
1721 Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, HashStable,
1723 pub enum PlaceBase<'tcx> {
1727 /// static or static mut variable
1728 Static(Box<Static<'tcx>>),
1731 /// We store the normalized type to avoid requiring normalization when reading MIR
1732 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
1733 pub struct Static<'tcx> {
1735 pub kind: StaticKind,
1739 Clone, PartialEq, Eq, PartialOrd, Ord, Hash, HashStable, RustcEncodable, RustcDecodable,
1741 pub enum StaticKind {
1746 impl_stable_hash_for!(struct Static<'tcx> {
1751 /// The `Projection` data structure defines things of the form `base.x`, `*b` or `b[index]`.
1753 Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, HashStable,
1755 pub struct Projection<'tcx> {
1756 pub base: Option<Box<Projection<'tcx>>>,
1757 pub elem: PlaceElem<'tcx>,
1761 Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, HashStable,
1763 pub enum ProjectionElem<V, T> {
1768 /// These indices are generated by slice patterns. Easiest to explain
1772 /// [X, _, .._, _, _] => { offset: 0, min_length: 4, from_end: false },
1773 /// [_, X, .._, _, _] => { offset: 1, min_length: 4, from_end: false },
1774 /// [_, _, .._, X, _] => { offset: 2, min_length: 4, from_end: true },
1775 /// [_, _, .._, _, X] => { offset: 1, min_length: 4, from_end: true },
1778 /// index or -index (in Python terms), depending on from_end
1780 /// thing being indexed must be at least this long
1782 /// counting backwards from end?
1786 /// These indices are generated by slice patterns.
1788 /// slice[from:-to] in Python terms.
1794 /// "Downcast" to a variant of an ADT. Currently, we only introduce
1795 /// this for ADTs with more than one variant. It may be better to
1796 /// just introduce it always, or always for enums.
1798 /// The included Symbol is the name of the variant, used for printing MIR.
1799 Downcast(Option<Symbol>, VariantIdx),
1802 /// Alias for projections as they appear in places, where the base is a place
1803 /// and the index is a local.
1804 pub type PlaceElem<'tcx> = ProjectionElem<Local, Ty<'tcx>>;
1806 // At least on 64 bit systems, `PlaceElem` should not be larger than two pointers.
1807 #[cfg(target_arch = "x86_64")]
1808 static_assert_size!(PlaceElem<'_>, 16);
1810 /// Alias for projections as they appear in `UserTypeProjection`, where we
1811 /// need neither the `V` parameter for `Index` nor the `T` for `Field`.
1812 pub type ProjectionKind = ProjectionElem<(), ()>;
1817 DEBUG_FORMAT = "field[{}]"
1821 #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
1822 pub struct PlaceRef<'a, 'tcx> {
1823 pub base: &'a PlaceBase<'tcx>,
1824 pub projection: &'a Option<Box<Projection<'tcx>>>,
1827 impl<'tcx> Place<'tcx> {
1828 pub const RETURN_PLACE: Place<'tcx> = Place {
1829 base: PlaceBase::Local(RETURN_PLACE),
1833 pub fn field(self, f: Field, ty: Ty<'tcx>) -> Place<'tcx> {
1834 self.elem(ProjectionElem::Field(f, ty))
1837 pub fn deref(self) -> Place<'tcx> {
1838 self.elem(ProjectionElem::Deref)
1841 pub fn downcast(self, adt_def: &'tcx AdtDef, variant_index: VariantIdx) -> Place<'tcx> {
1842 self.elem(ProjectionElem::Downcast(
1843 Some(adt_def.variants[variant_index].ident.name),
1848 pub fn downcast_unnamed(self, variant_index: VariantIdx) -> Place<'tcx> {
1849 self.elem(ProjectionElem::Downcast(None, variant_index))
1852 pub fn index(self, index: Local) -> Place<'tcx> {
1853 self.elem(ProjectionElem::Index(index))
1856 pub fn elem(self, elem: PlaceElem<'tcx>) -> Place<'tcx> {
1859 projection: Some(Box::new(Projection { base: self.projection, elem })),
1863 /// Finds the innermost `Local` from this `Place`, *if* it is either a local itself or
1864 /// a single deref of a local.
1866 // FIXME: can we safely swap the semantics of `fn base_local` below in here instead?
1867 pub fn local_or_deref_local(&self) -> Option<Local> {
1870 base: PlaceBase::Local(local),
1874 base: PlaceBase::Local(local),
1875 projection: Some(box Projection {
1877 elem: ProjectionElem::Deref,
1884 /// Recursively "iterates" over place components, generating a `PlaceBase` and
1885 /// `Projections` list and invoking `op` with a `ProjectionsIter`.
1888 op: impl FnOnce(&PlaceBase<'tcx>, ProjectionsIter<'_, 'tcx>) -> R,
1890 Place::iterate_over(&self.base, &self.projection, op)
1893 pub fn iterate_over<R>(
1894 place_base: &PlaceBase<'tcx>,
1895 place_projection: &Option<Box<Projection<'tcx>>>,
1896 op: impl FnOnce(&PlaceBase<'tcx>, ProjectionsIter<'_, 'tcx>) -> R,
1898 fn iterate_over2<'tcx, R>(
1899 place_base: &PlaceBase<'tcx>,
1900 place_projection: &Option<Box<Projection<'tcx>>>,
1901 next: &Projections<'_, 'tcx>,
1902 op: impl FnOnce(&PlaceBase<'tcx>, ProjectionsIter<'_, 'tcx>) -> R,
1904 match place_projection {
1906 op(place_base, next.iter())
1913 &Projections::List {
1914 projection: interior,
1923 iterate_over2(place_base, place_projection, &Projections::Empty, op)
1926 pub fn as_ref(&self) -> PlaceRef<'_, 'tcx> {
1929 projection: &self.projection,
1934 impl From<Local> for Place<'_> {
1935 fn from(local: Local) -> Self {
1943 impl From<Local> for PlaceBase<'_> {
1944 fn from(local: Local) -> Self {
1945 PlaceBase::Local(local)
1949 impl<'a, 'tcx> PlaceRef<'a, 'tcx> {
1952 op: impl FnOnce(&PlaceBase<'tcx>, ProjectionsIter<'_, 'tcx>) -> R,
1954 Place::iterate_over(self.base, self.projection, op)
1957 /// Finds the innermost `Local` from this `Place`, *if* it is either a local itself or
1958 /// a single deref of a local.
1960 // FIXME: can we safely swap the semantics of `fn base_local` below in here instead?
1961 pub fn local_or_deref_local(&self) -> Option<Local> {
1964 base: PlaceBase::Local(local),
1968 base: PlaceBase::Local(local),
1969 projection: Some(box Projection {
1971 elem: ProjectionElem::Deref,
1979 /// A linked list of projections running up the stack; begins with the
1980 /// innermost projection and extends to the outermost (e.g., `a.b.c`
1981 /// would have the place `b` with a "next" pointer to `b.c`).
1982 /// Created by `Place::iterate`.
1984 /// N.B., this particular impl strategy is not the most obvious. It was
1985 /// chosen because it makes a measurable difference to NLL
1986 /// performance, as this code (`borrow_conflicts_with_place`) is somewhat hot.
1987 pub enum Projections<'p, 'tcx> {
1990 List { projection: &'p Projection<'tcx>, next: &'p Projections<'p, 'tcx> },
1993 impl<'p, 'tcx> Projections<'p, 'tcx> {
1994 fn iter(&self) -> ProjectionsIter<'_, 'tcx> {
1995 ProjectionsIter { value: self }
1999 impl<'p, 'tcx> IntoIterator for &'p Projections<'p, 'tcx> {
2000 type Item = &'p Projection<'tcx>;
2001 type IntoIter = ProjectionsIter<'p, 'tcx>;
2003 /// Converts a list of `Projection` components into an iterator;
2004 /// this iterator yields up a never-ending stream of `Option<&Place>`.
2005 /// These begin with the "innermost" projection and then with each
2006 /// projection therefrom. So given a place like `a.b.c` it would
2010 /// Some(`a`), Some(`a.b`), Some(`a.b.c`), None, None, ...
2012 fn into_iter(self) -> Self::IntoIter {
2017 /// Iterator over components; see `Projections::iter` for more
2020 /// N.B., this is not a *true* Rust iterator -- the code above just
2021 /// manually invokes `next`. This is because we (sometimes) want to
2022 /// keep executing even after `None` has been returned.
2023 pub struct ProjectionsIter<'p, 'tcx> {
2024 pub value: &'p Projections<'p, 'tcx>,
2027 impl<'p, 'tcx> Iterator for ProjectionsIter<'p, 'tcx> {
2028 type Item = &'p Projection<'tcx>;
2030 fn next(&mut self) -> Option<Self::Item> {
2031 if let &Projections::List { projection, next } = self.value {
2040 impl<'p, 'tcx> FusedIterator for ProjectionsIter<'p, 'tcx> {}
2042 impl<'tcx> Debug for Place<'tcx> {
2043 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2044 self.iterate(|_place_base, place_projections| {
2045 // FIXME: remove this collect once we have migrated to slices
2046 let projs_vec: Vec<_> = place_projections.collect();
2047 for projection in projs_vec.iter().rev() {
2048 match projection.elem {
2049 ProjectionElem::Downcast(_, _) | ProjectionElem::Field(_, _) => {
2050 write!(fmt, "(").unwrap();
2052 ProjectionElem::Deref => {
2053 write!(fmt, "(*").unwrap();
2055 ProjectionElem::Index(_)
2056 | ProjectionElem::ConstantIndex { .. }
2057 | ProjectionElem::Subslice { .. } => {}
2062 self.iterate(|place_base, place_projections| {
2063 write!(fmt, "{:?}", place_base)?;
2065 for projection in place_projections {
2066 match projection.elem {
2067 ProjectionElem::Downcast(Some(name), _index) => {
2068 write!(fmt, " as {})", name)?;
2070 ProjectionElem::Downcast(None, index) => {
2071 write!(fmt, " as variant#{:?})", index)?;
2073 ProjectionElem::Deref => {
2076 ProjectionElem::Field(field, ty) => {
2077 write!(fmt, ".{:?}: {:?})", field.index(), ty)?;
2079 ProjectionElem::Index(ref index) => {
2080 write!(fmt, "[{:?}]", index)?;
2082 ProjectionElem::ConstantIndex { offset, min_length, from_end: false } => {
2083 write!(fmt, "[{:?} of {:?}]", offset, min_length)?;
2085 ProjectionElem::ConstantIndex { offset, min_length, from_end: true } => {
2086 write!(fmt, "[-{:?} of {:?}]", offset, min_length)?;
2088 ProjectionElem::Subslice { from, to } if to == 0 => {
2089 write!(fmt, "[{:?}:]", from)?;
2091 ProjectionElem::Subslice { from, to } if from == 0 => {
2092 write!(fmt, "[:-{:?}]", to)?;
2094 ProjectionElem::Subslice { from, to } => {
2095 write!(fmt, "[{:?}:-{:?}]", from, to)?;
2105 impl Debug for PlaceBase<'_> {
2106 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2108 PlaceBase::Local(id) => write!(fmt, "{:?}", id),
2109 PlaceBase::Static(box self::Static { ty, kind: StaticKind::Static(def_id) }) => {
2110 write!(fmt, "({}: {:?})", ty::tls::with(|tcx| tcx.def_path_str(def_id)), ty)
2112 PlaceBase::Static(box self::Static { ty, kind: StaticKind::Promoted(promoted) }) => {
2113 write!(fmt, "({:?}: {:?})", promoted, ty)
2119 ///////////////////////////////////////////////////////////////////////////
2123 pub struct SourceScope {
2125 DEBUG_FORMAT = "scope[{}]",
2126 const OUTERMOST_SOURCE_SCOPE = 0,
2130 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
2131 pub struct SourceScopeData {
2133 pub parent_scope: Option<SourceScope>,
2136 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
2137 pub struct SourceScopeLocalData {
2138 /// A HirId with lint levels equivalent to this scope's lint levels.
2139 pub lint_root: hir::HirId,
2140 /// The unsafe block that contains this node.
2144 ///////////////////////////////////////////////////////////////////////////
2147 /// These are values that can appear inside an rvalue. They are intentionally
2148 /// limited to prevent rvalues from being nested in one another.
2149 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable)]
2150 pub enum Operand<'tcx> {
2151 /// Copy: The value must be available for use afterwards.
2153 /// This implies that the type of the place must be `Copy`; this is true
2154 /// by construction during build, but also checked by the MIR type checker.
2157 /// Move: The value (including old borrows of it) will not be used again.
2159 /// Safe for values of all types (modulo future developments towards `?Move`).
2160 /// Correct usage patterns are enforced by the borrow checker for safe code.
2161 /// `Copy` may be converted to `Move` to enable "last-use" optimizations.
2164 /// Synthesizes a constant value.
2165 Constant(Box<Constant<'tcx>>),
2168 impl<'tcx> Debug for Operand<'tcx> {
2169 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2170 use self::Operand::*;
2172 Constant(ref a) => write!(fmt, "{:?}", a),
2173 Copy(ref place) => write!(fmt, "{:?}", place),
2174 Move(ref place) => write!(fmt, "move {:?}", place),
2179 impl<'tcx> Operand<'tcx> {
2180 /// Convenience helper to make a constant that refers to the fn
2181 /// with given `DefId` and substs. Since this is used to synthesize
2182 /// MIR, assumes `user_ty` is None.
2183 pub fn function_handle(
2186 substs: SubstsRef<'tcx>,
2189 let ty = tcx.type_of(def_id).subst(tcx, substs);
2190 Operand::Constant(box Constant {
2193 literal: ty::Const::zero_sized(tcx, ty),
2197 pub fn to_copy(&self) -> Self {
2199 Operand::Copy(_) | Operand::Constant(_) => self.clone(),
2200 Operand::Move(ref place) => Operand::Copy(place.clone()),
2205 ///////////////////////////////////////////////////////////////////////////
2208 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable)]
2209 pub enum Rvalue<'tcx> {
2210 /// x (either a move or copy, depending on type of x)
2214 Repeat(Operand<'tcx>, u64),
2217 Ref(Region<'tcx>, BorrowKind, Place<'tcx>),
2219 /// length of a [X] or [X;n] value
2222 Cast(CastKind, Operand<'tcx>, Ty<'tcx>),
2224 BinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
2225 CheckedBinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
2227 NullaryOp(NullOp, Ty<'tcx>),
2228 UnaryOp(UnOp, Operand<'tcx>),
2230 /// Read the discriminant of an ADT.
2232 /// Undefined (i.e., no effort is made to make it defined, but there’s no reason why it cannot
2233 /// be defined to return, say, a 0) if ADT is not an enum.
2234 Discriminant(Place<'tcx>),
2236 /// Creates an aggregate value, like a tuple or struct. This is
2237 /// only needed because we want to distinguish `dest = Foo { x:
2238 /// ..., y: ... }` from `dest.x = ...; dest.y = ...;` in the case
2239 /// that `Foo` has a destructor. These rvalues can be optimized
2240 /// away after type-checking and before lowering.
2241 Aggregate(Box<AggregateKind<'tcx>>, Vec<Operand<'tcx>>),
2244 #[derive(Clone, Copy, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2247 Pointer(PointerCast),
2250 #[derive(Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2251 pub enum AggregateKind<'tcx> {
2252 /// The type is of the element
2256 /// The second field is the variant index. It's equal to 0 for struct
2257 /// and union expressions. The fourth field is
2258 /// active field number and is present only for union expressions
2259 /// -- e.g., for a union expression `SomeUnion { c: .. }`, the
2260 /// active field index would identity the field `c`
2261 Adt(&'tcx AdtDef, VariantIdx, SubstsRef<'tcx>, Option<UserTypeAnnotationIndex>, Option<usize>),
2263 Closure(DefId, ClosureSubsts<'tcx>),
2264 Generator(DefId, GeneratorSubsts<'tcx>, hir::GeneratorMovability),
2267 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2269 /// The `+` operator (addition)
2271 /// The `-` operator (subtraction)
2273 /// The `*` operator (multiplication)
2275 /// The `/` operator (division)
2277 /// The `%` operator (modulus)
2279 /// The `^` operator (bitwise xor)
2281 /// The `&` operator (bitwise and)
2283 /// The `|` operator (bitwise or)
2285 /// The `<<` operator (shift left)
2287 /// The `>>` operator (shift right)
2289 /// The `==` operator (equality)
2291 /// The `<` operator (less than)
2293 /// The `<=` operator (less than or equal to)
2295 /// The `!=` operator (not equal to)
2297 /// The `>=` operator (greater than or equal to)
2299 /// The `>` operator (greater than)
2301 /// The `ptr.offset` operator
2306 pub fn is_checkable(self) -> bool {
2309 Add | Sub | Mul | Shl | Shr => true,
2315 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2317 /// Returns the size of a value of that type
2319 /// Creates a new uninitialized box for a value of that type
2323 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2325 /// The `!` operator for logical inversion
2327 /// The `-` operator for negation
2331 impl<'tcx> Debug for Rvalue<'tcx> {
2332 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2333 use self::Rvalue::*;
2336 Use(ref place) => write!(fmt, "{:?}", place),
2337 Repeat(ref a, ref b) => write!(fmt, "[{:?}; {:?}]", a, b),
2338 Len(ref a) => write!(fmt, "Len({:?})", a),
2339 Cast(ref kind, ref place, ref ty) => {
2340 write!(fmt, "{:?} as {:?} ({:?})", place, ty, kind)
2342 BinaryOp(ref op, ref a, ref b) => write!(fmt, "{:?}({:?}, {:?})", op, a, b),
2343 CheckedBinaryOp(ref op, ref a, ref b) => {
2344 write!(fmt, "Checked{:?}({:?}, {:?})", op, a, b)
2346 UnaryOp(ref op, ref a) => write!(fmt, "{:?}({:?})", op, a),
2347 Discriminant(ref place) => write!(fmt, "discriminant({:?})", place),
2348 NullaryOp(ref op, ref t) => write!(fmt, "{:?}({:?})", op, t),
2349 Ref(region, borrow_kind, ref place) => {
2350 let kind_str = match borrow_kind {
2351 BorrowKind::Shared => "",
2352 BorrowKind::Shallow => "shallow ",
2353 BorrowKind::Mut { .. } | BorrowKind::Unique => "mut ",
2356 // When printing regions, add trailing space if necessary.
2357 let print_region = ty::tls::with(|tcx| {
2358 tcx.sess.verbose() || tcx.sess.opts.debugging_opts.identify_regions
2360 let region = if print_region {
2361 let mut region = region.to_string();
2362 if region.len() > 0 {
2367 // Do not even print 'static
2370 write!(fmt, "&{}{}{:?}", region, kind_str, place)
2373 Aggregate(ref kind, ref places) => {
2374 fn fmt_tuple(fmt: &mut Formatter<'_>, places: &[Operand<'_>]) -> fmt::Result {
2375 let mut tuple_fmt = fmt.debug_tuple("");
2376 for place in places {
2377 tuple_fmt.field(place);
2383 AggregateKind::Array(_) => write!(fmt, "{:?}", places),
2385 AggregateKind::Tuple => match places.len() {
2386 0 => write!(fmt, "()"),
2387 1 => write!(fmt, "({:?},)", places[0]),
2388 _ => fmt_tuple(fmt, places),
2391 AggregateKind::Adt(adt_def, variant, substs, _user_ty, _) => {
2392 let variant_def = &adt_def.variants[variant];
2395 ty::tls::with(|tcx| {
2396 let substs = tcx.lift(&substs).expect("could not lift for printing");
2397 FmtPrinter::new(tcx, f, Namespace::ValueNS)
2398 .print_def_path(variant_def.def_id, substs)?;
2402 match variant_def.ctor_kind {
2403 CtorKind::Const => Ok(()),
2404 CtorKind::Fn => fmt_tuple(fmt, places),
2405 CtorKind::Fictive => {
2406 let mut struct_fmt = fmt.debug_struct("");
2407 for (field, place) in variant_def.fields.iter().zip(places) {
2408 struct_fmt.field(&field.ident.as_str(), place);
2415 AggregateKind::Closure(def_id, _) => ty::tls::with(|tcx| {
2416 if let Some(hir_id) = tcx.hir().as_local_hir_id(def_id) {
2417 let name = if tcx.sess.opts.debugging_opts.span_free_formats {
2418 format!("[closure@{:?}]", hir_id)
2420 format!("[closure@{:?}]", tcx.hir().span(hir_id))
2422 let mut struct_fmt = fmt.debug_struct(&name);
2424 if let Some(upvars) = tcx.upvars(def_id) {
2425 for (&var_id, place) in upvars.keys().zip(places) {
2426 let var_name = tcx.hir().name(var_id);
2427 struct_fmt.field(&var_name.as_str(), place);
2433 write!(fmt, "[closure]")
2437 AggregateKind::Generator(def_id, _, _) => ty::tls::with(|tcx| {
2438 if let Some(hir_id) = tcx.hir().as_local_hir_id(def_id) {
2439 let name = format!("[generator@{:?}]", tcx.hir().span(hir_id));
2440 let mut struct_fmt = fmt.debug_struct(&name);
2442 if let Some(upvars) = tcx.upvars(def_id) {
2443 for (&var_id, place) in upvars.keys().zip(places) {
2444 let var_name = tcx.hir().name(var_id);
2445 struct_fmt.field(&var_name.as_str(), place);
2451 write!(fmt, "[generator]")
2460 ///////////////////////////////////////////////////////////////////////////
2463 /// Two constants are equal if they are the same constant. Note that
2464 /// this does not necessarily mean that they are "==" in Rust -- in
2465 /// particular one must be wary of `NaN`!
2467 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, HashStable)]
2468 pub struct Constant<'tcx> {
2471 /// Optional user-given type: for something like
2472 /// `collect::<Vec<_>>`, this would be present and would
2473 /// indicate that `Vec<_>` was explicitly specified.
2475 /// Needed for NLL to impose user-given type constraints.
2476 pub user_ty: Option<UserTypeAnnotationIndex>,
2478 pub literal: &'tcx ty::Const<'tcx>,
2481 /// A collection of projections into user types.
2483 /// They are projections because a binding can occur a part of a
2484 /// parent pattern that has been ascribed a type.
2486 /// Its a collection because there can be multiple type ascriptions on
2487 /// the path from the root of the pattern down to the binding itself.
2492 /// struct S<'a>((i32, &'a str), String);
2493 /// let S((_, w): (i32, &'static str), _): S = ...;
2494 /// // ------ ^^^^^^^^^^^^^^^^^^^ (1)
2495 /// // --------------------------------- ^ (2)
2498 /// The highlights labelled `(1)` show the subpattern `(_, w)` being
2499 /// ascribed the type `(i32, &'static str)`.
2501 /// The highlights labelled `(2)` show the whole pattern being
2502 /// ascribed the type `S`.
2504 /// In this example, when we descend to `w`, we will have built up the
2505 /// following two projected types:
2507 /// * base: `S`, projection: `(base.0).1`
2508 /// * base: `(i32, &'static str)`, projection: `base.1`
2510 /// The first will lead to the constraint `w: &'1 str` (for some
2511 /// inferred region `'1`). The second will lead to the constraint `w:
2513 #[derive(Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, HashStable)]
2514 pub struct UserTypeProjections {
2515 pub(crate) contents: Vec<(UserTypeProjection, Span)>,
2518 BraceStructTypeFoldableImpl! {
2519 impl<'tcx> TypeFoldable<'tcx> for UserTypeProjections {
2524 impl<'tcx> UserTypeProjections {
2525 pub fn none() -> Self {
2526 UserTypeProjections { contents: vec![] }
2529 pub fn from_projections(projs: impl Iterator<Item = (UserTypeProjection, Span)>) -> Self {
2530 UserTypeProjections { contents: projs.collect() }
2533 pub fn projections_and_spans(&self) -> impl Iterator<Item = &(UserTypeProjection, Span)> {
2534 self.contents.iter()
2537 pub fn projections(&self) -> impl Iterator<Item = &UserTypeProjection> {
2538 self.contents.iter().map(|&(ref user_type, _span)| user_type)
2541 pub fn push_projection(mut self, user_ty: &UserTypeProjection, span: Span) -> Self {
2542 self.contents.push((user_ty.clone(), span));
2548 mut f: impl FnMut(UserTypeProjection) -> UserTypeProjection,
2550 self.contents = self.contents.drain(..).map(|(proj, span)| (f(proj), span)).collect();
2554 pub fn index(self) -> Self {
2555 self.map_projections(|pat_ty_proj| pat_ty_proj.index())
2558 pub fn subslice(self, from: u32, to: u32) -> Self {
2559 self.map_projections(|pat_ty_proj| pat_ty_proj.subslice(from, to))
2562 pub fn deref(self) -> Self {
2563 self.map_projections(|pat_ty_proj| pat_ty_proj.deref())
2566 pub fn leaf(self, field: Field) -> Self {
2567 self.map_projections(|pat_ty_proj| pat_ty_proj.leaf(field))
2570 pub fn variant(self, adt_def: &'tcx AdtDef, variant_index: VariantIdx, field: Field) -> Self {
2571 self.map_projections(|pat_ty_proj| pat_ty_proj.variant(adt_def, variant_index, field))
2575 /// Encodes the effect of a user-supplied type annotation on the
2576 /// subcomponents of a pattern. The effect is determined by applying the
2577 /// given list of proejctions to some underlying base type. Often,
2578 /// the projection element list `projs` is empty, in which case this
2579 /// directly encodes a type in `base`. But in the case of complex patterns with
2580 /// subpatterns and bindings, we want to apply only a *part* of the type to a variable,
2581 /// in which case the `projs` vector is used.
2585 /// * `let x: T = ...` -- here, the `projs` vector is empty.
2587 /// * `let (x, _): T = ...` -- here, the `projs` vector would contain
2588 /// `field[0]` (aka `.0`), indicating that the type of `s` is
2589 /// determined by finding the type of the `.0` field from `T`.
2590 #[derive(Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, HashStable)]
2591 pub struct UserTypeProjection {
2592 pub base: UserTypeAnnotationIndex,
2593 pub projs: Vec<ProjectionKind>,
2596 impl Copy for ProjectionKind {}
2598 impl UserTypeProjection {
2599 pub(crate) fn index(mut self) -> Self {
2600 self.projs.push(ProjectionElem::Index(()));
2604 pub(crate) fn subslice(mut self, from: u32, to: u32) -> Self {
2605 self.projs.push(ProjectionElem::Subslice { from, to });
2609 pub(crate) fn deref(mut self) -> Self {
2610 self.projs.push(ProjectionElem::Deref);
2614 pub(crate) fn leaf(mut self, field: Field) -> Self {
2615 self.projs.push(ProjectionElem::Field(field, ()));
2619 pub(crate) fn variant(
2621 adt_def: &'tcx AdtDef,
2622 variant_index: VariantIdx,
2625 self.projs.push(ProjectionElem::Downcast(
2626 Some(adt_def.variants[variant_index].ident.name),
2629 self.projs.push(ProjectionElem::Field(field, ()));
2634 CloneTypeFoldableAndLiftImpls! { ProjectionKind, }
2636 impl<'tcx> TypeFoldable<'tcx> for UserTypeProjection {
2637 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
2638 use crate::mir::ProjectionElem::*;
2640 let base = self.base.fold_with(folder);
2641 let projs: Vec<_> = self
2644 .map(|elem| match elem {
2646 Field(f, ()) => Field(f.clone(), ()),
2647 Index(()) => Index(()),
2648 elem => elem.clone(),
2652 UserTypeProjection { base, projs }
2655 fn super_visit_with<Vs: TypeVisitor<'tcx>>(&self, visitor: &mut Vs) -> bool {
2656 self.base.visit_with(visitor)
2657 // Note: there's nothing in `self.proj` to visit.
2662 pub struct Promoted {
2664 DEBUG_FORMAT = "promoted[{}]"
2668 impl<'tcx> Debug for Constant<'tcx> {
2669 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2670 write!(fmt, "{}", self)
2674 impl<'tcx> Display for Constant<'tcx> {
2675 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2676 write!(fmt, "const ")?;
2677 write!(fmt, "{}", self.literal)
2681 impl<'tcx> graph::DirectedGraph for Body<'tcx> {
2682 type Node = BasicBlock;
2685 impl<'tcx> graph::WithNumNodes for Body<'tcx> {
2686 fn num_nodes(&self) -> usize {
2687 self.basic_blocks.len()
2691 impl<'tcx> graph::WithStartNode for Body<'tcx> {
2692 fn start_node(&self) -> Self::Node {
2697 impl<'tcx> graph::WithPredecessors for Body<'tcx> {
2701 ) -> <Self as GraphPredecessors<'_>>::Iter {
2702 self.predecessors_for(node).clone().into_iter()
2706 impl<'tcx> graph::WithSuccessors for Body<'tcx> {
2710 ) -> <Self as GraphSuccessors<'_>>::Iter {
2711 self.basic_blocks[node].terminator().successors().cloned()
2715 impl<'a, 'b> graph::GraphPredecessors<'b> for Body<'a> {
2716 type Item = BasicBlock;
2717 type Iter = IntoIter<BasicBlock>;
2720 impl<'a, 'b> graph::GraphSuccessors<'b> for Body<'a> {
2721 type Item = BasicBlock;
2722 type Iter = iter::Cloned<Successors<'b>>;
2725 #[derive(Copy, Clone, PartialEq, Eq, Hash, Ord, PartialOrd, HashStable)]
2726 pub struct Location {
2727 /// the location is within this block
2728 pub block: BasicBlock,
2730 /// the location is the start of the statement; or, if `statement_index`
2731 /// == num-statements, then the start of the terminator.
2732 pub statement_index: usize,
2735 impl fmt::Debug for Location {
2736 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2737 write!(fmt, "{:?}[{}]", self.block, self.statement_index)
2742 pub const START: Location = Location { block: START_BLOCK, statement_index: 0 };
2744 /// Returns the location immediately after this one within the enclosing block.
2746 /// Note that if this location represents a terminator, then the
2747 /// resulting location would be out of bounds and invalid.
2748 pub fn successor_within_block(&self) -> Location {
2749 Location { block: self.block, statement_index: self.statement_index + 1 }
2752 /// Returns `true` if `other` is earlier in the control flow graph than `self`.
2753 pub fn is_predecessor_of<'tcx>(&self, other: Location, body: &Body<'tcx>) -> bool {
2754 // If we are in the same block as the other location and are an earlier statement
2755 // then we are a predecessor of `other`.
2756 if self.block == other.block && self.statement_index < other.statement_index {
2760 // If we're in another block, then we want to check that block is a predecessor of `other`.
2761 let mut queue: Vec<BasicBlock> = body.predecessors_for(other.block).clone();
2762 let mut visited = FxHashSet::default();
2764 while let Some(block) = queue.pop() {
2765 // If we haven't visited this block before, then make sure we visit it's predecessors.
2766 if visited.insert(block) {
2767 queue.append(&mut body.predecessors_for(block).clone());
2772 // If we found the block that `self` is in, then we are a predecessor of `other` (since
2773 // we found that block by looking at the predecessors of `other`).
2774 if self.block == block {
2782 pub fn dominates(&self, other: Location, dominators: &Dominators<BasicBlock>) -> bool {
2783 if self.block == other.block {
2784 self.statement_index <= other.statement_index
2786 dominators.is_dominated_by(other.block, self.block)
2791 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, HashStable)]
2792 pub enum UnsafetyViolationKind {
2794 /// Permitted in const fn and regular fns.
2796 ExternStatic(hir::HirId),
2797 BorrowPacked(hir::HirId),
2800 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, HashStable)]
2801 pub struct UnsafetyViolation {
2802 pub source_info: SourceInfo,
2803 pub description: InternedString,
2804 pub details: InternedString,
2805 pub kind: UnsafetyViolationKind,
2808 #[derive(Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, HashStable)]
2809 pub struct UnsafetyCheckResult {
2810 /// Violations that are propagated *upwards* from this function
2811 pub violations: Lrc<[UnsafetyViolation]>,
2812 /// unsafe blocks in this function, along with whether they are used. This is
2813 /// used for the "unused_unsafe" lint.
2814 pub unsafe_blocks: Lrc<[(hir::HirId, bool)]>,
2818 pub struct GeneratorSavedLocal {
2820 DEBUG_FORMAT = "_{}",
2824 /// The layout of generator state
2825 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
2826 pub struct GeneratorLayout<'tcx> {
2827 /// The type of every local stored inside the generator.
2828 pub field_tys: IndexVec<GeneratorSavedLocal, Ty<'tcx>>,
2830 /// Which of the above fields are in each variant. Note that one field may
2831 /// be stored in multiple variants.
2832 pub variant_fields: IndexVec<VariantIdx, IndexVec<Field, GeneratorSavedLocal>>,
2834 /// Which saved locals are storage-live at the same time. Locals that do not
2835 /// have conflicts with each other are allowed to overlap in the computed
2837 pub storage_conflicts: BitMatrix<GeneratorSavedLocal, GeneratorSavedLocal>,
2839 /// Names and scopes of all the stored generator locals.
2840 /// NOTE(tmandry) This is *strictly* a temporary hack for codegen
2841 /// debuginfo generation, and will be removed at some point.
2842 /// Do **NOT** use it for anything else, local information should not be
2843 /// in the MIR, please rely on local crate HIR or other side-channels.
2844 pub __local_debuginfo_codegen_only_do_not_use: IndexVec<GeneratorSavedLocal, LocalDecl<'tcx>>,
2847 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
2848 pub struct BorrowCheckResult<'tcx> {
2849 pub closure_requirements: Option<ClosureRegionRequirements<'tcx>>,
2850 pub used_mut_upvars: SmallVec<[Field; 8]>,
2853 /// After we borrow check a closure, we are left with various
2854 /// requirements that we have inferred between the free regions that
2855 /// appear in the closure's signature or on its field types. These
2856 /// requirements are then verified and proved by the closure's
2857 /// creating function. This struct encodes those requirements.
2859 /// The requirements are listed as being between various
2860 /// `RegionVid`. The 0th region refers to `'static`; subsequent region
2861 /// vids refer to the free regions that appear in the closure (or
2862 /// generator's) type, in order of appearance. (This numbering is
2863 /// actually defined by the `UniversalRegions` struct in the NLL
2864 /// region checker. See for example
2865 /// `UniversalRegions::closure_mapping`.) Note that we treat the free
2866 /// regions in the closure's type "as if" they were erased, so their
2867 /// precise identity is not important, only their position.
2869 /// Example: If type check produces a closure with the closure substs:
2872 /// ClosureSubsts = [
2873 /// i8, // the "closure kind"
2874 /// for<'x> fn(&'a &'x u32) -> &'x u32, // the "closure signature"
2875 /// &'a String, // some upvar
2879 /// here, there is one unique free region (`'a`) but it appears
2880 /// twice. We would "renumber" each occurrence to a unique vid, as follows:
2883 /// ClosureSubsts = [
2884 /// i8, // the "closure kind"
2885 /// for<'x> fn(&'1 &'x u32) -> &'x u32, // the "closure signature"
2886 /// &'2 String, // some upvar
2890 /// Now the code might impose a requirement like `'1: '2`. When an
2891 /// instance of the closure is created, the corresponding free regions
2892 /// can be extracted from its type and constrained to have the given
2893 /// outlives relationship.
2895 /// In some cases, we have to record outlives requirements between
2896 /// types and regions as well. In that case, if those types include
2897 /// any regions, those regions are recorded as `ReClosureBound`
2898 /// instances assigned one of these same indices. Those regions will
2899 /// be substituted away by the creator. We use `ReClosureBound` in
2900 /// that case because the regions must be allocated in the global
2901 /// TyCtxt, and hence we cannot use `ReVar` (which is what we use
2902 /// internally within the rest of the NLL code).
2903 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
2904 pub struct ClosureRegionRequirements<'tcx> {
2905 /// The number of external regions defined on the closure. In our
2906 /// example above, it would be 3 -- one for `'static`, then `'1`
2907 /// and `'2`. This is just used for a sanity check later on, to
2908 /// make sure that the number of regions we see at the callsite
2910 pub num_external_vids: usize,
2912 /// Requirements between the various free regions defined in
2914 pub outlives_requirements: Vec<ClosureOutlivesRequirement<'tcx>>,
2917 /// Indicates an outlives constraint between a type or between two
2918 /// free-regions declared on the closure.
2919 #[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
2920 pub struct ClosureOutlivesRequirement<'tcx> {
2921 // This region or type ...
2922 pub subject: ClosureOutlivesSubject<'tcx>,
2924 // ... must outlive this one.
2925 pub outlived_free_region: ty::RegionVid,
2927 // If not, report an error here ...
2928 pub blame_span: Span,
2930 // ... due to this reason.
2931 pub category: ConstraintCategory,
2934 /// Outlives constraints can be categorized to determine whether and why they
2935 /// are interesting (for error reporting). Order of variants indicates sort
2936 /// order of the category, thereby influencing diagnostic output.
2938 /// See also [rustc_mir::borrow_check::nll::constraints]
2952 pub enum ConstraintCategory {
2960 /// A constraint that came from checking the body of a closure.
2962 /// We try to get the category that the closure used when reporting this.
2970 /// A "boring" constraint (caused by the given location) is one that
2971 /// the user probably doesn't want to see described in diagnostics,
2972 /// because it is kind of an artifact of the type system setup.
2973 /// Example: `x = Foo { field: y }` technically creates
2974 /// intermediate regions representing the "type of `Foo { field: y
2975 /// }`", and data flows from `y` into those variables, but they
2976 /// are not very interesting. The assignment into `x` on the other
2979 // Boring and applicable everywhere.
2982 /// A constraint that doesn't correspond to anything the user sees.
2986 /// The subject of a ClosureOutlivesRequirement -- that is, the thing
2987 /// that must outlive some region.
2988 #[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
2989 pub enum ClosureOutlivesSubject<'tcx> {
2990 /// Subject is a type, typically a type parameter, but could also
2991 /// be a projection. Indicates a requirement like `T: 'a` being
2992 /// passed to the caller, where the type here is `T`.
2994 /// The type here is guaranteed not to contain any free regions at
2998 /// Subject is a free region from the closure. Indicates a requirement
2999 /// like `'a: 'b` being passed to the caller; the region here is `'a`.
3000 Region(ty::RegionVid),
3004 * TypeFoldable implementations for MIR types
3007 CloneTypeFoldableAndLiftImpls! {
3017 SourceScopeLocalData,
3018 UserTypeAnnotationIndex,
3021 BraceStructTypeFoldableImpl! {
3022 impl<'tcx> TypeFoldable<'tcx> for Body<'tcx> {
3026 source_scope_local_data,
3031 user_type_annotations,
3033 __upvar_debuginfo_codegen_only_do_not_use,
3035 control_flow_destroyed,
3041 BraceStructTypeFoldableImpl! {
3042 impl<'tcx> TypeFoldable<'tcx> for GeneratorLayout<'tcx> {
3046 __local_debuginfo_codegen_only_do_not_use,
3050 BraceStructTypeFoldableImpl! {
3051 impl<'tcx> TypeFoldable<'tcx> for LocalDecl<'tcx> {
3064 BraceStructTypeFoldableImpl! {
3065 impl<'tcx> TypeFoldable<'tcx> for BasicBlockData<'tcx> {
3072 BraceStructTypeFoldableImpl! {
3073 impl<'tcx> TypeFoldable<'tcx> for Statement<'tcx> {
3078 EnumTypeFoldableImpl! {
3079 impl<'tcx> TypeFoldable<'tcx> for StatementKind<'tcx> {
3080 (StatementKind::Assign)(a, b),
3081 (StatementKind::FakeRead)(cause, place),
3082 (StatementKind::SetDiscriminant) { place, variant_index },
3083 (StatementKind::StorageLive)(a),
3084 (StatementKind::StorageDead)(a),
3085 (StatementKind::InlineAsm)(a),
3086 (StatementKind::Retag)(kind, place),
3087 (StatementKind::AscribeUserType)(a, v, b),
3088 (StatementKind::Nop),
3092 BraceStructTypeFoldableImpl! {
3093 impl<'tcx> TypeFoldable<'tcx> for InlineAsm<'tcx> {
3100 EnumTypeFoldableImpl! {
3101 impl<'tcx, T> TypeFoldable<'tcx> for ClearCrossCrate<T> {
3102 (ClearCrossCrate::Clear),
3103 (ClearCrossCrate::Set)(a),
3104 } where T: TypeFoldable<'tcx>
3107 impl<'tcx> TypeFoldable<'tcx> for Terminator<'tcx> {
3108 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
3109 use crate::mir::TerminatorKind::*;
3111 let kind = match self.kind {
3112 Goto { target } => Goto { target },
3113 SwitchInt { ref discr, switch_ty, ref values, ref targets } => SwitchInt {
3114 discr: discr.fold_with(folder),
3115 switch_ty: switch_ty.fold_with(folder),
3116 values: values.clone(),
3117 targets: targets.clone(),
3119 Drop { ref location, target, unwind } => {
3120 Drop { location: location.fold_with(folder), target, unwind }
3122 DropAndReplace { ref location, ref value, target, unwind } => DropAndReplace {
3123 location: location.fold_with(folder),
3124 value: value.fold_with(folder),
3128 Yield { ref value, resume, drop } => {
3129 Yield { value: value.fold_with(folder), resume: resume, drop: drop }
3131 Call { ref func, ref args, ref destination, cleanup, from_hir_call } => {
3133 destination.as_ref().map(|&(ref loc, dest)| (loc.fold_with(folder), dest));
3136 func: func.fold_with(folder),
3137 args: args.fold_with(folder),
3143 Assert { ref cond, expected, ref msg, target, cleanup } => {
3145 let msg = match msg {
3146 BoundsCheck { ref len, ref index } =>
3148 len: len.fold_with(folder),
3149 index: index.fold_with(folder),
3151 Panic { .. } | Overflow(_) | OverflowNeg | DivisionByZero | RemainderByZero |
3152 GeneratorResumedAfterReturn | GeneratorResumedAfterPanic =>
3155 Assert { cond: cond.fold_with(folder), expected, msg, target, cleanup }
3157 GeneratorDrop => GeneratorDrop,
3161 Unreachable => Unreachable,
3162 FalseEdges { real_target, imaginary_target } => {
3163 FalseEdges { real_target, imaginary_target }
3165 FalseUnwind { real_target, unwind } => FalseUnwind { real_target, unwind },
3167 Terminator { source_info: self.source_info, kind }
3170 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3171 use crate::mir::TerminatorKind::*;
3174 SwitchInt { ref discr, switch_ty, .. } => {
3175 discr.visit_with(visitor) || switch_ty.visit_with(visitor)
3177 Drop { ref location, .. } => location.visit_with(visitor),
3178 DropAndReplace { ref location, ref value, .. } => {
3179 location.visit_with(visitor) || value.visit_with(visitor)
3181 Yield { ref value, .. } => value.visit_with(visitor),
3182 Call { ref func, ref args, ref destination, .. } => {
3183 let dest = if let Some((ref loc, _)) = *destination {
3184 loc.visit_with(visitor)
3188 dest || func.visit_with(visitor) || args.visit_with(visitor)
3190 Assert { ref cond, ref msg, .. } => {
3191 if cond.visit_with(visitor) {
3194 BoundsCheck { ref len, ref index } =>
3195 len.visit_with(visitor) || index.visit_with(visitor),
3196 Panic { .. } | Overflow(_) | OverflowNeg |
3197 DivisionByZero | RemainderByZero |
3198 GeneratorResumedAfterReturn | GeneratorResumedAfterPanic =>
3212 | FalseUnwind { .. } => false,
3217 impl<'tcx> TypeFoldable<'tcx> for Place<'tcx> {
3218 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
3220 base: self.base.clone(),
3221 projection: self.projection.fold_with(folder),
3225 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3226 self.projection.visit_with(visitor)
3230 impl<'tcx> TypeFoldable<'tcx> for Rvalue<'tcx> {
3231 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
3232 use crate::mir::Rvalue::*;
3234 Use(ref op) => Use(op.fold_with(folder)),
3235 Repeat(ref op, len) => Repeat(op.fold_with(folder), len),
3236 Ref(region, bk, ref place) => {
3237 Ref(region.fold_with(folder), bk, place.fold_with(folder))
3239 Len(ref place) => Len(place.fold_with(folder)),
3240 Cast(kind, ref op, ty) => Cast(kind, op.fold_with(folder), ty.fold_with(folder)),
3241 BinaryOp(op, ref rhs, ref lhs) => {
3242 BinaryOp(op, rhs.fold_with(folder), lhs.fold_with(folder))
3244 CheckedBinaryOp(op, ref rhs, ref lhs) => {
3245 CheckedBinaryOp(op, rhs.fold_with(folder), lhs.fold_with(folder))
3247 UnaryOp(op, ref val) => UnaryOp(op, val.fold_with(folder)),
3248 Discriminant(ref place) => Discriminant(place.fold_with(folder)),
3249 NullaryOp(op, ty) => NullaryOp(op, ty.fold_with(folder)),
3250 Aggregate(ref kind, ref fields) => {
3251 let kind = box match **kind {
3252 AggregateKind::Array(ty) => AggregateKind::Array(ty.fold_with(folder)),
3253 AggregateKind::Tuple => AggregateKind::Tuple,
3254 AggregateKind::Adt(def, v, substs, user_ty, n) => AggregateKind::Adt(
3257 substs.fold_with(folder),
3258 user_ty.fold_with(folder),
3261 AggregateKind::Closure(id, substs) => {
3262 AggregateKind::Closure(id, substs.fold_with(folder))
3264 AggregateKind::Generator(id, substs, movablity) => {
3265 AggregateKind::Generator(id, substs.fold_with(folder), movablity)
3268 Aggregate(kind, fields.fold_with(folder))
3273 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3274 use crate::mir::Rvalue::*;
3276 Use(ref op) => op.visit_with(visitor),
3277 Repeat(ref op, _) => op.visit_with(visitor),
3278 Ref(region, _, ref place) => region.visit_with(visitor) || place.visit_with(visitor),
3279 Len(ref place) => place.visit_with(visitor),
3280 Cast(_, ref op, ty) => op.visit_with(visitor) || ty.visit_with(visitor),
3281 BinaryOp(_, ref rhs, ref lhs) | CheckedBinaryOp(_, ref rhs, ref lhs) => {
3282 rhs.visit_with(visitor) || lhs.visit_with(visitor)
3284 UnaryOp(_, ref val) => val.visit_with(visitor),
3285 Discriminant(ref place) => place.visit_with(visitor),
3286 NullaryOp(_, ty) => ty.visit_with(visitor),
3287 Aggregate(ref kind, ref fields) => {
3289 AggregateKind::Array(ty) => ty.visit_with(visitor),
3290 AggregateKind::Tuple => false,
3291 AggregateKind::Adt(_, _, substs, user_ty, _) => {
3292 substs.visit_with(visitor) || user_ty.visit_with(visitor)
3294 AggregateKind::Closure(_, substs) => substs.visit_with(visitor),
3295 AggregateKind::Generator(_, substs, _) => substs.visit_with(visitor),
3296 }) || fields.visit_with(visitor)
3302 impl<'tcx> TypeFoldable<'tcx> for Operand<'tcx> {
3303 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
3305 Operand::Copy(ref place) => Operand::Copy(place.fold_with(folder)),
3306 Operand::Move(ref place) => Operand::Move(place.fold_with(folder)),
3307 Operand::Constant(ref c) => Operand::Constant(c.fold_with(folder)),
3311 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3313 Operand::Copy(ref place) | Operand::Move(ref place) => place.visit_with(visitor),
3314 Operand::Constant(ref c) => c.visit_with(visitor),
3319 impl<'tcx> TypeFoldable<'tcx> for Projection<'tcx> {
3320 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
3321 use crate::mir::ProjectionElem::*;
3323 let base = self.base.fold_with(folder);
3324 let elem = match self.elem {
3326 Field(f, ref ty) => Field(f, ty.fold_with(folder)),
3327 Index(ref v) => Index(v.fold_with(folder)),
3328 ref elem => elem.clone(),
3331 Projection { base, elem }
3334 fn super_visit_with<Vs: TypeVisitor<'tcx>>(&self, visitor: &mut Vs) -> bool {
3335 use crate::mir::ProjectionElem::*;
3337 self.base.visit_with(visitor)
3338 || match self.elem {
3339 Field(_, ref ty) => ty.visit_with(visitor),
3340 Index(ref v) => v.visit_with(visitor),
3346 impl<'tcx> TypeFoldable<'tcx> for Field {
3347 fn super_fold_with<F: TypeFolder<'tcx>>(&self, _: &mut F) -> Self {
3350 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, _: &mut V) -> bool {
3355 impl<'tcx> TypeFoldable<'tcx> for GeneratorSavedLocal {
3356 fn super_fold_with<F: TypeFolder<'tcx>>(&self, _: &mut F) -> Self {
3359 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, _: &mut V) -> bool {
3364 impl<'tcx, R: Idx, C: Idx> TypeFoldable<'tcx> for BitMatrix<R, C> {
3365 fn super_fold_with<F: TypeFolder<'tcx>>(&self, _: &mut F) -> Self {
3368 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, _: &mut V) -> bool {
3373 impl<'tcx> TypeFoldable<'tcx> for Constant<'tcx> {
3374 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
3376 span: self.span.clone(),
3377 user_ty: self.user_ty.fold_with(folder),
3378 literal: self.literal.fold_with(folder),
3381 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3382 self.literal.visit_with(visitor)