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, GeneratorKind};
10 use crate::mir::interpret::{GlobalAlloc, 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, List, Region, Ty, TyCtxt, UserTypeAnnotationIndex,
21 use polonius_engine::Atom;
22 use rustc_index::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_index::vec::{Idx, IndexVec};
27 use rustc_data_structures::sync::Lrc;
28 use rustc_macros::HashStable;
29 use rustc_serialize::{Encodable, Decodable};
30 use smallvec::SmallVec;
32 use std::fmt::{self, Debug, Display, Formatter, Write};
33 use std::ops::{Index, IndexMut};
35 use std::vec::IntoIter;
36 use std::{iter, mem, option, u32};
37 use syntax::ast::Name;
38 use syntax::symbol::Symbol;
39 use syntax_pos::{Span, DUMMY_SP};
41 pub use crate::mir::interpret::AssertMessage;
50 type LocalDecls<'tcx> = IndexVec<Local, LocalDecl<'tcx>>;
52 pub trait HasLocalDecls<'tcx> {
53 fn local_decls(&self) -> &LocalDecls<'tcx>;
56 impl<'tcx> HasLocalDecls<'tcx> for LocalDecls<'tcx> {
57 fn local_decls(&self) -> &LocalDecls<'tcx> {
62 impl<'tcx> HasLocalDecls<'tcx> for Body<'tcx> {
63 fn local_decls(&self) -> &LocalDecls<'tcx> {
68 /// The various "big phases" that MIR goes through.
70 /// Warning: ordering of variants is significant.
71 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, HashStable,
72 Debug, PartialEq, Eq, PartialOrd, Ord)]
81 /// Gets the index of the current MirPhase within the set of all `MirPhase`s.
82 pub fn phase_index(&self) -> usize {
87 /// The lowered representation of a single function.
88 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable, TypeFoldable)]
89 pub struct Body<'tcx> {
90 /// A list of basic blocks. References to basic block use a newtyped index type `BasicBlock`
91 /// that indexes into this vector.
92 basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
94 /// Records how far through the "desugaring and optimization" process this particular
95 /// MIR has traversed. This is particularly useful when inlining, since in that context
96 /// we instantiate the promoted constants and add them to our promoted vector -- but those
97 /// promoted items have already been optimized, whereas ours have not. This field allows
98 /// us to see the difference and forego optimization on the inlined promoted items.
101 /// A list of source scopes; these are referenced by statements
102 /// and used for debuginfo. Indexed by a `SourceScope`.
103 pub source_scopes: IndexVec<SourceScope, SourceScopeData>,
105 /// The yield type of the function, if it is a generator.
106 pub yield_ty: Option<Ty<'tcx>>,
108 /// Generator drop glue.
109 pub generator_drop: Option<Box<Body<'tcx>>>,
111 /// The layout of a generator. Produced by the state transformation.
112 pub generator_layout: Option<GeneratorLayout<'tcx>>,
114 /// If this is a generator then record the type of source expression that caused this generator
116 pub generator_kind: Option<GeneratorKind>,
118 /// Declarations of locals.
120 /// The first local is the return value pointer, followed by `arg_count`
121 /// locals for the function arguments, followed by any user-declared
122 /// variables and temporaries.
123 pub local_decls: LocalDecls<'tcx>,
125 /// User type annotations.
126 pub user_type_annotations: CanonicalUserTypeAnnotations<'tcx>,
128 /// The number of arguments this function takes.
130 /// Starting at local 1, `arg_count` locals will be provided by the caller
131 /// and can be assumed to be initialized.
133 /// If this MIR was built for a constant, this will be 0.
134 pub arg_count: usize,
136 /// Mark an argument local (which must be a tuple) as getting passed as
137 /// its individual components at the LLVM level.
139 /// This is used for the "rust-call" ABI.
140 pub spread_arg: Option<Local>,
142 /// Debug information pertaining to user variables, including captures.
143 pub var_debug_info: Vec<VarDebugInfo<'tcx>>,
145 /// Mark this MIR of a const context other than const functions as having converted a `&&` or
146 /// `||` expression into `&` or `|` respectively. This is problematic because if we ever stop
147 /// this conversion from happening and use short circuiting, we will cause the following code
148 /// to change the value of `x`: `let mut x = 42; false && { x = 55; true };`
150 /// List of places where control flow was destroyed. Used for error reporting.
151 pub control_flow_destroyed: Vec<(Span, String)>,
153 /// A span representing this MIR, for error reporting.
156 /// A cache for various calculations.
157 predecessors_cache: Option<IndexVec<BasicBlock, Vec<BasicBlock>>>,
160 impl<'tcx> Body<'tcx> {
162 basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
163 source_scopes: IndexVec<SourceScope, SourceScopeData>,
164 local_decls: LocalDecls<'tcx>,
165 user_type_annotations: CanonicalUserTypeAnnotations<'tcx>,
167 var_debug_info: Vec<VarDebugInfo<'tcx>>,
169 control_flow_destroyed: Vec<(Span, String)>,
170 generator_kind : Option<GeneratorKind>,
172 // We need `arg_count` locals, and one for the return place.
174 local_decls.len() >= arg_count + 1,
175 "expected at least {} locals, got {}",
181 phase: MirPhase::Build,
185 generator_drop: None,
186 generator_layout: None,
189 user_type_annotations,
194 predecessors_cache: None,
195 control_flow_destroyed,
200 pub fn basic_blocks(&self) -> &IndexVec<BasicBlock, BasicBlockData<'tcx>> {
205 pub fn basic_blocks_mut(&mut self) -> &mut IndexVec<BasicBlock, BasicBlockData<'tcx>> {
206 &mut self.basic_blocks
209 pub fn basic_block_terminator_opt_mut(
210 &mut self, bb: BasicBlock
211 ) -> &mut Option<Terminator<'tcx>> {
212 // FIXME we should look into improving the cache invalidation
213 self.predecessors_cache = None;
214 &mut self.basic_blocks[bb].terminator
217 pub fn basic_block_terminator_mut(&mut self, bb: BasicBlock) -> &mut Terminator<'tcx> {
218 // FIXME we should look into improving the cache invalidation
219 self.predecessors_cache = None;
220 self.basic_blocks[bb].terminator_mut()
224 pub fn basic_blocks_and_local_decls_mut(
226 ) -> (&mut IndexVec<BasicBlock, BasicBlockData<'tcx>>, &mut LocalDecls<'tcx>) {
227 (&mut self.basic_blocks, &mut self.local_decls)
231 pub fn unwrap_predecessors(&self) -> &IndexVec<BasicBlock, Vec<BasicBlock>> {
232 assert!(self.predecessors_cache.is_some());
233 self.predecessors_cache.as_ref().unwrap()
237 /// This will recompute the predecessors cache if it is not available
238 pub fn predecessors(&mut self) -> &IndexVec<BasicBlock, Vec<BasicBlock>> {
239 if self.predecessors_cache.is_none() {
240 self.predecessors_cache = Some(self.calculate_predecessors())
243 self.predecessors_cache.as_ref().unwrap()
246 fn calculate_predecessors(&self) -> IndexVec<BasicBlock, Vec<BasicBlock>> {
247 let mut result = IndexVec::from_elem(vec![], self.basic_blocks());
248 for (bb, data) in self.basic_blocks().iter_enumerated() {
249 if let Some(ref term) = data.terminator {
250 for &tgt in term.successors() {
251 result[tgt].push(bb);
260 pub fn predecessors_for(&self, bb: BasicBlock) -> &[BasicBlock] {
261 // FIXME(nashenas88) could this be predecessors sometimes too?
262 &self.unwrap_predecessors()[bb]
266 pub fn predecessor_locations(&self, loc: Location) -> impl Iterator<Item = Location> + '_ {
267 let if_zero_locations = if loc.statement_index == 0 {
268 let predecessor_blocks = self.predecessors_for(loc.block);
269 let num_predecessor_blocks = predecessor_blocks.len();
271 (0..num_predecessor_blocks)
272 .map(move |i| predecessor_blocks[i])
273 .map(move |bb| self.terminator_loc(bb)),
279 let if_not_zero_locations = if loc.statement_index == 0 {
282 Some(Location { block: loc.block, statement_index: loc.statement_index - 1 })
285 if_zero_locations.into_iter().flatten().chain(if_not_zero_locations)
289 pub fn dominators(&self) -> Dominators<BasicBlock> {
293 /// Returns `true` if a cycle exists in the control-flow graph that is reachable from the
295 pub fn is_cfg_cyclic(&self) -> bool {
296 graph::is_cyclic(self)
300 pub fn local_kind(&self, local: Local) -> LocalKind {
301 let index = local.as_usize();
304 self.local_decls[local].mutability == Mutability::Mut,
305 "return place should be mutable"
308 LocalKind::ReturnPointer
309 } else if index < self.arg_count + 1 {
311 } else if self.local_decls[local].is_user_variable() {
318 /// Returns an iterator over all temporaries.
320 pub fn temps_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
321 (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
322 let local = Local::new(index);
323 if self.local_decls[local].is_user_variable() {
331 /// Returns an iterator over all user-declared locals.
333 pub fn vars_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
334 (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
335 let local = Local::new(index);
336 if self.local_decls[local].is_user_variable() {
344 /// Returns an iterator over all user-declared mutable locals.
346 pub fn mut_vars_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
347 (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
348 let local = Local::new(index);
349 let decl = &self.local_decls[local];
350 if decl.is_user_variable() && decl.mutability == Mutability::Mut {
358 /// Returns an iterator over all user-declared mutable arguments and locals.
360 pub fn mut_vars_and_args_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
361 (1..self.local_decls.len()).filter_map(move |index| {
362 let local = Local::new(index);
363 let decl = &self.local_decls[local];
364 if (decl.is_user_variable() || index < self.arg_count + 1)
365 && decl.mutability == Mutability::Mut
374 /// Returns an iterator over all function arguments.
376 pub fn args_iter(&self) -> impl Iterator<Item = Local> {
377 let arg_count = self.arg_count;
378 (1..=arg_count).map(Local::new)
381 /// Returns an iterator over all user-defined variables and compiler-generated temporaries (all
382 /// locals that are neither arguments nor the return place).
384 pub fn vars_and_temps_iter(&self) -> impl Iterator<Item = Local> {
385 let arg_count = self.arg_count;
386 let local_count = self.local_decls.len();
387 (arg_count + 1..local_count).map(Local::new)
390 /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
391 /// invalidating statement indices in `Location`s.
392 pub fn make_statement_nop(&mut self, location: Location) {
393 let block = &mut self[location.block];
394 debug_assert!(location.statement_index < block.statements.len());
395 block.statements[location.statement_index].make_nop()
398 /// Returns the source info associated with `location`.
399 pub fn source_info(&self, location: Location) -> &SourceInfo {
400 let block = &self[location.block];
401 let stmts = &block.statements;
402 let idx = location.statement_index;
403 if idx < stmts.len() {
404 &stmts[idx].source_info
406 assert_eq!(idx, stmts.len());
407 &block.terminator().source_info
411 /// Checks if `sub` is a sub scope of `sup`
412 pub fn is_sub_scope(&self, mut sub: SourceScope, sup: SourceScope) -> bool {
414 match self.source_scopes[sub].parent_scope {
415 None => return false,
422 /// Returns the return type; it always return first element from `local_decls` array.
423 pub fn return_ty(&self) -> Ty<'tcx> {
424 self.local_decls[RETURN_PLACE].ty
427 /// Gets the location of the terminator for the given block.
428 pub fn terminator_loc(&self, bb: BasicBlock) -> Location {
429 Location { block: bb, statement_index: self[bb].statements.len() }
433 #[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
436 /// Unsafe because of a PushUnsafeBlock
438 /// Unsafe because of an unsafe fn
440 /// Unsafe because of an `unsafe` block
441 ExplicitUnsafe(hir::HirId),
444 impl<'tcx> Index<BasicBlock> for Body<'tcx> {
445 type Output = BasicBlockData<'tcx>;
448 fn index(&self, index: BasicBlock) -> &BasicBlockData<'tcx> {
449 &self.basic_blocks()[index]
453 impl<'tcx> IndexMut<BasicBlock> for Body<'tcx> {
455 fn index_mut(&mut self, index: BasicBlock) -> &mut BasicBlockData<'tcx> {
456 &mut self.basic_blocks_mut()[index]
460 #[derive(Copy, Clone, Debug, HashStable, TypeFoldable)]
461 pub enum ClearCrossCrate<T> {
466 impl<T> ClearCrossCrate<T> {
467 pub fn as_ref(&'a self) -> ClearCrossCrate<&'a T> {
469 ClearCrossCrate::Clear => ClearCrossCrate::Clear,
470 ClearCrossCrate::Set(v) => ClearCrossCrate::Set(v),
474 pub fn assert_crate_local(self) -> T {
476 ClearCrossCrate::Clear => bug!("unwrapping cross-crate data"),
477 ClearCrossCrate::Set(v) => v,
482 impl<T: Encodable> rustc_serialize::UseSpecializedEncodable for ClearCrossCrate<T> {}
483 impl<T: Decodable> rustc_serialize::UseSpecializedDecodable for ClearCrossCrate<T> {}
485 /// Grouped information about the source code origin of a MIR entity.
486 /// Intended to be inspected by diagnostics and debuginfo.
487 /// Most passes can work with it as a whole, within a single function.
488 // The unofficial Cranelift backend, at least as of #65828, needs `SourceInfo` to implement `Eq` and
489 // `Hash`. Please ping @bjorn3 if removing them.
490 #[derive(Copy, Clone, Debug, Eq, PartialEq, RustcEncodable, RustcDecodable, Hash, HashStable)]
491 pub struct SourceInfo {
492 /// The source span for the AST pertaining to this MIR entity.
495 /// The source scope, keeping track of which bindings can be
496 /// seen by debuginfo, active lint levels, `unsafe {...}`, etc.
497 pub scope: SourceScope,
500 ///////////////////////////////////////////////////////////////////////////
501 // Mutability and borrow kinds
503 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
504 pub enum Mutability {
509 impl From<Mutability> for hir::Mutability {
510 fn from(m: Mutability) -> Self {
512 Mutability::Mut => hir::Mutability::Mutable,
513 Mutability::Not => hir::Mutability::Immutable,
519 Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, HashStable,
521 pub enum BorrowKind {
522 /// Data must be immutable and is aliasable.
525 /// The immediately borrowed place must be immutable, but projections from
526 /// it don't need to be. For example, a shallow borrow of `a.b` doesn't
527 /// conflict with a mutable borrow of `a.b.c`.
529 /// This is used when lowering matches: when matching on a place we want to
530 /// ensure that place have the same value from the start of the match until
531 /// an arm is selected. This prevents this code from compiling:
533 /// let mut x = &Some(0);
536 /// Some(_) if { x = &None; false } => (),
540 /// This can't be a shared borrow because mutably borrowing (*x as Some).0
541 /// should not prevent `if let None = x { ... }`, for example, because the
542 /// mutating `(*x as Some).0` can't affect the discriminant of `x`.
543 /// We can also report errors with this kind of borrow differently.
546 /// Data must be immutable but not aliasable. This kind of borrow
547 /// cannot currently be expressed by the user and is used only in
548 /// implicit closure bindings. It is needed when the closure is
549 /// borrowing or mutating a mutable referent, e.g.:
551 /// let x: &mut isize = ...;
552 /// let y = || *x += 5;
554 /// If we were to try to translate this closure into a more explicit
555 /// form, we'd encounter an error with the code as written:
557 /// struct Env { x: & &mut isize }
558 /// let x: &mut isize = ...;
559 /// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn
560 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
562 /// This is then illegal because you cannot mutate an `&mut` found
563 /// in an aliasable location. To solve, you'd have to translate with
564 /// an `&mut` borrow:
566 /// struct Env { x: & &mut isize }
567 /// let x: &mut isize = ...;
568 /// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
569 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
571 /// Now the assignment to `**env.x` is legal, but creating a
572 /// mutable pointer to `x` is not because `x` is not mutable. We
573 /// could fix this by declaring `x` as `let mut x`. This is ok in
574 /// user code, if awkward, but extra weird for closures, since the
575 /// borrow is hidden.
577 /// So we introduce a "unique imm" borrow -- the referent is
578 /// immutable, but not aliasable. This solves the problem. For
579 /// simplicity, we don't give users the way to express this
580 /// borrow, it's just used when translating closures.
583 /// Data is mutable and not aliasable.
585 /// `true` if this borrow arose from method-call auto-ref
586 /// (i.e., `adjustment::Adjust::Borrow`).
587 allow_two_phase_borrow: bool,
592 pub fn allows_two_phase_borrow(&self) -> bool {
594 BorrowKind::Shared | BorrowKind::Shallow | BorrowKind::Unique => false,
595 BorrowKind::Mut { allow_two_phase_borrow } => allow_two_phase_borrow,
600 ///////////////////////////////////////////////////////////////////////////
601 // Variables and temps
603 rustc_index::newtype_index! {
606 DEBUG_FORMAT = "_{}",
607 const RETURN_PLACE = 0,
611 impl Atom for Local {
612 fn index(self) -> usize {
617 /// Classifies locals into categories. See `Body::local_kind`.
618 #[derive(PartialEq, Eq, Debug, HashStable)]
620 /// User-declared variable binding.
622 /// Compiler-introduced temporary.
624 /// Function argument.
626 /// Location of function's return value.
630 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
631 pub struct VarBindingForm<'tcx> {
632 /// Is variable bound via `x`, `mut x`, `ref x`, or `ref mut x`?
633 pub binding_mode: ty::BindingMode,
634 /// If an explicit type was provided for this variable binding,
635 /// this holds the source Span of that type.
637 /// NOTE: if you want to change this to a `HirId`, be wary that
638 /// doing so breaks incremental compilation (as of this writing),
639 /// while a `Span` does not cause our tests to fail.
640 pub opt_ty_info: Option<Span>,
641 /// Place of the RHS of the =, or the subject of the `match` where this
642 /// variable is initialized. None in the case of `let PATTERN;`.
643 /// Some((None, ..)) in the case of and `let [mut] x = ...` because
644 /// (a) the right-hand side isn't evaluated as a place expression.
645 /// (b) it gives a way to separate this case from the remaining cases
647 pub opt_match_place: Option<(Option<Place<'tcx>>, Span)>,
648 /// The span of the pattern in which this variable was bound.
652 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
653 pub enum BindingForm<'tcx> {
654 /// This is a binding for a non-`self` binding, or a `self` that has an explicit type.
655 Var(VarBindingForm<'tcx>),
656 /// Binding for a `self`/`&self`/`&mut self` binding where the type is implicit.
657 ImplicitSelf(ImplicitSelfKind),
658 /// Reference used in a guard expression to ensure immutability.
662 /// Represents what type of implicit self a function has, if any.
663 #[derive(Clone, Copy, PartialEq, Debug, RustcEncodable, RustcDecodable, HashStable)]
664 pub enum ImplicitSelfKind {
665 /// Represents a `fn x(self);`.
667 /// Represents a `fn x(mut self);`.
669 /// Represents a `fn x(&self);`.
671 /// Represents a `fn x(&mut self);`.
673 /// Represents when a function does not have a self argument or
674 /// when a function has a `self: X` argument.
678 CloneTypeFoldableAndLiftImpls! { BindingForm<'tcx>, }
680 mod binding_form_impl {
681 use crate::ich::StableHashingContext;
682 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
684 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for super::BindingForm<'tcx> {
685 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
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, HashStable)]
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,
718 /// This can be a binding declared by the user, a temporary inserted by the compiler, a function
719 /// argument, or the return place.
720 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
721 pub struct LocalDecl<'tcx> {
722 /// Whether this is a mutable minding (i.e., `let x` or `let mut x`).
724 /// Temporaries and the return place are always mutable.
725 pub mutability: Mutability,
727 // FIXME(matthewjasper) Don't store in this in `Body`
728 pub local_info: LocalInfo<'tcx>,
730 /// `true` if this is an internal local.
732 /// These locals are not based on types in the source code and are only used
733 /// for a few desugarings at the moment.
735 /// The generator transformation will sanity check the locals which are live
736 /// across a suspension point against the type components of the generator
737 /// which type checking knows are live across a suspension point. We need to
738 /// flag drop flags to avoid triggering this check as they are introduced
741 /// Unsafety checking will also ignore dereferences of these locals,
742 /// so they can be used for raw pointers only used in a desugaring.
744 /// This should be sound because the drop flags are fully algebraic, and
745 /// therefore don't affect the OIBIT or outlives properties of the
749 /// If this local is a temporary and `is_block_tail` is `Some`,
750 /// then it is a temporary created for evaluation of some
751 /// subexpression of some block's tail expression (with no
752 /// intervening statement context).
753 // FIXME(matthewjasper) Don't store in this in `Body`
754 pub is_block_tail: Option<BlockTailInfo>,
756 /// The type of this local.
759 /// If the user manually ascribed a type to this variable,
760 /// e.g., via `let x: T`, then we carry that type here. The MIR
761 /// borrow checker needs this information since it can affect
762 /// region inference.
763 // FIXME(matthewjasper) Don't store in this in `Body`
764 pub user_ty: UserTypeProjections,
766 /// The *syntactic* (i.e., not visibility) source scope the local is defined
767 /// in. If the local was defined in a let-statement, this
768 /// is *within* the let-statement, rather than outside
771 /// This is needed because the visibility source scope of locals within
772 /// a let-statement is weird.
774 /// The reason is that we want the local to be *within* the let-statement
775 /// for lint purposes, but we want the local to be *after* the let-statement
776 /// for names-in-scope purposes.
778 /// That's it, if we have a let-statement like the one in this
782 /// fn foo(x: &str) {
783 /// #[allow(unused_mut)]
784 /// let mut x: u32 = { // <- one unused mut
785 /// let mut y: u32 = x.parse().unwrap();
792 /// Then, from a lint point of view, the declaration of `x: u32`
793 /// (and `y: u32`) are within the `#[allow(unused_mut)]` scope - the
794 /// lint scopes are the same as the AST/HIR nesting.
796 /// However, from a name lookup point of view, the scopes look more like
797 /// as if the let-statements were `match` expressions:
800 /// fn foo(x: &str) {
802 /// match x.parse().unwrap() {
811 /// We care about the name-lookup scopes for debuginfo - if the
812 /// debuginfo instruction pointer is at the call to `x.parse()`, we
813 /// want `x` to refer to `x: &str`, but if it is at the call to
814 /// `drop(x)`, we want it to refer to `x: u32`.
816 /// To allow both uses to work, we need to have more than a single scope
817 /// for a local. We have the `source_info.scope` represent the "syntactic"
818 /// lint scope (with a variable being under its let block) while the
819 /// `var_debug_info.source_info.scope` represents the "local variable"
820 /// scope (where the "rest" of a block is under all prior let-statements).
822 /// The end result looks like this:
826 /// │{ argument x: &str }
828 /// │ │{ #[allow(unused_mut)] } // This is actually split into 2 scopes
829 /// │ │ // in practice because I'm lazy.
831 /// │ │← x.source_info.scope
832 /// │ │← `x.parse().unwrap()`
834 /// │ │ │← y.source_info.scope
836 /// │ │ │{ let y: u32 }
838 /// │ │ │← y.var_debug_info.source_info.scope
841 /// │ │{ let x: u32 }
842 /// │ │← x.var_debug_info.source_info.scope
843 /// │ │← `drop(x)` // This accesses `x: u32`.
845 pub source_info: SourceInfo,
848 /// Extra information about a local that's used for diagnostics.
849 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
850 pub enum LocalInfo<'tcx> {
851 /// A user-defined local variable or function parameter
853 /// The `BindingForm` is solely used for local diagnostics when generating
854 /// warnings/errors when compiling the current crate, and therefore it need
855 /// not be visible across crates.
856 User(ClearCrossCrate<BindingForm<'tcx>>),
857 /// A temporary created that references the static with the given `DefId`.
858 StaticRef { def_id: DefId, is_thread_local: bool },
859 /// Any other temporary, the return place, or an anonymous function parameter.
863 impl<'tcx> LocalDecl<'tcx> {
864 /// Returns `true` only if local is a binding that can itself be
865 /// made mutable via the addition of the `mut` keyword, namely
866 /// something like the occurrences of `x` in:
867 /// - `fn foo(x: Type) { ... }`,
869 /// - or `match ... { C(x) => ... }`
870 pub fn can_be_made_mutable(&self) -> bool {
871 match self.local_info {
872 LocalInfo::User(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
873 binding_mode: ty::BindingMode::BindByValue(_),
880 ClearCrossCrate::Set(BindingForm::ImplicitSelf(ImplicitSelfKind::Imm)),
887 /// Returns `true` if local is definitely not a `ref ident` or
888 /// `ref mut ident` binding. (Such bindings cannot be made into
889 /// mutable bindings, but the inverse does not necessarily hold).
890 pub fn is_nonref_binding(&self) -> bool {
891 match self.local_info {
892 LocalInfo::User(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
893 binding_mode: ty::BindingMode::BindByValue(_),
899 LocalInfo::User(ClearCrossCrate::Set(BindingForm::ImplicitSelf(_))) => true,
905 /// Returns `true` if this variable is a named variable or function
906 /// parameter declared by the user.
908 pub fn is_user_variable(&self) -> bool {
909 match self.local_info {
910 LocalInfo::User(_) => true,
915 /// Returns `true` if this is a reference to a variable bound in a `match`
916 /// expression that is used to access said variable for the guard of the
918 pub fn is_ref_for_guard(&self) -> bool {
919 match self.local_info {
920 LocalInfo::User(ClearCrossCrate::Set(BindingForm::RefForGuard)) => true,
925 /// Returns `Some` if this is a reference to a static item that is used to
926 /// access that static
927 pub fn is_ref_to_static(&self) -> bool {
928 match self.local_info {
929 LocalInfo::StaticRef { .. } => true,
934 /// Returns `Some` if this is a reference to a static item that is used to
935 /// access that static
936 pub fn is_ref_to_thread_local(&self) -> bool {
937 match self.local_info {
938 LocalInfo::StaticRef { is_thread_local, .. } => is_thread_local,
943 /// Returns `true` is the local is from a compiler desugaring, e.g.,
944 /// `__next` from a `for` loop.
946 pub fn from_compiler_desugaring(&self) -> bool {
947 self.source_info.span.desugaring_kind().is_some()
950 /// Creates a new `LocalDecl` for a temporary.
952 pub fn new_temp(ty: Ty<'tcx>, span: Span) -> Self {
953 Self::new_local(ty, Mutability::Mut, false, span)
956 /// Converts `self` into same `LocalDecl` except tagged as immutable.
958 pub fn immutable(mut self) -> Self {
959 self.mutability = Mutability::Not;
963 /// Converts `self` into same `LocalDecl` except tagged as internal temporary.
965 pub fn block_tail(mut self, info: BlockTailInfo) -> Self {
966 assert!(self.is_block_tail.is_none());
967 self.is_block_tail = Some(info);
971 /// Creates a new `LocalDecl` for a internal temporary.
973 pub fn new_internal(ty: Ty<'tcx>, span: Span) -> Self {
974 Self::new_local(ty, Mutability::Mut, true, span)
978 fn new_local(ty: Ty<'tcx>, mutability: Mutability, internal: bool, span: Span) -> Self {
982 user_ty: UserTypeProjections::none(),
983 source_info: SourceInfo { span, scope: OUTERMOST_SOURCE_SCOPE },
985 local_info: LocalInfo::Other,
990 /// Builds a `LocalDecl` for the return place.
992 /// This must be inserted into the `local_decls` list as the first local.
994 pub fn new_return_place(return_ty: Ty<'_>, span: Span) -> LocalDecl<'_> {
996 mutability: Mutability::Mut,
998 user_ty: UserTypeProjections::none(),
999 source_info: SourceInfo { span, scope: OUTERMOST_SOURCE_SCOPE },
1001 is_block_tail: None,
1002 local_info: LocalInfo::Other,
1007 /// Debug information pertaining to a user variable.
1008 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
1009 pub struct VarDebugInfo<'tcx> {
1012 /// Source info of the user variable, including the scope
1013 /// within which the variable is visible (to debuginfo)
1014 /// (see `LocalDecl`'s `source_info` field for more details).
1015 pub source_info: SourceInfo,
1017 /// Where the data for this user variable is to be found.
1018 /// NOTE(eddyb) There's an unenforced invariant that this `Place` is
1019 /// based on a `Local`, not a `Static`, and contains no indexing.
1020 pub place: Place<'tcx>,
1023 ///////////////////////////////////////////////////////////////////////////
1026 rustc_index::newtype_index! {
1027 pub struct BasicBlock {
1029 DEBUG_FORMAT = "bb{}",
1030 const START_BLOCK = 0,
1035 pub fn start_location(self) -> Location {
1036 Location { block: self, statement_index: 0 }
1040 CloneTypeFoldableAndLiftImpls!{ BasicBlock, }
1042 ///////////////////////////////////////////////////////////////////////////
1043 // BasicBlockData and Terminator
1045 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
1046 pub struct BasicBlockData<'tcx> {
1047 /// List of statements in this block.
1048 pub statements: Vec<Statement<'tcx>>,
1050 /// Terminator for this block.
1052 /// N.B., this should generally ONLY be `None` during construction.
1053 /// Therefore, you should generally access it via the
1054 /// `terminator()` or `terminator_mut()` methods. The only
1055 /// exception is that certain passes, such as `simplify_cfg`, swap
1056 /// out the terminator temporarily with `None` while they continue
1057 /// to recurse over the set of basic blocks.
1058 pub terminator: Option<Terminator<'tcx>>,
1060 /// If true, this block lies on an unwind path. This is used
1061 /// during codegen where distinct kinds of basic blocks may be
1062 /// generated (particularly for MSVC cleanup). Unwind blocks must
1063 /// only branch to other unwind blocks.
1064 pub is_cleanup: bool,
1067 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
1068 pub struct Terminator<'tcx> {
1069 pub source_info: SourceInfo,
1070 pub kind: TerminatorKind<'tcx>,
1073 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable, PartialEq)]
1074 pub enum TerminatorKind<'tcx> {
1075 /// Block should have one successor in the graph; we jump there.
1076 Goto { target: BasicBlock },
1078 /// Operand evaluates to an integer; jump depending on its value
1079 /// to one of the targets, and otherwise fallback to `otherwise`.
1081 /// The discriminant value being tested.
1082 discr: Operand<'tcx>,
1084 /// The type of value being tested.
1085 switch_ty: Ty<'tcx>,
1087 /// Possible values. The locations to branch to in each case
1088 /// are found in the corresponding indices from the `targets` vector.
1089 values: Cow<'tcx, [u128]>,
1091 /// Possible branch sites. The last element of this vector is used
1092 /// for the otherwise branch, so targets.len() == values.len() + 1
1095 // This invariant is quite non-obvious and also could be improved.
1096 // One way to make this invariant is to have something like this instead:
1098 // branches: Vec<(ConstInt, BasicBlock)>,
1099 // otherwise: Option<BasicBlock> // exhaustive if None
1101 // However we’ve decided to keep this as-is until we figure a case
1102 // where some other approach seems to be strictly better than other.
1103 targets: Vec<BasicBlock>,
1106 /// Indicates that the landing pad is finished and unwinding should
1107 /// continue. Emitted by `build::scope::diverge_cleanup`.
1110 /// Indicates that the landing pad is finished and that the process
1111 /// should abort. Used to prevent unwinding for foreign items.
1114 /// Indicates a normal return. The return place should have
1115 /// been filled in by now. This should occur at most once.
1118 /// Indicates a terminator that can never be reached.
1121 /// Drop the `Place`.
1122 Drop { location: Place<'tcx>, target: BasicBlock, unwind: Option<BasicBlock> },
1124 /// Drop the `Place` and assign the new value over it. This ensures
1125 /// that the assignment to `P` occurs *even if* the destructor for
1126 /// place unwinds. Its semantics are best explained by the
1131 /// DropAndReplace(P <- V, goto BB1, unwind BB2)
1139 /// Drop(P, goto BB1, unwind BB2)
1142 /// // P is now uninitialized
1146 /// // P is now uninitialized -- its dtor panicked
1151 location: Place<'tcx>,
1152 value: Operand<'tcx>,
1154 unwind: Option<BasicBlock>,
1157 /// Block ends with a call of a converging function.
1159 /// The function that’s being called.
1160 func: Operand<'tcx>,
1161 /// Arguments the function is called with.
1162 /// These are owned by the callee, which is free to modify them.
1163 /// This allows the memory occupied by "by-value" arguments to be
1164 /// reused across function calls without duplicating the contents.
1165 args: Vec<Operand<'tcx>>,
1166 /// Destination for the return value. If some, the call is converging.
1167 destination: Option<(Place<'tcx>, BasicBlock)>,
1168 /// Cleanups to be done if the call unwinds.
1169 cleanup: Option<BasicBlock>,
1170 /// `true` if this is from a call in HIR rather than from an overloaded
1171 /// operator. True for overloaded function call.
1172 from_hir_call: bool,
1175 /// Jump to the target if the condition has the expected value,
1176 /// otherwise panic with a message and a cleanup target.
1178 cond: Operand<'tcx>,
1180 msg: AssertMessage<'tcx>,
1182 cleanup: Option<BasicBlock>,
1185 /// A suspend point.
1187 /// The value to return.
1188 value: Operand<'tcx>,
1189 /// Where to resume to.
1191 /// Cleanup to be done if the generator is dropped at this suspend point.
1192 drop: Option<BasicBlock>,
1195 /// Indicates the end of the dropping of a generator.
1198 /// A block where control flow only ever takes one real path, but borrowck
1199 /// needs to be more conservative.
1201 /// The target normal control flow will take.
1202 real_target: BasicBlock,
1203 /// A block control flow could conceptually jump to, but won't in
1205 imaginary_target: BasicBlock,
1207 /// A terminator for blocks that only take one path in reality, but where we
1208 /// reserve the right to unwind in borrowck, even if it won't happen in practice.
1209 /// This can arise in infinite loops with no function calls for example.
1211 /// The target normal control flow will take.
1212 real_target: BasicBlock,
1213 /// The imaginary cleanup block link. This particular path will never be taken
1214 /// in practice, but in order to avoid fragility we want to always
1215 /// consider it in borrowck. We don't want to accept programs which
1216 /// pass borrowck only when `panic=abort` or some assertions are disabled
1217 /// due to release vs. debug mode builds. This needs to be an `Option` because
1218 /// of the `remove_noop_landing_pads` and `no_landing_pads` passes.
1219 unwind: Option<BasicBlock>,
1223 pub type Successors<'a> =
1224 iter::Chain<option::IntoIter<&'a BasicBlock>, slice::Iter<'a, BasicBlock>>;
1225 pub type SuccessorsMut<'a> =
1226 iter::Chain<option::IntoIter<&'a mut BasicBlock>, slice::IterMut<'a, BasicBlock>>;
1228 impl<'tcx> Terminator<'tcx> {
1229 pub fn successors(&self) -> Successors<'_> {
1230 self.kind.successors()
1233 pub fn successors_mut(&mut self) -> SuccessorsMut<'_> {
1234 self.kind.successors_mut()
1237 pub fn unwind(&self) -> Option<&Option<BasicBlock>> {
1241 pub fn unwind_mut(&mut self) -> Option<&mut Option<BasicBlock>> {
1242 self.kind.unwind_mut()
1246 impl<'tcx> TerminatorKind<'tcx> {
1249 cond: Operand<'tcx>,
1252 ) -> TerminatorKind<'tcx> {
1253 static BOOL_SWITCH_FALSE: &'static [u128] = &[0];
1254 TerminatorKind::SwitchInt {
1256 switch_ty: tcx.types.bool,
1257 values: From::from(BOOL_SWITCH_FALSE),
1258 targets: vec![f, t],
1262 pub fn successors(&self) -> Successors<'_> {
1263 use self::TerminatorKind::*;
1270 | Call { destination: None, cleanup: None, .. } => None.into_iter().chain(&[]),
1271 Goto { target: ref t }
1272 | Call { destination: None, cleanup: Some(ref t), .. }
1273 | Call { destination: Some((_, ref t)), cleanup: None, .. }
1274 | Yield { resume: ref t, drop: None, .. }
1275 | DropAndReplace { target: ref t, unwind: None, .. }
1276 | Drop { target: ref t, unwind: None, .. }
1277 | Assert { target: ref t, cleanup: None, .. }
1278 | FalseUnwind { real_target: ref t, unwind: None } => Some(t).into_iter().chain(&[]),
1279 Call { destination: Some((_, ref t)), cleanup: Some(ref u), .. }
1280 | Yield { resume: ref t, drop: Some(ref u), .. }
1281 | DropAndReplace { target: ref t, unwind: Some(ref u), .. }
1282 | Drop { target: ref t, unwind: Some(ref u), .. }
1283 | Assert { target: ref t, cleanup: Some(ref u), .. }
1284 | FalseUnwind { real_target: ref t, unwind: Some(ref u) } => {
1285 Some(t).into_iter().chain(slice::from_ref(u))
1287 SwitchInt { ref targets, .. } => None.into_iter().chain(&targets[..]),
1288 FalseEdges { ref real_target, ref imaginary_target } => {
1289 Some(real_target).into_iter().chain(slice::from_ref(imaginary_target))
1294 pub fn successors_mut(&mut self) -> SuccessorsMut<'_> {
1295 use self::TerminatorKind::*;
1302 | Call { destination: None, cleanup: None, .. } => None.into_iter().chain(&mut []),
1303 Goto { target: ref mut t }
1304 | Call { destination: None, cleanup: Some(ref mut t), .. }
1305 | Call { destination: Some((_, ref mut t)), cleanup: None, .. }
1306 | Yield { resume: ref mut t, drop: None, .. }
1307 | DropAndReplace { target: ref mut t, unwind: None, .. }
1308 | Drop { target: ref mut t, unwind: None, .. }
1309 | Assert { target: ref mut t, cleanup: None, .. }
1310 | FalseUnwind { real_target: ref mut t, unwind: None } => {
1311 Some(t).into_iter().chain(&mut [])
1313 Call { destination: Some((_, ref mut t)), cleanup: Some(ref mut u), .. }
1314 | Yield { resume: ref mut t, drop: Some(ref mut u), .. }
1315 | DropAndReplace { target: ref mut t, unwind: Some(ref mut u), .. }
1316 | Drop { target: ref mut t, unwind: Some(ref mut u), .. }
1317 | Assert { target: ref mut t, cleanup: Some(ref mut u), .. }
1318 | FalseUnwind { real_target: ref mut t, unwind: Some(ref mut u) } => {
1319 Some(t).into_iter().chain(slice::from_mut(u))
1321 SwitchInt { ref mut targets, .. } => None.into_iter().chain(&mut targets[..]),
1322 FalseEdges { ref mut real_target, ref mut imaginary_target } => {
1323 Some(real_target).into_iter().chain(slice::from_mut(imaginary_target))
1328 pub fn unwind(&self) -> Option<&Option<BasicBlock>> {
1330 TerminatorKind::Goto { .. }
1331 | TerminatorKind::Resume
1332 | TerminatorKind::Abort
1333 | TerminatorKind::Return
1334 | TerminatorKind::Unreachable
1335 | TerminatorKind::GeneratorDrop
1336 | TerminatorKind::Yield { .. }
1337 | TerminatorKind::SwitchInt { .. }
1338 | TerminatorKind::FalseEdges { .. } => None,
1339 TerminatorKind::Call { cleanup: ref unwind, .. }
1340 | TerminatorKind::Assert { cleanup: ref unwind, .. }
1341 | TerminatorKind::DropAndReplace { ref unwind, .. }
1342 | TerminatorKind::Drop { ref unwind, .. }
1343 | TerminatorKind::FalseUnwind { ref unwind, .. } => Some(unwind),
1347 pub fn unwind_mut(&mut self) -> Option<&mut Option<BasicBlock>> {
1349 TerminatorKind::Goto { .. }
1350 | TerminatorKind::Resume
1351 | TerminatorKind::Abort
1352 | TerminatorKind::Return
1353 | TerminatorKind::Unreachable
1354 | TerminatorKind::GeneratorDrop
1355 | TerminatorKind::Yield { .. }
1356 | TerminatorKind::SwitchInt { .. }
1357 | TerminatorKind::FalseEdges { .. } => None,
1358 TerminatorKind::Call { cleanup: ref mut unwind, .. }
1359 | TerminatorKind::Assert { cleanup: ref mut unwind, .. }
1360 | TerminatorKind::DropAndReplace { ref mut unwind, .. }
1361 | TerminatorKind::Drop { ref mut unwind, .. }
1362 | TerminatorKind::FalseUnwind { ref mut unwind, .. } => Some(unwind),
1367 impl<'tcx> BasicBlockData<'tcx> {
1368 pub fn new(terminator: Option<Terminator<'tcx>>) -> BasicBlockData<'tcx> {
1369 BasicBlockData { statements: vec![], terminator, is_cleanup: false }
1372 pub fn terminator_opt(&self) -> &Option<Terminator<'tcx>> {
1376 /// Accessor for terminator.
1378 /// Terminator may not be None after construction of the basic block is complete. This accessor
1379 /// provides a convenience way to reach the terminator.
1380 pub fn terminator(&self) -> &Terminator<'tcx> {
1381 self.terminator.as_ref().expect("invalid terminator state")
1384 // This cannot be public since changing the terminator will break the predecessors cache in Body
1385 // To do so outside of this module, use Body::basic_block_terminator_mut(BasicBlock)
1386 fn terminator_mut(&mut self) -> &mut Terminator<'tcx> {
1387 self.terminator.as_mut().expect("invalid terminator state")
1390 // This can be public since changing the kind will not break the predecessors cache in Body
1391 pub fn terminator_kind_mut(&mut self) -> &mut TerminatorKind<'tcx> {
1392 &mut self.terminator_mut().kind
1395 pub fn retain_statements<F>(&mut self, mut f: F)
1397 F: FnMut(&mut Statement<'_>) -> bool,
1399 for s in &mut self.statements {
1406 pub fn expand_statements<F, I>(&mut self, mut f: F)
1408 F: FnMut(&mut Statement<'tcx>) -> Option<I>,
1409 I: iter::TrustedLen<Item = Statement<'tcx>>,
1411 // Gather all the iterators we'll need to splice in, and their positions.
1412 let mut splices: Vec<(usize, I)> = vec![];
1413 let mut extra_stmts = 0;
1414 for (i, s) in self.statements.iter_mut().enumerate() {
1415 if let Some(mut new_stmts) = f(s) {
1416 if let Some(first) = new_stmts.next() {
1417 // We can already store the first new statement.
1420 // Save the other statements for optimized splicing.
1421 let remaining = new_stmts.size_hint().0;
1423 splices.push((i + 1 + extra_stmts, new_stmts));
1424 extra_stmts += remaining;
1432 // Splice in the new statements, from the end of the block.
1433 // FIXME(eddyb) This could be more efficient with a "gap buffer"
1434 // where a range of elements ("gap") is left uninitialized, with
1435 // splicing adding new elements to the end of that gap and moving
1436 // existing elements from before the gap to the end of the gap.
1437 // For now, this is safe code, emulating a gap but initializing it.
1438 let mut gap = self.statements.len()..self.statements.len() + extra_stmts;
1439 self.statements.resize(
1442 source_info: SourceInfo { span: DUMMY_SP, scope: OUTERMOST_SOURCE_SCOPE },
1443 kind: StatementKind::Nop,
1446 for (splice_start, new_stmts) in splices.into_iter().rev() {
1447 let splice_end = splice_start + new_stmts.size_hint().0;
1448 while gap.end > splice_end {
1451 self.statements.swap(gap.start, gap.end);
1453 self.statements.splice(splice_start..splice_end, new_stmts);
1454 gap.end = splice_start;
1458 pub fn visitable(&self, index: usize) -> &dyn MirVisitable<'tcx> {
1459 if index < self.statements.len() {
1460 &self.statements[index]
1467 impl<'tcx> Debug for TerminatorKind<'tcx> {
1468 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1469 self.fmt_head(fmt)?;
1470 let successor_count = self.successors().count();
1471 let labels = self.fmt_successor_labels();
1472 assert_eq!(successor_count, labels.len());
1474 match successor_count {
1477 1 => write!(fmt, " -> {:?}", self.successors().nth(0).unwrap()),
1480 write!(fmt, " -> [")?;
1481 for (i, target) in self.successors().enumerate() {
1485 write!(fmt, "{}: {:?}", labels[i], target)?;
1493 impl<'tcx> TerminatorKind<'tcx> {
1494 /// Writes the "head" part of the terminator; that is, its name and the data it uses to pick the
1495 /// successor basic block, if any. The only information not included is the list of possible
1496 /// successors, which may be rendered differently between the text and the graphviz format.
1497 pub fn fmt_head<W: Write>(&self, fmt: &mut W) -> fmt::Result {
1498 use self::TerminatorKind::*;
1500 Goto { .. } => write!(fmt, "goto"),
1501 SwitchInt { discr: ref place, .. } => write!(fmt, "switchInt({:?})", place),
1502 Return => write!(fmt, "return"),
1503 GeneratorDrop => write!(fmt, "generator_drop"),
1504 Resume => write!(fmt, "resume"),
1505 Abort => write!(fmt, "abort"),
1506 Yield { ref value, .. } => write!(fmt, "_1 = suspend({:?})", value),
1507 Unreachable => write!(fmt, "unreachable"),
1508 Drop { ref location, .. } => write!(fmt, "drop({:?})", location),
1509 DropAndReplace { ref location, ref value, .. } => {
1510 write!(fmt, "replace({:?} <- {:?})", location, value)
1512 Call { ref func, ref args, ref destination, .. } => {
1513 if let Some((ref destination, _)) = *destination {
1514 write!(fmt, "{:?} = ", destination)?;
1516 write!(fmt, "{:?}(", func)?;
1517 for (index, arg) in args.iter().enumerate() {
1521 write!(fmt, "{:?}", arg)?;
1525 Assert { ref cond, expected, ref msg, .. } => {
1526 write!(fmt, "assert(")?;
1530 write!(fmt, "{:?}, \"{:?}\")", cond, msg)
1532 FalseEdges { .. } => write!(fmt, "falseEdges"),
1533 FalseUnwind { .. } => write!(fmt, "falseUnwind"),
1537 /// Returns the list of labels for the edges to the successor basic blocks.
1538 pub fn fmt_successor_labels(&self) -> Vec<Cow<'static, str>> {
1539 use self::TerminatorKind::*;
1541 Return | Resume | Abort | Unreachable | GeneratorDrop => vec![],
1542 Goto { .. } => vec!["".into()],
1543 SwitchInt { ref values, switch_ty, .. } => ty::tls::with(|tcx| {
1544 let param_env = ty::ParamEnv::empty();
1545 let switch_ty = tcx.lift(&switch_ty).unwrap();
1546 let size = tcx.layout_of(param_env.and(switch_ty)).unwrap().size;
1550 ty::Const::from_scalar(
1552 Scalar::from_uint(u, size).into(),
1558 .chain(iter::once("otherwise".into()))
1561 Call { destination: Some(_), cleanup: Some(_), .. } => {
1562 vec!["return".into(), "unwind".into()]
1564 Call { destination: Some(_), cleanup: None, .. } => vec!["return".into()],
1565 Call { destination: None, cleanup: Some(_), .. } => vec!["unwind".into()],
1566 Call { destination: None, cleanup: None, .. } => vec![],
1567 Yield { drop: Some(_), .. } => vec!["resume".into(), "drop".into()],
1568 Yield { drop: None, .. } => vec!["resume".into()],
1569 DropAndReplace { unwind: None, .. } | Drop { unwind: None, .. } => {
1570 vec!["return".into()]
1572 DropAndReplace { unwind: Some(_), .. } | Drop { unwind: Some(_), .. } => {
1573 vec!["return".into(), "unwind".into()]
1575 Assert { cleanup: None, .. } => vec!["".into()],
1576 Assert { .. } => vec!["success".into(), "unwind".into()],
1577 FalseEdges { .. } => vec!["real".into(), "imaginary".into()],
1578 FalseUnwind { unwind: Some(_), .. } => vec!["real".into(), "cleanup".into()],
1579 FalseUnwind { unwind: None, .. } => vec!["real".into()],
1584 ///////////////////////////////////////////////////////////////////////////
1587 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
1588 pub struct Statement<'tcx> {
1589 pub source_info: SourceInfo,
1590 pub kind: StatementKind<'tcx>,
1593 // `Statement` is used a lot. Make sure it doesn't unintentionally get bigger.
1594 #[cfg(target_arch = "x86_64")]
1595 static_assert_size!(Statement<'_>, 32);
1597 impl Statement<'_> {
1598 /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
1599 /// invalidating statement indices in `Location`s.
1600 pub fn make_nop(&mut self) {
1601 self.kind = StatementKind::Nop
1604 /// Changes a statement to a nop and returns the original statement.
1605 pub fn replace_nop(&mut self) -> Self {
1607 source_info: self.source_info,
1608 kind: mem::replace(&mut self.kind, StatementKind::Nop),
1613 #[derive(Clone, Debug, PartialEq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
1614 pub enum StatementKind<'tcx> {
1615 /// Write the RHS Rvalue to the LHS Place.
1616 Assign(Box<(Place<'tcx>, Rvalue<'tcx>)>),
1618 /// This represents all the reading that a pattern match may do
1619 /// (e.g., inspecting constants and discriminant values), and the
1620 /// kind of pattern it comes from. This is in order to adapt potential
1621 /// error messages to these specific patterns.
1623 /// Note that this also is emitted for regular `let` bindings to ensure that locals that are
1624 /// never accessed still get some sanity checks for, e.g., `let x: ! = ..;`
1625 FakeRead(FakeReadCause, Box<Place<'tcx>>),
1627 /// Write the discriminant for a variant to the enum Place.
1628 SetDiscriminant { place: Box<Place<'tcx>>, variant_index: VariantIdx },
1630 /// Start a live range for the storage of the local.
1633 /// End the current live range for the storage of the local.
1636 /// Executes a piece of inline Assembly. Stored in a Box to keep the size
1637 /// of `StatementKind` low.
1638 InlineAsm(Box<InlineAsm<'tcx>>),
1640 /// Retag references in the given place, ensuring they got fresh tags. This is
1641 /// part of the Stacked Borrows model. These statements are currently only interpreted
1642 /// by miri and only generated when "-Z mir-emit-retag" is passed.
1643 /// See <https://internals.rust-lang.org/t/stacked-borrows-an-aliasing-model-for-rust/8153/>
1644 /// for more details.
1645 Retag(RetagKind, Box<Place<'tcx>>),
1647 /// Encodes a user's type ascription. These need to be preserved
1648 /// intact so that NLL can respect them. For example:
1652 /// The effect of this annotation is to relate the type `T_y` of the place `y`
1653 /// to the user-given type `T`. The effect depends on the specified variance:
1655 /// - `Covariant` -- requires that `T_y <: T`
1656 /// - `Contravariant` -- requires that `T_y :> T`
1657 /// - `Invariant` -- requires that `T_y == T`
1658 /// - `Bivariant` -- no effect
1659 AscribeUserType(Box<(Place<'tcx>, UserTypeProjection)>, ty::Variance),
1661 /// No-op. Useful for deleting instructions without affecting statement indices.
1665 /// Describes what kind of retag is to be performed.
1666 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, PartialEq, Eq, HashStable)]
1667 pub enum RetagKind {
1668 /// The initial retag when entering a function.
1670 /// Retag preparing for a two-phase borrow.
1672 /// Retagging raw pointers.
1674 /// A "normal" retag.
1678 /// The `FakeReadCause` describes the type of pattern why a FakeRead statement exists.
1679 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable, PartialEq)]
1680 pub enum FakeReadCause {
1681 /// Inject a fake read of the borrowed input at the end of each guards
1684 /// This should ensure that you cannot change the variant for an enum while
1685 /// you are in the midst of matching on it.
1688 /// `let x: !; match x {}` doesn't generate any read of x so we need to
1689 /// generate a read of x to check that it is initialized and safe.
1692 /// A fake read of the RefWithinGuard version of a bind-by-value variable
1693 /// in a match guard to ensure that it's value hasn't change by the time
1694 /// we create the OutsideGuard version.
1697 /// Officially, the semantics of
1699 /// `let pattern = <expr>;`
1701 /// is that `<expr>` is evaluated into a temporary and then this temporary is
1702 /// into the pattern.
1704 /// However, if we see the simple pattern `let var = <expr>`, we optimize this to
1705 /// evaluate `<expr>` directly into the variable `var`. This is mostly unobservable,
1706 /// but in some cases it can affect the borrow checker, as in #53695.
1707 /// Therefore, we insert a "fake read" here to ensure that we get
1708 /// appropriate errors.
1711 /// If we have an index expression like
1713 /// (*x)[1][{ x = y; 4}]
1715 /// then the first bounds check is invalidated when we evaluate the second
1716 /// index expression. Thus we create a fake borrow of `x` across the second
1717 /// indexer, which will cause a borrow check error.
1721 #[derive(Clone, Debug, PartialEq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
1722 pub struct InlineAsm<'tcx> {
1723 pub asm: hir::InlineAsmInner,
1724 pub outputs: Box<[Place<'tcx>]>,
1725 pub inputs: Box<[(Span, Operand<'tcx>)]>,
1728 impl Debug for Statement<'_> {
1729 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1730 use self::StatementKind::*;
1732 Assign(box(ref place, ref rv)) => write!(fmt, "{:?} = {:?}", place, rv),
1733 FakeRead(ref cause, ref place) => write!(fmt, "FakeRead({:?}, {:?})", cause, place),
1734 Retag(ref kind, ref place) => write!(
1738 RetagKind::FnEntry => "[fn entry] ",
1739 RetagKind::TwoPhase => "[2phase] ",
1740 RetagKind::Raw => "[raw] ",
1741 RetagKind::Default => "",
1745 StorageLive(ref place) => write!(fmt, "StorageLive({:?})", place),
1746 StorageDead(ref place) => write!(fmt, "StorageDead({:?})", place),
1747 SetDiscriminant { ref place, variant_index } => {
1748 write!(fmt, "discriminant({:?}) = {:?}", place, variant_index)
1750 InlineAsm(ref asm) => {
1751 write!(fmt, "asm!({:?} : {:?} : {:?})", asm.asm, asm.outputs, asm.inputs)
1753 AscribeUserType(box(ref place, ref c_ty), ref variance) => {
1754 write!(fmt, "AscribeUserType({:?}, {:?}, {:?})", place, variance, c_ty)
1756 Nop => write!(fmt, "nop"),
1761 ///////////////////////////////////////////////////////////////////////////
1764 /// A path to a value; something that can be evaluated without
1765 /// changing or disturbing program state.
1767 Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, HashStable,
1769 pub struct Place<'tcx> {
1770 pub base: PlaceBase<'tcx>,
1772 /// projection out of a place (access a field, deref a pointer, etc)
1773 pub projection: &'tcx List<PlaceElem<'tcx>>,
1776 impl<'tcx> rustc_serialize::UseSpecializedDecodable for Place<'tcx> {}
1779 Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, HashStable,
1781 pub enum PlaceBase<'tcx> {
1785 /// static or static mut variable
1786 Static(Box<Static<'tcx>>),
1789 /// We store the normalized type to avoid requiring normalization when reading MIR
1790 #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash,
1791 RustcEncodable, RustcDecodable, HashStable)]
1792 pub struct Static<'tcx> {
1794 pub kind: StaticKind<'tcx>,
1795 /// The `DefId` of the item this static was declared in. For promoted values, usually, this is
1796 /// the same as the `DefId` of the `mir::Body` containing the `Place` this promoted appears in.
1797 /// However, after inlining, that might no longer be the case as inlined `Place`s are copied
1798 /// into the calling frame.
1803 Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, HashStable, RustcEncodable, RustcDecodable,
1805 pub enum StaticKind<'tcx> {
1806 /// Promoted references consist of an id (`Promoted`) and the substs necessary to monomorphize
1807 /// it. Usually, these substs are just the identity substs for the item. However, the inliner
1808 /// will adjust these substs when it inlines a function based on the substs at the callsite.
1809 Promoted(Promoted, SubstsRef<'tcx>),
1813 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
1814 #[derive(RustcEncodable, RustcDecodable, HashStable)]
1815 pub enum ProjectionElem<V, T> {
1820 /// These indices are generated by slice patterns. Easiest to explain
1824 /// [X, _, .._, _, _] => { offset: 0, min_length: 4, from_end: false },
1825 /// [_, X, .._, _, _] => { offset: 1, min_length: 4, from_end: false },
1826 /// [_, _, .._, X, _] => { offset: 2, min_length: 4, from_end: true },
1827 /// [_, _, .._, _, X] => { offset: 1, min_length: 4, from_end: true },
1830 /// index or -index (in Python terms), depending on from_end
1832 /// thing being indexed must be at least this long
1834 /// counting backwards from end?
1838 /// These indices are generated by slice patterns.
1840 /// slice[from:-to] in Python terms.
1846 /// "Downcast" to a variant of an ADT. Currently, we only introduce
1847 /// this for ADTs with more than one variant. It may be better to
1848 /// just introduce it always, or always for enums.
1850 /// The included Symbol is the name of the variant, used for printing MIR.
1851 Downcast(Option<Symbol>, VariantIdx),
1854 impl<V, T> ProjectionElem<V, T> {
1855 /// Returns `true` if the target of this projection may refer to a different region of memory
1857 fn is_indirect(&self) -> bool {
1859 Self::Deref => true,
1863 | Self::ConstantIndex { .. }
1864 | Self::Subslice { .. }
1865 | Self::Downcast(_, _)
1871 /// Alias for projections as they appear in places, where the base is a place
1872 /// and the index is a local.
1873 pub type PlaceElem<'tcx> = ProjectionElem<Local, Ty<'tcx>>;
1875 impl<'tcx> Copy for PlaceElem<'tcx> { }
1877 // At least on 64 bit systems, `PlaceElem` should not be larger than two pointers.
1878 #[cfg(target_arch = "x86_64")]
1879 static_assert_size!(PlaceElem<'_>, 16);
1881 /// Alias for projections as they appear in `UserTypeProjection`, where we
1882 /// need neither the `V` parameter for `Index` nor the `T` for `Field`.
1883 pub type ProjectionKind = ProjectionElem<(), ()>;
1885 rustc_index::newtype_index! {
1888 DEBUG_FORMAT = "field[{}]"
1892 #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
1893 pub struct PlaceRef<'a, 'tcx> {
1894 pub base: &'a PlaceBase<'tcx>,
1895 pub projection: &'a [PlaceElem<'tcx>],
1898 impl<'tcx> Place<'tcx> {
1899 // FIXME change this to a const fn by also making List::empty a const fn.
1900 pub fn return_place() -> Place<'tcx> {
1902 base: PlaceBase::Local(RETURN_PLACE),
1903 projection: List::empty(),
1907 /// Returns `true` if this `Place` contains a `Deref` projection.
1909 /// If `Place::is_indirect` returns false, the caller knows that the `Place` refers to the
1910 /// same region of memory as its base.
1911 pub fn is_indirect(&self) -> bool {
1912 self.projection.iter().any(|elem| elem.is_indirect())
1915 /// Finds the innermost `Local` from this `Place`, *if* it is either a local itself or
1916 /// a single deref of a local.
1918 // FIXME: can we safely swap the semantics of `fn base_local` below in here instead?
1919 pub fn local_or_deref_local(&self) -> Option<Local> {
1920 match self.as_ref() {
1922 base: &PlaceBase::Local(local),
1926 base: &PlaceBase::Local(local),
1927 projection: &[ProjectionElem::Deref],
1933 /// If this place represents a local variable like `_X` with no
1934 /// projections, return `Some(_X)`.
1935 pub fn as_local(&self) -> Option<Local> {
1936 self.as_ref().as_local()
1939 pub fn as_ref(&self) -> PlaceRef<'_, 'tcx> {
1942 projection: &self.projection,
1947 impl From<Local> for Place<'_> {
1948 fn from(local: Local) -> Self {
1951 projection: List::empty(),
1956 impl From<Local> for PlaceBase<'_> {
1957 fn from(local: Local) -> Self {
1958 PlaceBase::Local(local)
1962 impl<'a, 'tcx> PlaceRef<'a, 'tcx> {
1963 /// Finds the innermost `Local` from this `Place`, *if* it is either a local itself or
1964 /// a single deref of a local.
1966 // FIXME: can we safely swap the semantics of `fn base_local` below in here instead?
1967 pub fn local_or_deref_local(&self) -> Option<Local> {
1970 base: PlaceBase::Local(local),
1974 base: PlaceBase::Local(local),
1975 projection: [ProjectionElem::Deref],
1981 /// If this place represents a local variable like `_X` with no
1982 /// projections, return `Some(_X)`.
1983 pub fn as_local(&self) -> Option<Local> {
1985 PlaceRef { base: PlaceBase::Local(l), projection: [] } => Some(*l),
1991 impl Debug for Place<'_> {
1992 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1993 for elem in self.projection.iter().rev() {
1995 ProjectionElem::Downcast(_, _) | ProjectionElem::Field(_, _) => {
1996 write!(fmt, "(").unwrap();
1998 ProjectionElem::Deref => {
1999 write!(fmt, "(*").unwrap();
2001 ProjectionElem::Index(_)
2002 | ProjectionElem::ConstantIndex { .. }
2003 | ProjectionElem::Subslice { .. } => {}
2007 write!(fmt, "{:?}", self.base)?;
2009 for elem in self.projection.iter() {
2011 ProjectionElem::Downcast(Some(name), _index) => {
2012 write!(fmt, " as {})", name)?;
2014 ProjectionElem::Downcast(None, index) => {
2015 write!(fmt, " as variant#{:?})", index)?;
2017 ProjectionElem::Deref => {
2020 ProjectionElem::Field(field, ty) => {
2021 write!(fmt, ".{:?}: {:?})", field.index(), ty)?;
2023 ProjectionElem::Index(ref index) => {
2024 write!(fmt, "[{:?}]", index)?;
2026 ProjectionElem::ConstantIndex { offset, min_length, from_end: false } => {
2027 write!(fmt, "[{:?} of {:?}]", offset, min_length)?;
2029 ProjectionElem::ConstantIndex { offset, min_length, from_end: true } => {
2030 write!(fmt, "[-{:?} of {:?}]", offset, min_length)?;
2032 ProjectionElem::Subslice { from, to } if *to == 0 => {
2033 write!(fmt, "[{:?}:]", from)?;
2035 ProjectionElem::Subslice { from, to } if *from == 0 => {
2036 write!(fmt, "[:-{:?}]", to)?;
2038 ProjectionElem::Subslice { from, to } => {
2039 write!(fmt, "[{:?}:-{:?}]", from, to)?;
2048 impl Debug for PlaceBase<'_> {
2049 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2051 PlaceBase::Local(id) => write!(fmt, "{:?}", id),
2052 PlaceBase::Static(box self::Static { ty, kind: StaticKind::Static, def_id }) => {
2053 write!(fmt, "({}: {:?})", ty::tls::with(|tcx| tcx.def_path_str(def_id)), ty)
2055 PlaceBase::Static(box self::Static {
2056 ty, kind: StaticKind::Promoted(promoted, _), def_id: _
2058 write!(fmt, "({:?}: {:?})", promoted, ty)
2064 ///////////////////////////////////////////////////////////////////////////
2067 rustc_index::newtype_index! {
2068 pub struct SourceScope {
2070 DEBUG_FORMAT = "scope[{}]",
2071 const OUTERMOST_SOURCE_SCOPE = 0,
2075 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
2076 pub struct SourceScopeData {
2078 pub parent_scope: Option<SourceScope>,
2080 /// Crate-local information for this source scope, that can't (and
2081 /// needn't) be tracked across crates.
2082 pub local_data: ClearCrossCrate<SourceScopeLocalData>,
2085 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
2086 pub struct SourceScopeLocalData {
2087 /// An `HirId` with lint levels equivalent to this scope's lint levels.
2088 pub lint_root: hir::HirId,
2089 /// The unsafe block that contains this node.
2093 ///////////////////////////////////////////////////////////////////////////
2096 /// These are values that can appear inside an rvalue. They are intentionally
2097 /// limited to prevent rvalues from being nested in one another.
2098 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable)]
2099 pub enum Operand<'tcx> {
2100 /// Copy: The value must be available for use afterwards.
2102 /// This implies that the type of the place must be `Copy`; this is true
2103 /// by construction during build, but also checked by the MIR type checker.
2106 /// Move: The value (including old borrows of it) will not be used again.
2108 /// Safe for values of all types (modulo future developments towards `?Move`).
2109 /// Correct usage patterns are enforced by the borrow checker for safe code.
2110 /// `Copy` may be converted to `Move` to enable "last-use" optimizations.
2113 /// Synthesizes a constant value.
2114 Constant(Box<Constant<'tcx>>),
2117 impl<'tcx> Debug for Operand<'tcx> {
2118 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2119 use self::Operand::*;
2121 Constant(ref a) => write!(fmt, "{:?}", a),
2122 Copy(ref place) => write!(fmt, "{:?}", place),
2123 Move(ref place) => write!(fmt, "move {:?}", place),
2128 impl<'tcx> Operand<'tcx> {
2129 /// Convenience helper to make a constant that refers to the fn
2130 /// with given `DefId` and substs. Since this is used to synthesize
2131 /// MIR, assumes `user_ty` is None.
2132 pub fn function_handle(
2135 substs: SubstsRef<'tcx>,
2138 let ty = tcx.type_of(def_id).subst(tcx, substs);
2139 Operand::Constant(box Constant {
2142 literal: ty::Const::zero_sized(tcx, ty),
2146 pub fn to_copy(&self) -> Self {
2148 Operand::Copy(_) | Operand::Constant(_) => self.clone(),
2149 Operand::Move(ref place) => Operand::Copy(place.clone()),
2154 ///////////////////////////////////////////////////////////////////////////
2157 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable, PartialEq)]
2158 pub enum Rvalue<'tcx> {
2159 /// x (either a move or copy, depending on type of x)
2163 Repeat(Operand<'tcx>, u64),
2166 Ref(Region<'tcx>, BorrowKind, Place<'tcx>),
2168 /// length of a [X] or [X;n] value
2171 Cast(CastKind, Operand<'tcx>, Ty<'tcx>),
2173 BinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
2174 CheckedBinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
2176 NullaryOp(NullOp, Ty<'tcx>),
2177 UnaryOp(UnOp, Operand<'tcx>),
2179 /// Read the discriminant of an ADT.
2181 /// Undefined (i.e., no effort is made to make it defined, but there’s no reason why it cannot
2182 /// be defined to return, say, a 0) if ADT is not an enum.
2183 Discriminant(Place<'tcx>),
2185 /// Creates an aggregate value, like a tuple or struct. This is
2186 /// only needed because we want to distinguish `dest = Foo { x:
2187 /// ..., y: ... }` from `dest.x = ...; dest.y = ...;` in the case
2188 /// that `Foo` has a destructor. These rvalues can be optimized
2189 /// away after type-checking and before lowering.
2190 Aggregate(Box<AggregateKind<'tcx>>, Vec<Operand<'tcx>>),
2193 #[derive(Clone, Copy, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2196 Pointer(PointerCast),
2199 #[derive(Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2200 pub enum AggregateKind<'tcx> {
2201 /// The type is of the element
2205 /// The second field is the variant index. It's equal to 0 for struct
2206 /// and union expressions. The fourth field is
2207 /// active field number and is present only for union expressions
2208 /// -- e.g., for a union expression `SomeUnion { c: .. }`, the
2209 /// active field index would identity the field `c`
2210 Adt(&'tcx AdtDef, VariantIdx, SubstsRef<'tcx>, Option<UserTypeAnnotationIndex>, Option<usize>),
2212 Closure(DefId, SubstsRef<'tcx>),
2213 Generator(DefId, SubstsRef<'tcx>, hir::Movability),
2216 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2218 /// The `+` operator (addition)
2220 /// The `-` operator (subtraction)
2222 /// The `*` operator (multiplication)
2224 /// The `/` operator (division)
2226 /// The `%` operator (modulus)
2228 /// The `^` operator (bitwise xor)
2230 /// The `&` operator (bitwise and)
2232 /// The `|` operator (bitwise or)
2234 /// The `<<` operator (shift left)
2236 /// The `>>` operator (shift right)
2238 /// The `==` operator (equality)
2240 /// The `<` operator (less than)
2242 /// The `<=` operator (less than or equal to)
2244 /// The `!=` operator (not equal to)
2246 /// The `>=` operator (greater than or equal to)
2248 /// The `>` operator (greater than)
2250 /// The `ptr.offset` operator
2255 pub fn is_checkable(self) -> bool {
2258 Add | Sub | Mul | Shl | Shr => true,
2264 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2266 /// Returns the size of a value of that type
2268 /// Creates a new uninitialized box for a value of that type
2272 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2274 /// The `!` operator for logical inversion
2276 /// The `-` operator for negation
2280 impl<'tcx> Debug for Rvalue<'tcx> {
2281 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2282 use self::Rvalue::*;
2285 Use(ref place) => write!(fmt, "{:?}", place),
2286 Repeat(ref a, ref b) => write!(fmt, "[{:?}; {:?}]", a, b),
2287 Len(ref a) => write!(fmt, "Len({:?})", a),
2288 Cast(ref kind, ref place, ref ty) => {
2289 write!(fmt, "{:?} as {:?} ({:?})", place, ty, kind)
2291 BinaryOp(ref op, ref a, ref b) => write!(fmt, "{:?}({:?}, {:?})", op, a, b),
2292 CheckedBinaryOp(ref op, ref a, ref b) => {
2293 write!(fmt, "Checked{:?}({:?}, {:?})", op, a, b)
2295 UnaryOp(ref op, ref a) => write!(fmt, "{:?}({:?})", op, a),
2296 Discriminant(ref place) => write!(fmt, "discriminant({:?})", place),
2297 NullaryOp(ref op, ref t) => write!(fmt, "{:?}({:?})", op, t),
2298 Ref(region, borrow_kind, ref place) => {
2299 let kind_str = match borrow_kind {
2300 BorrowKind::Shared => "",
2301 BorrowKind::Shallow => "shallow ",
2302 BorrowKind::Mut { .. } | BorrowKind::Unique => "mut ",
2305 // When printing regions, add trailing space if necessary.
2306 let print_region = ty::tls::with(|tcx| {
2307 tcx.sess.verbose() || tcx.sess.opts.debugging_opts.identify_regions
2309 let region = if print_region {
2310 let mut region = region.to_string();
2311 if region.len() > 0 {
2316 // Do not even print 'static
2319 write!(fmt, "&{}{}{:?}", region, kind_str, place)
2322 Aggregate(ref kind, ref places) => {
2323 fn fmt_tuple(fmt: &mut Formatter<'_>, places: &[Operand<'_>]) -> fmt::Result {
2324 let mut tuple_fmt = fmt.debug_tuple("");
2325 for place in places {
2326 tuple_fmt.field(place);
2332 AggregateKind::Array(_) => write!(fmt, "{:?}", places),
2334 AggregateKind::Tuple => match places.len() {
2335 0 => write!(fmt, "()"),
2336 1 => write!(fmt, "({:?},)", places[0]),
2337 _ => fmt_tuple(fmt, places),
2340 AggregateKind::Adt(adt_def, variant, substs, _user_ty, _) => {
2341 let variant_def = &adt_def.variants[variant];
2344 ty::tls::with(|tcx| {
2345 let substs = tcx.lift(&substs).expect("could not lift for printing");
2346 FmtPrinter::new(tcx, f, Namespace::ValueNS)
2347 .print_def_path(variant_def.def_id, substs)?;
2351 match variant_def.ctor_kind {
2352 CtorKind::Const => Ok(()),
2353 CtorKind::Fn => fmt_tuple(fmt, places),
2354 CtorKind::Fictive => {
2355 let mut struct_fmt = fmt.debug_struct("");
2356 for (field, place) in variant_def.fields.iter().zip(places) {
2357 struct_fmt.field(&field.ident.as_str(), place);
2364 AggregateKind::Closure(def_id, substs) => ty::tls::with(|tcx| {
2365 if let Some(hir_id) = tcx.hir().as_local_hir_id(def_id) {
2366 let name = if tcx.sess.opts.debugging_opts.span_free_formats {
2367 let substs = tcx.lift(&substs).unwrap();
2370 tcx.def_path_str_with_substs(def_id, substs),
2373 format!("[closure@{:?}]", tcx.hir().span(hir_id))
2375 let mut struct_fmt = fmt.debug_struct(&name);
2377 if let Some(upvars) = tcx.upvars(def_id) {
2378 for (&var_id, place) in upvars.keys().zip(places) {
2379 let var_name = tcx.hir().name(var_id);
2380 struct_fmt.field(&var_name.as_str(), place);
2386 write!(fmt, "[closure]")
2390 AggregateKind::Generator(def_id, _, _) => ty::tls::with(|tcx| {
2391 if let Some(hir_id) = tcx.hir().as_local_hir_id(def_id) {
2392 let name = format!("[generator@{:?}]", tcx.hir().span(hir_id));
2393 let mut struct_fmt = fmt.debug_struct(&name);
2395 if let Some(upvars) = tcx.upvars(def_id) {
2396 for (&var_id, place) in upvars.keys().zip(places) {
2397 let var_name = tcx.hir().name(var_id);
2398 struct_fmt.field(&var_name.as_str(), place);
2404 write!(fmt, "[generator]")
2413 ///////////////////////////////////////////////////////////////////////////
2416 /// Two constants are equal if they are the same constant. Note that
2417 /// this does not necessarily mean that they are "==" in Rust -- in
2418 /// particular one must be wary of `NaN`!
2420 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable)]
2421 pub struct Constant<'tcx> {
2424 /// Optional user-given type: for something like
2425 /// `collect::<Vec<_>>`, this would be present and would
2426 /// indicate that `Vec<_>` was explicitly specified.
2428 /// Needed for NLL to impose user-given type constraints.
2429 pub user_ty: Option<UserTypeAnnotationIndex>,
2431 pub literal: &'tcx ty::Const<'tcx>,
2434 impl Constant<'tcx> {
2435 pub fn check_static_ptr(&self, tcx: TyCtxt<'_>) -> Option<DefId> {
2436 match self.literal.val.try_to_scalar() {
2437 Some(Scalar::Ptr(ptr)) => match tcx.alloc_map.lock().get(ptr.alloc_id) {
2438 Some(GlobalAlloc::Static(def_id)) => Some(def_id),
2441 tcx.sess.delay_span_bug(
2442 DUMMY_SP, "MIR cannot contain dangling const pointers",
2452 /// A collection of projections into user types.
2454 /// They are projections because a binding can occur a part of a
2455 /// parent pattern that has been ascribed a type.
2457 /// Its a collection because there can be multiple type ascriptions on
2458 /// the path from the root of the pattern down to the binding itself.
2463 /// struct S<'a>((i32, &'a str), String);
2464 /// let S((_, w): (i32, &'static str), _): S = ...;
2465 /// // ------ ^^^^^^^^^^^^^^^^^^^ (1)
2466 /// // --------------------------------- ^ (2)
2469 /// The highlights labelled `(1)` show the subpattern `(_, w)` being
2470 /// ascribed the type `(i32, &'static str)`.
2472 /// The highlights labelled `(2)` show the whole pattern being
2473 /// ascribed the type `S`.
2475 /// In this example, when we descend to `w`, we will have built up the
2476 /// following two projected types:
2478 /// * base: `S`, projection: `(base.0).1`
2479 /// * base: `(i32, &'static str)`, projection: `base.1`
2481 /// The first will lead to the constraint `w: &'1 str` (for some
2482 /// inferred region `'1`). The second will lead to the constraint `w:
2484 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
2485 pub struct UserTypeProjections {
2486 pub(crate) contents: Vec<(UserTypeProjection, Span)>,
2489 impl<'tcx> UserTypeProjections {
2490 pub fn none() -> Self {
2491 UserTypeProjections { contents: vec![] }
2494 pub fn from_projections(projs: impl Iterator<Item = (UserTypeProjection, Span)>) -> Self {
2495 UserTypeProjections { contents: projs.collect() }
2498 pub fn projections_and_spans(&self) -> impl Iterator<Item = &(UserTypeProjection, Span)> {
2499 self.contents.iter()
2502 pub fn projections(&self) -> impl Iterator<Item = &UserTypeProjection> {
2503 self.contents.iter().map(|&(ref user_type, _span)| user_type)
2506 pub fn push_projection(mut self, user_ty: &UserTypeProjection, span: Span) -> Self {
2507 self.contents.push((user_ty.clone(), span));
2513 mut f: impl FnMut(UserTypeProjection) -> UserTypeProjection,
2515 self.contents = self.contents.drain(..).map(|(proj, span)| (f(proj), span)).collect();
2519 pub fn index(self) -> Self {
2520 self.map_projections(|pat_ty_proj| pat_ty_proj.index())
2523 pub fn subslice(self, from: u32, to: u32) -> Self {
2524 self.map_projections(|pat_ty_proj| pat_ty_proj.subslice(from, to))
2527 pub fn deref(self) -> Self {
2528 self.map_projections(|pat_ty_proj| pat_ty_proj.deref())
2531 pub fn leaf(self, field: Field) -> Self {
2532 self.map_projections(|pat_ty_proj| pat_ty_proj.leaf(field))
2535 pub fn variant(self, adt_def: &'tcx AdtDef, variant_index: VariantIdx, field: Field) -> Self {
2536 self.map_projections(|pat_ty_proj| pat_ty_proj.variant(adt_def, variant_index, field))
2540 /// Encodes the effect of a user-supplied type annotation on the
2541 /// subcomponents of a pattern. The effect is determined by applying the
2542 /// given list of proejctions to some underlying base type. Often,
2543 /// the projection element list `projs` is empty, in which case this
2544 /// directly encodes a type in `base`. But in the case of complex patterns with
2545 /// subpatterns and bindings, we want to apply only a *part* of the type to a variable,
2546 /// in which case the `projs` vector is used.
2550 /// * `let x: T = ...` -- here, the `projs` vector is empty.
2552 /// * `let (x, _): T = ...` -- here, the `projs` vector would contain
2553 /// `field[0]` (aka `.0`), indicating that the type of `s` is
2554 /// determined by finding the type of the `.0` field from `T`.
2555 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable, PartialEq)]
2556 pub struct UserTypeProjection {
2557 pub base: UserTypeAnnotationIndex,
2558 pub projs: Vec<ProjectionKind>,
2561 impl Copy for ProjectionKind {}
2563 impl UserTypeProjection {
2564 pub(crate) fn index(mut self) -> Self {
2565 self.projs.push(ProjectionElem::Index(()));
2569 pub(crate) fn subslice(mut self, from: u32, to: u32) -> Self {
2570 self.projs.push(ProjectionElem::Subslice { from, to });
2574 pub(crate) fn deref(mut self) -> Self {
2575 self.projs.push(ProjectionElem::Deref);
2579 pub(crate) fn leaf(mut self, field: Field) -> Self {
2580 self.projs.push(ProjectionElem::Field(field, ()));
2584 pub(crate) fn variant(
2586 adt_def: &'tcx AdtDef,
2587 variant_index: VariantIdx,
2590 self.projs.push(ProjectionElem::Downcast(
2591 Some(adt_def.variants[variant_index].ident.name),
2594 self.projs.push(ProjectionElem::Field(field, ()));
2599 CloneTypeFoldableAndLiftImpls! { ProjectionKind, }
2601 impl<'tcx> TypeFoldable<'tcx> for UserTypeProjection {
2602 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
2603 use crate::mir::ProjectionElem::*;
2605 let base = self.base.fold_with(folder);
2606 let projs: Vec<_> = self
2609 .map(|elem| match elem {
2611 Field(f, ()) => Field(f.clone(), ()),
2612 Index(()) => Index(()),
2613 elem => elem.clone(),
2617 UserTypeProjection { base, projs }
2620 fn super_visit_with<Vs: TypeVisitor<'tcx>>(&self, visitor: &mut Vs) -> bool {
2621 self.base.visit_with(visitor)
2622 // Note: there's nothing in `self.proj` to visit.
2626 rustc_index::newtype_index! {
2627 pub struct Promoted {
2629 DEBUG_FORMAT = "promoted[{}]"
2633 impl<'tcx> Debug for Constant<'tcx> {
2634 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2635 write!(fmt, "{}", self)
2639 impl<'tcx> Display for Constant<'tcx> {
2640 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2641 write!(fmt, "const ")?;
2642 // FIXME make the default pretty printing of raw pointers more detailed. Here we output the
2643 // debug representation of raw pointers, so that the raw pointers in the mir dump output are
2644 // detailed and just not '{pointer}'.
2645 if let ty::RawPtr(_) = self.literal.ty.kind {
2646 write!(fmt, "{:?} : {}", self.literal.val, self.literal.ty)
2648 write!(fmt, "{}", self.literal)
2653 impl<'tcx> graph::DirectedGraph for Body<'tcx> {
2654 type Node = BasicBlock;
2657 impl<'tcx> graph::WithNumNodes for Body<'tcx> {
2658 fn num_nodes(&self) -> usize {
2659 self.basic_blocks.len()
2663 impl<'tcx> graph::WithStartNode for Body<'tcx> {
2664 fn start_node(&self) -> Self::Node {
2669 impl<'tcx> graph::WithPredecessors for Body<'tcx> {
2673 ) -> <Self as GraphPredecessors<'_>>::Iter {
2674 self.predecessors_for(node).to_vec().into_iter()
2678 impl<'tcx> graph::WithSuccessors for Body<'tcx> {
2682 ) -> <Self as GraphSuccessors<'_>>::Iter {
2683 self.basic_blocks[node].terminator().successors().cloned()
2687 impl<'a, 'b> graph::GraphPredecessors<'b> for Body<'a> {
2688 type Item = BasicBlock;
2689 type Iter = IntoIter<BasicBlock>;
2692 impl<'a, 'b> graph::GraphSuccessors<'b> for Body<'a> {
2693 type Item = BasicBlock;
2694 type Iter = iter::Cloned<Successors<'b>>;
2697 #[derive(Copy, Clone, PartialEq, Eq, Hash, Ord, PartialOrd, HashStable)]
2698 pub struct Location {
2699 /// The block that the location is within.
2700 pub block: BasicBlock,
2702 /// The location is the position of the start of the statement; or, if
2703 /// `statement_index` equals the number of statements, then the start of the
2705 pub statement_index: usize,
2708 impl fmt::Debug for Location {
2709 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2710 write!(fmt, "{:?}[{}]", self.block, self.statement_index)
2715 pub const START: Location = Location { block: START_BLOCK, statement_index: 0 };
2717 /// Returns the location immediately after this one within the enclosing block.
2719 /// Note that if this location represents a terminator, then the
2720 /// resulting location would be out of bounds and invalid.
2721 pub fn successor_within_block(&self) -> Location {
2722 Location { block: self.block, statement_index: self.statement_index + 1 }
2725 /// Returns `true` if `other` is earlier in the control flow graph than `self`.
2726 pub fn is_predecessor_of<'tcx>(&self, other: Location, body: &Body<'tcx>) -> bool {
2727 // If we are in the same block as the other location and are an earlier statement
2728 // then we are a predecessor of `other`.
2729 if self.block == other.block && self.statement_index < other.statement_index {
2733 // If we're in another block, then we want to check that block is a predecessor of `other`.
2734 let mut queue: Vec<BasicBlock> = body.predecessors_for(other.block).to_vec();
2735 let mut visited = FxHashSet::default();
2737 while let Some(block) = queue.pop() {
2738 // If we haven't visited this block before, then make sure we visit it's predecessors.
2739 if visited.insert(block) {
2740 queue.extend(body.predecessors_for(block).iter().cloned());
2745 // If we found the block that `self` is in, then we are a predecessor of `other` (since
2746 // we found that block by looking at the predecessors of `other`).
2747 if self.block == block {
2755 pub fn dominates(&self, other: Location, dominators: &Dominators<BasicBlock>) -> bool {
2756 if self.block == other.block {
2757 self.statement_index <= other.statement_index
2759 dominators.is_dominated_by(other.block, self.block)
2764 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable)]
2765 pub enum UnsafetyViolationKind {
2767 /// Permitted both in `const fn`s and regular `fn`s.
2769 BorrowPacked(hir::HirId),
2772 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable)]
2773 pub struct UnsafetyViolation {
2774 pub source_info: SourceInfo,
2775 pub description: Symbol,
2776 pub details: Symbol,
2777 pub kind: UnsafetyViolationKind,
2780 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable)]
2781 pub struct UnsafetyCheckResult {
2782 /// Violations that are propagated *upwards* from this function.
2783 pub violations: Lrc<[UnsafetyViolation]>,
2784 /// `unsafe` blocks in this function, along with whether they are used. This is
2785 /// used for the "unused_unsafe" lint.
2786 pub unsafe_blocks: Lrc<[(hir::HirId, bool)]>,
2789 rustc_index::newtype_index! {
2790 pub struct GeneratorSavedLocal {
2792 DEBUG_FORMAT = "_{}",
2796 /// The layout of generator state.
2797 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
2798 pub struct GeneratorLayout<'tcx> {
2799 /// The type of every local stored inside the generator.
2800 pub field_tys: IndexVec<GeneratorSavedLocal, Ty<'tcx>>,
2802 /// Which of the above fields are in each variant. Note that one field may
2803 /// be stored in multiple variants.
2804 pub variant_fields: IndexVec<VariantIdx, IndexVec<Field, GeneratorSavedLocal>>,
2806 /// Which saved locals are storage-live at the same time. Locals that do not
2807 /// have conflicts with each other are allowed to overlap in the computed
2809 pub storage_conflicts: BitMatrix<GeneratorSavedLocal, GeneratorSavedLocal>,
2812 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
2813 pub struct BorrowCheckResult<'tcx> {
2814 pub closure_requirements: Option<ClosureRegionRequirements<'tcx>>,
2815 pub used_mut_upvars: SmallVec<[Field; 8]>,
2818 /// The result of the `mir_const_qualif` query.
2820 /// Each field corresponds to an implementer of the `Qualif` trait in
2821 /// `librustc_mir/transform/check_consts/qualifs.rs`. See that file for more information on each
2823 #[derive(Clone, Copy, Debug, Default, RustcEncodable, RustcDecodable, HashStable)]
2824 pub struct ConstQualifs {
2825 pub has_mut_interior: bool,
2826 pub needs_drop: bool,
2829 /// After we borrow check a closure, we are left with various
2830 /// requirements that we have inferred between the free regions that
2831 /// appear in the closure's signature or on its field types. These
2832 /// requirements are then verified and proved by the closure's
2833 /// creating function. This struct encodes those requirements.
2835 /// The requirements are listed as being between various
2836 /// `RegionVid`. The 0th region refers to `'static`; subsequent region
2837 /// vids refer to the free regions that appear in the closure (or
2838 /// generator's) type, in order of appearance. (This numbering is
2839 /// actually defined by the `UniversalRegions` struct in the NLL
2840 /// region checker. See for example
2841 /// `UniversalRegions::closure_mapping`.) Note that we treat the free
2842 /// regions in the closure's type "as if" they were erased, so their
2843 /// precise identity is not important, only their position.
2845 /// Example: If type check produces a closure with the closure substs:
2848 /// ClosureSubsts = [
2849 /// i8, // the "closure kind"
2850 /// for<'x> fn(&'a &'x u32) -> &'x u32, // the "closure signature"
2851 /// &'a String, // some upvar
2855 /// here, there is one unique free region (`'a`) but it appears
2856 /// twice. We would "renumber" each occurrence to a unique vid, as follows:
2859 /// ClosureSubsts = [
2860 /// i8, // the "closure kind"
2861 /// for<'x> fn(&'1 &'x u32) -> &'x u32, // the "closure signature"
2862 /// &'2 String, // some upvar
2866 /// Now the code might impose a requirement like `'1: '2`. When an
2867 /// instance of the closure is created, the corresponding free regions
2868 /// can be extracted from its type and constrained to have the given
2869 /// outlives relationship.
2871 /// In some cases, we have to record outlives requirements between
2872 /// types and regions as well. In that case, if those types include
2873 /// any regions, those regions are recorded as `ReClosureBound`
2874 /// instances assigned one of these same indices. Those regions will
2875 /// be substituted away by the creator. We use `ReClosureBound` in
2876 /// that case because the regions must be allocated in the global
2877 /// `TyCtxt`, and hence we cannot use `ReVar` (which is what we use
2878 /// internally within the rest of the NLL code).
2879 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
2880 pub struct ClosureRegionRequirements<'tcx> {
2881 /// The number of external regions defined on the closure. In our
2882 /// example above, it would be 3 -- one for `'static`, then `'1`
2883 /// and `'2`. This is just used for a sanity check later on, to
2884 /// make sure that the number of regions we see at the callsite
2886 pub num_external_vids: usize,
2888 /// Requirements between the various free regions defined in
2890 pub outlives_requirements: Vec<ClosureOutlivesRequirement<'tcx>>,
2893 /// Indicates an outlives-constraint between a type or between two
2894 /// free regions declared on the closure.
2895 #[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
2896 pub struct ClosureOutlivesRequirement<'tcx> {
2897 // This region or type ...
2898 pub subject: ClosureOutlivesSubject<'tcx>,
2900 // ... must outlive this one.
2901 pub outlived_free_region: ty::RegionVid,
2903 // If not, report an error here ...
2904 pub blame_span: Span,
2906 // ... due to this reason.
2907 pub category: ConstraintCategory,
2910 /// Outlives-constraints can be categorized to determine whether and why they
2911 /// are interesting (for error reporting). Order of variants indicates sort
2912 /// order of the category, thereby influencing diagnostic output.
2914 /// See also [rustc_mir::borrow_check::nll::constraints].
2928 pub enum ConstraintCategory {
2936 /// A constraint that came from checking the body of a closure.
2938 /// We try to get the category that the closure used when reporting this.
2946 /// A "boring" constraint (caused by the given location) is one that
2947 /// the user probably doesn't want to see described in diagnostics,
2948 /// because it is kind of an artifact of the type system setup.
2949 /// Example: `x = Foo { field: y }` technically creates
2950 /// intermediate regions representing the "type of `Foo { field: y
2951 /// }`", and data flows from `y` into those variables, but they
2952 /// are not very interesting. The assignment into `x` on the other
2955 // Boring and applicable everywhere.
2958 /// A constraint that doesn't correspond to anything the user sees.
2962 /// The subject of a `ClosureOutlivesRequirement` -- that is, the thing
2963 /// that must outlive some region.
2964 #[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
2965 pub enum ClosureOutlivesSubject<'tcx> {
2966 /// Subject is a type, typically a type parameter, but could also
2967 /// be a projection. Indicates a requirement like `T: 'a` being
2968 /// passed to the caller, where the type here is `T`.
2970 /// The type here is guaranteed not to contain any free regions at
2974 /// Subject is a free region from the closure. Indicates a requirement
2975 /// like `'a: 'b` being passed to the caller; the region here is `'a`.
2976 Region(ty::RegionVid),
2980 * `TypeFoldable` implementations for MIR types
2983 CloneTypeFoldableAndLiftImpls! {
2992 SourceScopeLocalData,
2993 UserTypeAnnotationIndex,
2996 impl<'tcx> TypeFoldable<'tcx> for Terminator<'tcx> {
2997 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
2998 use crate::mir::TerminatorKind::*;
3000 let kind = match self.kind {
3001 Goto { target } => Goto { target },
3002 SwitchInt { ref discr, switch_ty, ref values, ref targets } => SwitchInt {
3003 discr: discr.fold_with(folder),
3004 switch_ty: switch_ty.fold_with(folder),
3005 values: values.clone(),
3006 targets: targets.clone(),
3008 Drop { ref location, target, unwind } => {
3009 Drop { location: location.fold_with(folder), target, unwind }
3011 DropAndReplace { ref location, ref value, target, unwind } => DropAndReplace {
3012 location: location.fold_with(folder),
3013 value: value.fold_with(folder),
3017 Yield { ref value, resume, drop } => {
3018 Yield { value: value.fold_with(folder), resume: resume, drop: drop }
3020 Call { ref func, ref args, ref destination, cleanup, from_hir_call } => {
3022 destination.as_ref().map(|&(ref loc, dest)| (loc.fold_with(folder), dest));
3025 func: func.fold_with(folder),
3026 args: args.fold_with(folder),
3032 Assert { ref cond, expected, ref msg, target, cleanup } => {
3034 let msg = match msg {
3035 BoundsCheck { ref len, ref index } =>
3037 len: len.fold_with(folder),
3038 index: index.fold_with(folder),
3040 Panic { .. } | Overflow(_) | OverflowNeg | DivisionByZero | RemainderByZero |
3041 ResumedAfterReturn(_) | ResumedAfterPanic(_) =>
3044 Assert { cond: cond.fold_with(folder), expected, msg, target, cleanup }
3046 GeneratorDrop => GeneratorDrop,
3050 Unreachable => Unreachable,
3051 FalseEdges { real_target, imaginary_target } => {
3052 FalseEdges { real_target, imaginary_target }
3054 FalseUnwind { real_target, unwind } => FalseUnwind { real_target, unwind },
3056 Terminator { source_info: self.source_info, kind }
3059 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3060 use crate::mir::TerminatorKind::*;
3063 SwitchInt { ref discr, switch_ty, .. } => {
3064 discr.visit_with(visitor) || switch_ty.visit_with(visitor)
3066 Drop { ref location, .. } => location.visit_with(visitor),
3067 DropAndReplace { ref location, ref value, .. } => {
3068 location.visit_with(visitor) || value.visit_with(visitor)
3070 Yield { ref value, .. } => value.visit_with(visitor),
3071 Call { ref func, ref args, ref destination, .. } => {
3072 let dest = if let Some((ref loc, _)) = *destination {
3073 loc.visit_with(visitor)
3077 dest || func.visit_with(visitor) || args.visit_with(visitor)
3079 Assert { ref cond, ref msg, .. } => {
3080 if cond.visit_with(visitor) {
3083 BoundsCheck { ref len, ref index } =>
3084 len.visit_with(visitor) || index.visit_with(visitor),
3085 Panic { .. } | Overflow(_) | OverflowNeg |
3086 DivisionByZero | RemainderByZero |
3087 ResumedAfterReturn(_) | ResumedAfterPanic(_) =>
3101 | FalseUnwind { .. } => false,
3106 impl<'tcx> TypeFoldable<'tcx> for GeneratorKind {
3107 fn super_fold_with<F: TypeFolder<'tcx>>(&self, _: &mut F) -> Self {
3111 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, _: &mut V) -> bool {
3116 impl<'tcx> TypeFoldable<'tcx> for Place<'tcx> {
3117 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
3119 base: self.base.fold_with(folder),
3120 projection: self.projection.fold_with(folder),
3124 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3125 self.base.visit_with(visitor) || self.projection.visit_with(visitor)
3129 impl<'tcx> TypeFoldable<'tcx> for PlaceBase<'tcx> {
3130 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
3132 PlaceBase::Local(local) => PlaceBase::Local(local.fold_with(folder)),
3133 PlaceBase::Static(static_) => PlaceBase::Static(static_.fold_with(folder)),
3137 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3139 PlaceBase::Local(local) => local.visit_with(visitor),
3140 PlaceBase::Static(static_) => (**static_).visit_with(visitor),
3145 impl<'tcx> TypeFoldable<'tcx> for &'tcx ty::List<PlaceElem<'tcx>> {
3146 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
3147 let v = self.iter().map(|t| t.fold_with(folder)).collect::<Vec<_>>();
3148 folder.tcx().intern_place_elems(&v)
3151 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3152 self.iter().any(|t| t.visit_with(visitor))
3156 impl<'tcx> TypeFoldable<'tcx> for Static<'tcx> {
3157 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
3159 ty: self.ty.fold_with(folder),
3160 kind: self.kind.fold_with(folder),
3161 def_id: self.def_id,
3165 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3166 let Static { ty, kind, def_id: _ } = self;
3168 ty.visit_with(visitor) || kind.visit_with(visitor)
3172 impl<'tcx> TypeFoldable<'tcx> for StaticKind<'tcx> {
3173 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
3175 StaticKind::Promoted(promoted, substs) =>
3176 StaticKind::Promoted(promoted.fold_with(folder), substs.fold_with(folder)),
3177 StaticKind::Static => StaticKind::Static
3181 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3183 StaticKind::Promoted(promoted, substs) =>
3184 promoted.visit_with(visitor) || substs.visit_with(visitor),
3185 StaticKind::Static => { false }
3190 impl<'tcx> TypeFoldable<'tcx> for Rvalue<'tcx> {
3191 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
3192 use crate::mir::Rvalue::*;
3194 Use(ref op) => Use(op.fold_with(folder)),
3195 Repeat(ref op, len) => Repeat(op.fold_with(folder), len),
3196 Ref(region, bk, ref place) => {
3197 Ref(region.fold_with(folder), bk, place.fold_with(folder))
3199 Len(ref place) => Len(place.fold_with(folder)),
3200 Cast(kind, ref op, ty) => Cast(kind, op.fold_with(folder), ty.fold_with(folder)),
3201 BinaryOp(op, ref rhs, ref lhs) => {
3202 BinaryOp(op, rhs.fold_with(folder), lhs.fold_with(folder))
3204 CheckedBinaryOp(op, ref rhs, ref lhs) => {
3205 CheckedBinaryOp(op, rhs.fold_with(folder), lhs.fold_with(folder))
3207 UnaryOp(op, ref val) => UnaryOp(op, val.fold_with(folder)),
3208 Discriminant(ref place) => Discriminant(place.fold_with(folder)),
3209 NullaryOp(op, ty) => NullaryOp(op, ty.fold_with(folder)),
3210 Aggregate(ref kind, ref fields) => {
3211 let kind = box match **kind {
3212 AggregateKind::Array(ty) => AggregateKind::Array(ty.fold_with(folder)),
3213 AggregateKind::Tuple => AggregateKind::Tuple,
3214 AggregateKind::Adt(def, v, substs, user_ty, n) => AggregateKind::Adt(
3217 substs.fold_with(folder),
3218 user_ty.fold_with(folder),
3221 AggregateKind::Closure(id, substs) => {
3222 AggregateKind::Closure(id, substs.fold_with(folder))
3224 AggregateKind::Generator(id, substs, movablity) => {
3225 AggregateKind::Generator(id, substs.fold_with(folder), movablity)
3228 Aggregate(kind, fields.fold_with(folder))
3233 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3234 use crate::mir::Rvalue::*;
3236 Use(ref op) => op.visit_with(visitor),
3237 Repeat(ref op, _) => op.visit_with(visitor),
3238 Ref(region, _, ref place) => region.visit_with(visitor) || place.visit_with(visitor),
3239 Len(ref place) => place.visit_with(visitor),
3240 Cast(_, ref op, ty) => op.visit_with(visitor) || ty.visit_with(visitor),
3241 BinaryOp(_, ref rhs, ref lhs) | CheckedBinaryOp(_, ref rhs, ref lhs) => {
3242 rhs.visit_with(visitor) || lhs.visit_with(visitor)
3244 UnaryOp(_, ref val) => val.visit_with(visitor),
3245 Discriminant(ref place) => place.visit_with(visitor),
3246 NullaryOp(_, ty) => ty.visit_with(visitor),
3247 Aggregate(ref kind, ref fields) => {
3249 AggregateKind::Array(ty) => ty.visit_with(visitor),
3250 AggregateKind::Tuple => false,
3251 AggregateKind::Adt(_, _, substs, user_ty, _) => {
3252 substs.visit_with(visitor) || user_ty.visit_with(visitor)
3254 AggregateKind::Closure(_, substs) => substs.visit_with(visitor),
3255 AggregateKind::Generator(_, substs, _) => substs.visit_with(visitor),
3256 }) || fields.visit_with(visitor)
3262 impl<'tcx> TypeFoldable<'tcx> for Operand<'tcx> {
3263 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
3265 Operand::Copy(ref place) => Operand::Copy(place.fold_with(folder)),
3266 Operand::Move(ref place) => Operand::Move(place.fold_with(folder)),
3267 Operand::Constant(ref c) => Operand::Constant(c.fold_with(folder)),
3271 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3273 Operand::Copy(ref place) | Operand::Move(ref place) => place.visit_with(visitor),
3274 Operand::Constant(ref c) => c.visit_with(visitor),
3279 impl<'tcx> TypeFoldable<'tcx> for PlaceElem<'tcx> {
3280 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
3281 use crate::mir::ProjectionElem::*;
3285 Field(f, ty) => Field(*f, ty.fold_with(folder)),
3286 Index(v) => Index(v.fold_with(folder)),
3287 elem => elem.clone(),
3291 fn super_visit_with<Vs: TypeVisitor<'tcx>>(&self, visitor: &mut Vs) -> bool {
3292 use crate::mir::ProjectionElem::*;
3295 Field(_, ty) => ty.visit_with(visitor),
3296 Index(v) => v.visit_with(visitor),
3302 impl<'tcx> TypeFoldable<'tcx> for Field {
3303 fn super_fold_with<F: TypeFolder<'tcx>>(&self, _: &mut F) -> Self {
3306 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, _: &mut V) -> bool {
3311 impl<'tcx> TypeFoldable<'tcx> for GeneratorSavedLocal {
3312 fn super_fold_with<F: TypeFolder<'tcx>>(&self, _: &mut F) -> Self {
3315 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, _: &mut V) -> bool {
3320 impl<'tcx, R: Idx, C: Idx> TypeFoldable<'tcx> for BitMatrix<R, C> {
3321 fn super_fold_with<F: TypeFolder<'tcx>>(&self, _: &mut F) -> Self {
3324 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, _: &mut V) -> bool {
3329 impl<'tcx> TypeFoldable<'tcx> for Constant<'tcx> {
3330 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
3332 span: self.span.clone(),
3333 user_ty: self.user_ty.fold_with(folder),
3334 literal: self.literal.fold_with(folder),
3337 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3338 self.literal.visit_with(visitor)