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;
25 use rustc_data_structures::graph::{self, 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};
35 use std::{iter, mem, option, u32};
36 use syntax::ast::Name;
37 use syntax::symbol::Symbol;
38 use syntax_pos::{Span, DUMMY_SP};
40 pub use crate::mir::interpret::AssertMessage;
41 pub use crate::mir::cache::BodyCache;
51 type LocalDecls<'tcx> = IndexVec<Local, LocalDecl<'tcx>>;
53 pub trait HasLocalDecls<'tcx> {
54 fn local_decls(&self) -> &LocalDecls<'tcx>;
57 impl<'tcx> HasLocalDecls<'tcx> for LocalDecls<'tcx> {
58 fn local_decls(&self) -> &LocalDecls<'tcx> {
63 impl<'tcx> HasLocalDecls<'tcx> for Body<'tcx> {
64 fn local_decls(&self) -> &LocalDecls<'tcx> {
69 /// The various "big phases" that MIR goes through.
71 /// Warning: ordering of variants is significant.
72 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, HashStable,
73 Debug, PartialEq, Eq, PartialOrd, Ord)]
82 /// Gets the index of the current MirPhase within the set of all `MirPhase`s.
83 pub fn phase_index(&self) -> usize {
88 /// The lowered representation of a single function.
89 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable, TypeFoldable)]
90 pub struct Body<'tcx> {
91 /// A list of basic blocks. References to basic block use a newtyped index type `BasicBlock`
92 /// that indexes into this vector.
93 basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
95 /// Records how far through the "desugaring and optimization" process this particular
96 /// MIR has traversed. This is particularly useful when inlining, since in that context
97 /// we instantiate the promoted constants and add them to our promoted vector -- but those
98 /// promoted items have already been optimized, whereas ours have not. This field allows
99 /// us to see the difference and forego optimization on the inlined promoted items.
102 /// A list of source scopes; these are referenced by statements
103 /// and used for debuginfo. Indexed by a `SourceScope`.
104 pub source_scopes: IndexVec<SourceScope, SourceScopeData>,
106 /// The yield type of the function, if it is a generator.
107 pub yield_ty: Option<Ty<'tcx>>,
109 /// Generator drop glue.
110 pub generator_drop: Option<Box<Body<'tcx>>>,
112 /// The layout of a generator. Produced by the state transformation.
113 pub generator_layout: Option<GeneratorLayout<'tcx>>,
115 /// If this is a generator then record the type of source expression that caused this generator
117 pub generator_kind: Option<GeneratorKind>,
119 /// Declarations of locals.
121 /// The first local is the return value pointer, followed by `arg_count`
122 /// locals for the function arguments, followed by any user-declared
123 /// variables and temporaries.
124 pub local_decls: LocalDecls<'tcx>,
126 /// User type annotations.
127 pub user_type_annotations: CanonicalUserTypeAnnotations<'tcx>,
129 /// The number of arguments this function takes.
131 /// Starting at local 1, `arg_count` locals will be provided by the caller
132 /// and can be assumed to be initialized.
134 /// If this MIR was built for a constant, this will be 0.
135 pub arg_count: usize,
137 /// Mark an argument local (which must be a tuple) as getting passed as
138 /// its individual components at the LLVM level.
140 /// This is used for the "rust-call" ABI.
141 pub spread_arg: Option<Local>,
143 /// Debug information pertaining to user variables, including captures.
144 pub var_debug_info: Vec<VarDebugInfo<'tcx>>,
146 /// Mark this MIR of a const context other than const functions as having converted a `&&` or
147 /// `||` expression into `&` or `|` respectively. This is problematic because if we ever stop
148 /// this conversion from happening and use short circuiting, we will cause the following code
149 /// to change the value of `x`: `let mut x = 42; false && { x = 55; true };`
151 /// List of places where control flow was destroyed. Used for error reporting.
152 pub control_flow_destroyed: Vec<(Span, String)>,
154 /// A span representing this MIR, for error reporting.
158 impl<'tcx> Body<'tcx> {
160 basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
161 source_scopes: IndexVec<SourceScope, SourceScopeData>,
162 local_decls: LocalDecls<'tcx>,
163 user_type_annotations: CanonicalUserTypeAnnotations<'tcx>,
165 var_debug_info: Vec<VarDebugInfo<'tcx>>,
167 control_flow_destroyed: Vec<(Span, String)>,
168 generator_kind : Option<GeneratorKind>,
170 // We need `arg_count` locals, and one for the return place.
172 local_decls.len() >= arg_count + 1,
173 "expected at least {} locals, got {}",
179 phase: MirPhase::Build,
183 generator_drop: None,
184 generator_layout: None,
187 user_type_annotations,
192 control_flow_destroyed,
197 pub fn basic_blocks(&self) -> &IndexVec<BasicBlock, BasicBlockData<'tcx>> {
201 /// Returns `true` if a cycle exists in the control-flow graph that is reachable from the
203 pub fn is_cfg_cyclic(&self) -> bool {
204 graph::is_cyclic(self)
208 pub fn local_kind(&self, local: Local) -> LocalKind {
209 let index = local.as_usize();
212 self.local_decls[local].mutability == Mutability::Mut,
213 "return place should be mutable"
216 LocalKind::ReturnPointer
217 } else if index < self.arg_count + 1 {
219 } else if self.local_decls[local].is_user_variable() {
226 /// Returns an iterator over all temporaries.
228 pub fn temps_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
229 (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
230 let local = Local::new(index);
231 if self.local_decls[local].is_user_variable() {
239 /// Returns an iterator over all user-declared locals.
241 pub fn vars_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
242 (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
243 let local = Local::new(index);
244 if self.local_decls[local].is_user_variable() {
252 /// Returns an iterator over all user-declared mutable locals.
254 pub fn mut_vars_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
255 (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
256 let local = Local::new(index);
257 let decl = &self.local_decls[local];
258 if decl.is_user_variable() && decl.mutability == Mutability::Mut {
266 /// Returns an iterator over all user-declared mutable arguments and locals.
268 pub fn mut_vars_and_args_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
269 (1..self.local_decls.len()).filter_map(move |index| {
270 let local = Local::new(index);
271 let decl = &self.local_decls[local];
272 if (decl.is_user_variable() || index < self.arg_count + 1)
273 && decl.mutability == Mutability::Mut
282 /// Returns an iterator over all function arguments.
284 pub fn args_iter(&self) -> impl Iterator<Item = Local> {
285 let arg_count = self.arg_count;
286 (1..=arg_count).map(Local::new)
289 /// Returns an iterator over all user-defined variables and compiler-generated temporaries (all
290 /// locals that are neither arguments nor the return place).
292 pub fn vars_and_temps_iter(&self) -> impl Iterator<Item = Local> {
293 let arg_count = self.arg_count;
294 let local_count = self.local_decls.len();
295 (arg_count + 1..local_count).map(Local::new)
298 /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
299 /// invalidating statement indices in `Location`s.
300 pub fn make_statement_nop(&mut self, location: Location) {
301 let block = &mut self.basic_blocks[location.block];
302 debug_assert!(location.statement_index < block.statements.len());
303 block.statements[location.statement_index].make_nop()
306 /// Returns the source info associated with `location`.
307 pub fn source_info(&self, location: Location) -> &SourceInfo {
308 let block = &self[location.block];
309 let stmts = &block.statements;
310 let idx = location.statement_index;
311 if idx < stmts.len() {
312 &stmts[idx].source_info
314 assert_eq!(idx, stmts.len());
315 &block.terminator().source_info
319 /// Checks if `sub` is a sub scope of `sup`
320 pub fn is_sub_scope(&self, mut sub: SourceScope, sup: SourceScope) -> bool {
322 match self.source_scopes[sub].parent_scope {
323 None => return false,
330 /// Returns the return type; it always return first element from `local_decls` array.
331 pub fn return_ty(&self) -> Ty<'tcx> {
332 self.local_decls[RETURN_PLACE].ty
335 /// Gets the location of the terminator for the given block.
336 pub fn terminator_loc(&self, bb: BasicBlock) -> Location {
337 Location { block: bb, statement_index: self[bb].statements.len() }
341 #[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
344 /// Unsafe because of a PushUnsafeBlock
346 /// Unsafe because of an unsafe fn
348 /// Unsafe because of an `unsafe` block
349 ExplicitUnsafe(hir::HirId),
352 impl<'tcx> Index<BasicBlock> for Body<'tcx> {
353 type Output = BasicBlockData<'tcx>;
356 fn index(&self, index: BasicBlock) -> &BasicBlockData<'tcx> {
357 &self.basic_blocks()[index]
361 #[derive(Copy, Clone, Debug, HashStable, TypeFoldable)]
362 pub enum ClearCrossCrate<T> {
367 impl<T> ClearCrossCrate<T> {
368 pub fn as_ref(&'a self) -> ClearCrossCrate<&'a T> {
370 ClearCrossCrate::Clear => ClearCrossCrate::Clear,
371 ClearCrossCrate::Set(v) => ClearCrossCrate::Set(v),
375 pub fn assert_crate_local(self) -> T {
377 ClearCrossCrate::Clear => bug!("unwrapping cross-crate data"),
378 ClearCrossCrate::Set(v) => v,
383 impl<T: Encodable> rustc_serialize::UseSpecializedEncodable for ClearCrossCrate<T> {}
384 impl<T: Decodable> rustc_serialize::UseSpecializedDecodable for ClearCrossCrate<T> {}
386 /// Grouped information about the source code origin of a MIR entity.
387 /// Intended to be inspected by diagnostics and debuginfo.
388 /// Most passes can work with it as a whole, within a single function.
389 // The unofficial Cranelift backend, at least as of #65828, needs `SourceInfo` to implement `Eq` and
390 // `Hash`. Please ping @bjorn3 if removing them.
391 #[derive(Copy, Clone, Debug, Eq, PartialEq, RustcEncodable, RustcDecodable, Hash, HashStable)]
392 pub struct SourceInfo {
393 /// The source span for the AST pertaining to this MIR entity.
396 /// The source scope, keeping track of which bindings can be
397 /// seen by debuginfo, active lint levels, `unsafe {...}`, etc.
398 pub scope: SourceScope,
401 ///////////////////////////////////////////////////////////////////////////
402 // Mutability and borrow kinds
404 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
405 pub enum Mutability {
410 impl From<Mutability> for hir::Mutability {
411 fn from(m: Mutability) -> Self {
413 Mutability::Mut => hir::Mutability::Mutable,
414 Mutability::Not => hir::Mutability::Immutable,
420 Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, HashStable,
422 pub enum BorrowKind {
423 /// Data must be immutable and is aliasable.
426 /// The immediately borrowed place must be immutable, but projections from
427 /// it don't need to be. For example, a shallow borrow of `a.b` doesn't
428 /// conflict with a mutable borrow of `a.b.c`.
430 /// This is used when lowering matches: when matching on a place we want to
431 /// ensure that place have the same value from the start of the match until
432 /// an arm is selected. This prevents this code from compiling:
434 /// let mut x = &Some(0);
437 /// Some(_) if { x = &None; false } => (),
441 /// This can't be a shared borrow because mutably borrowing (*x as Some).0
442 /// should not prevent `if let None = x { ... }`, for example, because the
443 /// mutating `(*x as Some).0` can't affect the discriminant of `x`.
444 /// We can also report errors with this kind of borrow differently.
447 /// Data must be immutable but not aliasable. This kind of borrow
448 /// cannot currently be expressed by the user and is used only in
449 /// implicit closure bindings. It is needed when the closure is
450 /// borrowing or mutating a mutable referent, e.g.:
452 /// let x: &mut isize = ...;
453 /// let y = || *x += 5;
455 /// If we were to try to translate this closure into a more explicit
456 /// form, we'd encounter an error with the code as written:
458 /// struct Env { x: & &mut isize }
459 /// let x: &mut isize = ...;
460 /// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn
461 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
463 /// This is then illegal because you cannot mutate an `&mut` found
464 /// in an aliasable location. To solve, you'd have to translate with
465 /// an `&mut` borrow:
467 /// struct Env { x: & &mut isize }
468 /// let x: &mut isize = ...;
469 /// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
470 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
472 /// Now the assignment to `**env.x` is legal, but creating a
473 /// mutable pointer to `x` is not because `x` is not mutable. We
474 /// could fix this by declaring `x` as `let mut x`. This is ok in
475 /// user code, if awkward, but extra weird for closures, since the
476 /// borrow is hidden.
478 /// So we introduce a "unique imm" borrow -- the referent is
479 /// immutable, but not aliasable. This solves the problem. For
480 /// simplicity, we don't give users the way to express this
481 /// borrow, it's just used when translating closures.
484 /// Data is mutable and not aliasable.
486 /// `true` if this borrow arose from method-call auto-ref
487 /// (i.e., `adjustment::Adjust::Borrow`).
488 allow_two_phase_borrow: bool,
493 pub fn allows_two_phase_borrow(&self) -> bool {
495 BorrowKind::Shared | BorrowKind::Shallow | BorrowKind::Unique => false,
496 BorrowKind::Mut { allow_two_phase_borrow } => allow_two_phase_borrow,
501 ///////////////////////////////////////////////////////////////////////////
502 // Variables and temps
504 rustc_index::newtype_index! {
507 DEBUG_FORMAT = "_{}",
508 const RETURN_PLACE = 0,
512 impl Atom for Local {
513 fn index(self) -> usize {
518 /// Classifies locals into categories. See `Body::local_kind`.
519 #[derive(PartialEq, Eq, Debug, HashStable)]
521 /// User-declared variable binding.
523 /// Compiler-introduced temporary.
525 /// Function argument.
527 /// Location of function's return value.
531 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
532 pub struct VarBindingForm<'tcx> {
533 /// Is variable bound via `x`, `mut x`, `ref x`, or `ref mut x`?
534 pub binding_mode: ty::BindingMode,
535 /// If an explicit type was provided for this variable binding,
536 /// this holds the source Span of that type.
538 /// NOTE: if you want to change this to a `HirId`, be wary that
539 /// doing so breaks incremental compilation (as of this writing),
540 /// while a `Span` does not cause our tests to fail.
541 pub opt_ty_info: Option<Span>,
542 /// Place of the RHS of the =, or the subject of the `match` where this
543 /// variable is initialized. None in the case of `let PATTERN;`.
544 /// Some((None, ..)) in the case of and `let [mut] x = ...` because
545 /// (a) the right-hand side isn't evaluated as a place expression.
546 /// (b) it gives a way to separate this case from the remaining cases
548 pub opt_match_place: Option<(Option<Place<'tcx>>, Span)>,
549 /// The span of the pattern in which this variable was bound.
553 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
554 pub enum BindingForm<'tcx> {
555 /// This is a binding for a non-`self` binding, or a `self` that has an explicit type.
556 Var(VarBindingForm<'tcx>),
557 /// Binding for a `self`/`&self`/`&mut self` binding where the type is implicit.
558 ImplicitSelf(ImplicitSelfKind),
559 /// Reference used in a guard expression to ensure immutability.
563 /// Represents what type of implicit self a function has, if any.
564 #[derive(Clone, Copy, PartialEq, Debug, RustcEncodable, RustcDecodable, HashStable)]
565 pub enum ImplicitSelfKind {
566 /// Represents a `fn x(self);`.
568 /// Represents a `fn x(mut self);`.
570 /// Represents a `fn x(&self);`.
572 /// Represents a `fn x(&mut self);`.
574 /// Represents when a function does not have a self argument or
575 /// when a function has a `self: X` argument.
579 CloneTypeFoldableAndLiftImpls! { BindingForm<'tcx>, }
581 mod binding_form_impl {
582 use crate::ich::StableHashingContext;
583 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
585 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for super::BindingForm<'tcx> {
586 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
587 use super::BindingForm::*;
588 ::std::mem::discriminant(self).hash_stable(hcx, hasher);
591 Var(binding) => binding.hash_stable(hcx, hasher),
592 ImplicitSelf(kind) => kind.hash_stable(hcx, hasher),
599 /// `BlockTailInfo` is attached to the `LocalDecl` for temporaries
600 /// created during evaluation of expressions in a block tail
601 /// expression; that is, a block like `{ STMT_1; STMT_2; EXPR }`.
603 /// It is used to improve diagnostics when such temporaries are
604 /// involved in borrow_check errors, e.g., explanations of where the
605 /// temporaries come from, when their destructors are run, and/or how
606 /// one might revise the code to satisfy the borrow checker's rules.
607 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
608 pub struct BlockTailInfo {
609 /// If `true`, then the value resulting from evaluating this tail
610 /// expression is ignored by the block's expression context.
612 /// Examples include `{ ...; tail };` and `let _ = { ...; tail };`
613 /// but not e.g., `let _x = { ...; tail };`
614 pub tail_result_is_ignored: bool,
619 /// This can be a binding declared by the user, a temporary inserted by the compiler, a function
620 /// argument, or the return place.
621 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
622 pub struct LocalDecl<'tcx> {
623 /// Whether this is a mutable minding (i.e., `let x` or `let mut x`).
625 /// Temporaries and the return place are always mutable.
626 pub mutability: Mutability,
628 // FIXME(matthewjasper) Don't store in this in `Body`
629 pub local_info: LocalInfo<'tcx>,
631 /// `true` if this is an internal local.
633 /// These locals are not based on types in the source code and are only used
634 /// for a few desugarings at the moment.
636 /// The generator transformation will sanity check the locals which are live
637 /// across a suspension point against the type components of the generator
638 /// which type checking knows are live across a suspension point. We need to
639 /// flag drop flags to avoid triggering this check as they are introduced
642 /// Unsafety checking will also ignore dereferences of these locals,
643 /// so they can be used for raw pointers only used in a desugaring.
645 /// This should be sound because the drop flags are fully algebraic, and
646 /// therefore don't affect the OIBIT or outlives properties of the
650 /// If this local is a temporary and `is_block_tail` is `Some`,
651 /// then it is a temporary created for evaluation of some
652 /// subexpression of some block's tail expression (with no
653 /// intervening statement context).
654 // FIXME(matthewjasper) Don't store in this in `Body`
655 pub is_block_tail: Option<BlockTailInfo>,
657 /// The type of this local.
660 /// If the user manually ascribed a type to this variable,
661 /// e.g., via `let x: T`, then we carry that type here. The MIR
662 /// borrow checker needs this information since it can affect
663 /// region inference.
664 // FIXME(matthewjasper) Don't store in this in `Body`
665 pub user_ty: UserTypeProjections,
667 /// The *syntactic* (i.e., not visibility) source scope the local is defined
668 /// in. If the local was defined in a let-statement, this
669 /// is *within* the let-statement, rather than outside
672 /// This is needed because the visibility source scope of locals within
673 /// a let-statement is weird.
675 /// The reason is that we want the local to be *within* the let-statement
676 /// for lint purposes, but we want the local to be *after* the let-statement
677 /// for names-in-scope purposes.
679 /// That's it, if we have a let-statement like the one in this
683 /// fn foo(x: &str) {
684 /// #[allow(unused_mut)]
685 /// let mut x: u32 = { // <- one unused mut
686 /// let mut y: u32 = x.parse().unwrap();
693 /// Then, from a lint point of view, the declaration of `x: u32`
694 /// (and `y: u32`) are within the `#[allow(unused_mut)]` scope - the
695 /// lint scopes are the same as the AST/HIR nesting.
697 /// However, from a name lookup point of view, the scopes look more like
698 /// as if the let-statements were `match` expressions:
701 /// fn foo(x: &str) {
703 /// match x.parse().unwrap() {
712 /// We care about the name-lookup scopes for debuginfo - if the
713 /// debuginfo instruction pointer is at the call to `x.parse()`, we
714 /// want `x` to refer to `x: &str`, but if it is at the call to
715 /// `drop(x)`, we want it to refer to `x: u32`.
717 /// To allow both uses to work, we need to have more than a single scope
718 /// for a local. We have the `source_info.scope` represent the "syntactic"
719 /// lint scope (with a variable being under its let block) while the
720 /// `var_debug_info.source_info.scope` represents the "local variable"
721 /// scope (where the "rest" of a block is under all prior let-statements).
723 /// The end result looks like this:
727 /// │{ argument x: &str }
729 /// │ │{ #[allow(unused_mut)] } // This is actually split into 2 scopes
730 /// │ │ // in practice because I'm lazy.
732 /// │ │← x.source_info.scope
733 /// │ │← `x.parse().unwrap()`
735 /// │ │ │← y.source_info.scope
737 /// │ │ │{ let y: u32 }
739 /// │ │ │← y.var_debug_info.source_info.scope
742 /// │ │{ let x: u32 }
743 /// │ │← x.var_debug_info.source_info.scope
744 /// │ │← `drop(x)` // This accesses `x: u32`.
746 pub source_info: SourceInfo,
749 /// Extra information about a local that's used for diagnostics.
750 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
751 pub enum LocalInfo<'tcx> {
752 /// A user-defined local variable or function parameter
754 /// The `BindingForm` is solely used for local diagnostics when generating
755 /// warnings/errors when compiling the current crate, and therefore it need
756 /// not be visible across crates.
757 User(ClearCrossCrate<BindingForm<'tcx>>),
758 /// A temporary created that references the static with the given `DefId`.
759 StaticRef { def_id: DefId, is_thread_local: bool },
760 /// Any other temporary, the return place, or an anonymous function parameter.
764 impl<'tcx> LocalDecl<'tcx> {
765 /// Returns `true` only if local is a binding that can itself be
766 /// made mutable via the addition of the `mut` keyword, namely
767 /// something like the occurrences of `x` in:
768 /// - `fn foo(x: Type) { ... }`,
770 /// - or `match ... { C(x) => ... }`
771 pub fn can_be_made_mutable(&self) -> bool {
772 match self.local_info {
773 LocalInfo::User(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
774 binding_mode: ty::BindingMode::BindByValue(_),
781 ClearCrossCrate::Set(BindingForm::ImplicitSelf(ImplicitSelfKind::Imm)),
788 /// Returns `true` if local is definitely not a `ref ident` or
789 /// `ref mut ident` binding. (Such bindings cannot be made into
790 /// mutable bindings, but the inverse does not necessarily hold).
791 pub fn is_nonref_binding(&self) -> bool {
792 match self.local_info {
793 LocalInfo::User(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
794 binding_mode: ty::BindingMode::BindByValue(_),
800 LocalInfo::User(ClearCrossCrate::Set(BindingForm::ImplicitSelf(_))) => true,
806 /// Returns `true` if this variable is a named variable or function
807 /// parameter declared by the user.
809 pub fn is_user_variable(&self) -> bool {
810 match self.local_info {
811 LocalInfo::User(_) => true,
816 /// Returns `true` if this is a reference to a variable bound in a `match`
817 /// expression that is used to access said variable for the guard of the
819 pub fn is_ref_for_guard(&self) -> bool {
820 match self.local_info {
821 LocalInfo::User(ClearCrossCrate::Set(BindingForm::RefForGuard)) => true,
826 /// Returns `Some` if this is a reference to a static item that is used to
827 /// access that static
828 pub fn is_ref_to_static(&self) -> bool {
829 match self.local_info {
830 LocalInfo::StaticRef { .. } => true,
835 /// Returns `Some` if this is a reference to a static item that is used to
836 /// access that static
837 pub fn is_ref_to_thread_local(&self) -> bool {
838 match self.local_info {
839 LocalInfo::StaticRef { is_thread_local, .. } => is_thread_local,
844 /// Returns `true` is the local is from a compiler desugaring, e.g.,
845 /// `__next` from a `for` loop.
847 pub fn from_compiler_desugaring(&self) -> bool {
848 self.source_info.span.desugaring_kind().is_some()
851 /// Creates a new `LocalDecl` for a temporary.
853 pub fn new_temp(ty: Ty<'tcx>, span: Span) -> Self {
854 Self::new_local(ty, Mutability::Mut, false, span)
857 /// Converts `self` into same `LocalDecl` except tagged as immutable.
859 pub fn immutable(mut self) -> Self {
860 self.mutability = Mutability::Not;
864 /// Converts `self` into same `LocalDecl` except tagged as internal temporary.
866 pub fn block_tail(mut self, info: BlockTailInfo) -> Self {
867 assert!(self.is_block_tail.is_none());
868 self.is_block_tail = Some(info);
872 /// Creates a new `LocalDecl` for a internal temporary.
874 pub fn new_internal(ty: Ty<'tcx>, span: Span) -> Self {
875 Self::new_local(ty, Mutability::Mut, true, span)
879 fn new_local(ty: Ty<'tcx>, mutability: Mutability, internal: bool, span: Span) -> Self {
883 user_ty: UserTypeProjections::none(),
884 source_info: SourceInfo { span, scope: OUTERMOST_SOURCE_SCOPE },
886 local_info: LocalInfo::Other,
891 /// Builds a `LocalDecl` for the return place.
893 /// This must be inserted into the `local_decls` list as the first local.
895 pub fn new_return_place(return_ty: Ty<'_>, span: Span) -> LocalDecl<'_> {
897 mutability: Mutability::Mut,
899 user_ty: UserTypeProjections::none(),
900 source_info: SourceInfo { span, scope: OUTERMOST_SOURCE_SCOPE },
903 local_info: LocalInfo::Other,
908 /// Debug information pertaining to a user variable.
909 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
910 pub struct VarDebugInfo<'tcx> {
913 /// Source info of the user variable, including the scope
914 /// within which the variable is visible (to debuginfo)
915 /// (see `LocalDecl`'s `source_info` field for more details).
916 pub source_info: SourceInfo,
918 /// Where the data for this user variable is to be found.
919 /// NOTE(eddyb) There's an unenforced invariant that this `Place` is
920 /// based on a `Local`, not a `Static`, and contains no indexing.
921 pub place: Place<'tcx>,
924 ///////////////////////////////////////////////////////////////////////////
927 rustc_index::newtype_index! {
928 pub struct BasicBlock {
930 DEBUG_FORMAT = "bb{}",
931 const START_BLOCK = 0,
936 pub fn start_location(self) -> Location {
937 Location { block: self, statement_index: 0 }
941 ///////////////////////////////////////////////////////////////////////////
942 // BasicBlockData and Terminator
944 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
945 pub struct BasicBlockData<'tcx> {
946 /// List of statements in this block.
947 pub statements: Vec<Statement<'tcx>>,
949 /// Terminator for this block.
951 /// N.B., this should generally ONLY be `None` during construction.
952 /// Therefore, you should generally access it via the
953 /// `terminator()` or `terminator_mut()` methods. The only
954 /// exception is that certain passes, such as `simplify_cfg`, swap
955 /// out the terminator temporarily with `None` while they continue
956 /// to recurse over the set of basic blocks.
957 pub terminator: Option<Terminator<'tcx>>,
959 /// If true, this block lies on an unwind path. This is used
960 /// during codegen where distinct kinds of basic blocks may be
961 /// generated (particularly for MSVC cleanup). Unwind blocks must
962 /// only branch to other unwind blocks.
963 pub is_cleanup: bool,
966 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
967 pub struct Terminator<'tcx> {
968 pub source_info: SourceInfo,
969 pub kind: TerminatorKind<'tcx>,
972 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable, PartialEq)]
973 pub enum TerminatorKind<'tcx> {
974 /// Block should have one successor in the graph; we jump there.
975 Goto { target: BasicBlock },
977 /// Operand evaluates to an integer; jump depending on its value
978 /// to one of the targets, and otherwise fallback to `otherwise`.
980 /// The discriminant value being tested.
981 discr: Operand<'tcx>,
983 /// The type of value being tested.
986 /// Possible values. The locations to branch to in each case
987 /// are found in the corresponding indices from the `targets` vector.
988 values: Cow<'tcx, [u128]>,
990 /// Possible branch sites. The last element of this vector is used
991 /// for the otherwise branch, so targets.len() == values.len() + 1
994 // This invariant is quite non-obvious and also could be improved.
995 // One way to make this invariant is to have something like this instead:
997 // branches: Vec<(ConstInt, BasicBlock)>,
998 // otherwise: Option<BasicBlock> // exhaustive if None
1000 // However we’ve decided to keep this as-is until we figure a case
1001 // where some other approach seems to be strictly better than other.
1002 targets: Vec<BasicBlock>,
1005 /// Indicates that the landing pad is finished and unwinding should
1006 /// continue. Emitted by `build::scope::diverge_cleanup`.
1009 /// Indicates that the landing pad is finished and that the process
1010 /// should abort. Used to prevent unwinding for foreign items.
1013 /// Indicates a normal return. The return place should have
1014 /// been filled in by now. This should occur at most once.
1017 /// Indicates a terminator that can never be reached.
1020 /// Drop the `Place`.
1021 Drop { location: Place<'tcx>, target: BasicBlock, unwind: Option<BasicBlock> },
1023 /// Drop the `Place` and assign the new value over it. This ensures
1024 /// that the assignment to `P` occurs *even if* the destructor for
1025 /// place unwinds. Its semantics are best explained by the
1030 /// DropAndReplace(P <- V, goto BB1, unwind BB2)
1038 /// Drop(P, goto BB1, unwind BB2)
1041 /// // P is now uninitialized
1045 /// // P is now uninitialized -- its dtor panicked
1050 location: Place<'tcx>,
1051 value: Operand<'tcx>,
1053 unwind: Option<BasicBlock>,
1056 /// Block ends with a call of a converging function.
1058 /// The function that’s being called.
1059 func: Operand<'tcx>,
1060 /// Arguments the function is called with.
1061 /// These are owned by the callee, which is free to modify them.
1062 /// This allows the memory occupied by "by-value" arguments to be
1063 /// reused across function calls without duplicating the contents.
1064 args: Vec<Operand<'tcx>>,
1065 /// Destination for the return value. If some, the call is converging.
1066 destination: Option<(Place<'tcx>, BasicBlock)>,
1067 /// Cleanups to be done if the call unwinds.
1068 cleanup: Option<BasicBlock>,
1069 /// `true` if this is from a call in HIR rather than from an overloaded
1070 /// operator. True for overloaded function call.
1071 from_hir_call: bool,
1074 /// Jump to the target if the condition has the expected value,
1075 /// otherwise panic with a message and a cleanup target.
1077 cond: Operand<'tcx>,
1079 msg: AssertMessage<'tcx>,
1081 cleanup: Option<BasicBlock>,
1084 /// A suspend point.
1086 /// The value to return.
1087 value: Operand<'tcx>,
1088 /// Where to resume to.
1090 /// Cleanup to be done if the generator is dropped at this suspend point.
1091 drop: Option<BasicBlock>,
1094 /// Indicates the end of the dropping of a generator.
1097 /// A block where control flow only ever takes one real path, but borrowck
1098 /// needs to be more conservative.
1100 /// The target normal control flow will take.
1101 real_target: BasicBlock,
1102 /// A block control flow could conceptually jump to, but won't in
1104 imaginary_target: BasicBlock,
1106 /// A terminator for blocks that only take one path in reality, but where we
1107 /// reserve the right to unwind in borrowck, even if it won't happen in practice.
1108 /// This can arise in infinite loops with no function calls for example.
1110 /// The target normal control flow will take.
1111 real_target: BasicBlock,
1112 /// The imaginary cleanup block link. This particular path will never be taken
1113 /// in practice, but in order to avoid fragility we want to always
1114 /// consider it in borrowck. We don't want to accept programs which
1115 /// pass borrowck only when `panic=abort` or some assertions are disabled
1116 /// due to release vs. debug mode builds. This needs to be an `Option` because
1117 /// of the `remove_noop_landing_pads` and `no_landing_pads` passes.
1118 unwind: Option<BasicBlock>,
1122 pub type Successors<'a> =
1123 iter::Chain<option::IntoIter<&'a BasicBlock>, slice::Iter<'a, BasicBlock>>;
1124 pub type SuccessorsMut<'a> =
1125 iter::Chain<option::IntoIter<&'a mut BasicBlock>, slice::IterMut<'a, BasicBlock>>;
1127 impl<'tcx> Terminator<'tcx> {
1128 pub fn successors(&self) -> Successors<'_> {
1129 self.kind.successors()
1132 pub fn successors_mut(&mut self) -> SuccessorsMut<'_> {
1133 self.kind.successors_mut()
1136 pub fn unwind(&self) -> Option<&Option<BasicBlock>> {
1140 pub fn unwind_mut(&mut self) -> Option<&mut Option<BasicBlock>> {
1141 self.kind.unwind_mut()
1145 impl<'tcx> TerminatorKind<'tcx> {
1148 cond: Operand<'tcx>,
1151 ) -> TerminatorKind<'tcx> {
1152 static BOOL_SWITCH_FALSE: &'static [u128] = &[0];
1153 TerminatorKind::SwitchInt {
1155 switch_ty: tcx.types.bool,
1156 values: From::from(BOOL_SWITCH_FALSE),
1157 targets: vec![f, t],
1161 pub fn successors(&self) -> Successors<'_> {
1162 use self::TerminatorKind::*;
1169 | Call { destination: None, cleanup: None, .. } => None.into_iter().chain(&[]),
1170 Goto { target: ref t }
1171 | Call { destination: None, cleanup: Some(ref t), .. }
1172 | Call { destination: Some((_, ref t)), cleanup: None, .. }
1173 | Yield { resume: ref t, drop: None, .. }
1174 | DropAndReplace { target: ref t, unwind: None, .. }
1175 | Drop { target: ref t, unwind: None, .. }
1176 | Assert { target: ref t, cleanup: None, .. }
1177 | FalseUnwind { real_target: ref t, unwind: None } => Some(t).into_iter().chain(&[]),
1178 Call { destination: Some((_, ref t)), cleanup: Some(ref u), .. }
1179 | Yield { resume: ref t, drop: Some(ref u), .. }
1180 | DropAndReplace { target: ref t, unwind: Some(ref u), .. }
1181 | Drop { target: ref t, unwind: Some(ref u), .. }
1182 | Assert { target: ref t, cleanup: Some(ref u), .. }
1183 | FalseUnwind { real_target: ref t, unwind: Some(ref u) } => {
1184 Some(t).into_iter().chain(slice::from_ref(u))
1186 SwitchInt { ref targets, .. } => None.into_iter().chain(&targets[..]),
1187 FalseEdges { ref real_target, ref imaginary_target } => {
1188 Some(real_target).into_iter().chain(slice::from_ref(imaginary_target))
1193 pub fn successors_mut(&mut self) -> SuccessorsMut<'_> {
1194 use self::TerminatorKind::*;
1201 | Call { destination: None, cleanup: None, .. } => None.into_iter().chain(&mut []),
1202 Goto { target: ref mut t }
1203 | Call { destination: None, cleanup: Some(ref mut t), .. }
1204 | Call { destination: Some((_, ref mut t)), cleanup: None, .. }
1205 | Yield { resume: ref mut t, drop: None, .. }
1206 | DropAndReplace { target: ref mut t, unwind: None, .. }
1207 | Drop { target: ref mut t, unwind: None, .. }
1208 | Assert { target: ref mut t, cleanup: None, .. }
1209 | FalseUnwind { real_target: ref mut t, unwind: None } => {
1210 Some(t).into_iter().chain(&mut [])
1212 Call { destination: Some((_, ref mut t)), cleanup: Some(ref mut u), .. }
1213 | Yield { resume: ref mut t, drop: Some(ref mut u), .. }
1214 | DropAndReplace { target: ref mut t, unwind: Some(ref mut u), .. }
1215 | Drop { target: ref mut t, unwind: Some(ref mut u), .. }
1216 | Assert { target: ref mut t, cleanup: Some(ref mut u), .. }
1217 | FalseUnwind { real_target: ref mut t, unwind: Some(ref mut u) } => {
1218 Some(t).into_iter().chain(slice::from_mut(u))
1220 SwitchInt { ref mut targets, .. } => None.into_iter().chain(&mut targets[..]),
1221 FalseEdges { ref mut real_target, ref mut imaginary_target } => {
1222 Some(real_target).into_iter().chain(slice::from_mut(imaginary_target))
1227 pub fn unwind(&self) -> Option<&Option<BasicBlock>> {
1229 TerminatorKind::Goto { .. }
1230 | TerminatorKind::Resume
1231 | TerminatorKind::Abort
1232 | TerminatorKind::Return
1233 | TerminatorKind::Unreachable
1234 | TerminatorKind::GeneratorDrop
1235 | TerminatorKind::Yield { .. }
1236 | TerminatorKind::SwitchInt { .. }
1237 | TerminatorKind::FalseEdges { .. } => None,
1238 TerminatorKind::Call { cleanup: ref unwind, .. }
1239 | TerminatorKind::Assert { cleanup: ref unwind, .. }
1240 | TerminatorKind::DropAndReplace { ref unwind, .. }
1241 | TerminatorKind::Drop { ref unwind, .. }
1242 | TerminatorKind::FalseUnwind { ref unwind, .. } => Some(unwind),
1246 pub fn unwind_mut(&mut self) -> Option<&mut Option<BasicBlock>> {
1248 TerminatorKind::Goto { .. }
1249 | TerminatorKind::Resume
1250 | TerminatorKind::Abort
1251 | TerminatorKind::Return
1252 | TerminatorKind::Unreachable
1253 | TerminatorKind::GeneratorDrop
1254 | TerminatorKind::Yield { .. }
1255 | TerminatorKind::SwitchInt { .. }
1256 | TerminatorKind::FalseEdges { .. } => None,
1257 TerminatorKind::Call { cleanup: ref mut unwind, .. }
1258 | TerminatorKind::Assert { cleanup: ref mut unwind, .. }
1259 | TerminatorKind::DropAndReplace { ref mut unwind, .. }
1260 | TerminatorKind::Drop { ref mut unwind, .. }
1261 | TerminatorKind::FalseUnwind { ref mut unwind, .. } => Some(unwind),
1266 impl<'tcx> BasicBlockData<'tcx> {
1267 pub fn new(terminator: Option<Terminator<'tcx>>) -> BasicBlockData<'tcx> {
1268 BasicBlockData { statements: vec![], terminator, is_cleanup: false }
1271 /// Accessor for terminator.
1273 /// Terminator may not be None after construction of the basic block is complete. This accessor
1274 /// provides a convenience way to reach the terminator.
1275 pub fn terminator(&self) -> &Terminator<'tcx> {
1276 self.terminator.as_ref().expect("invalid terminator state")
1279 pub fn terminator_mut(&mut self) -> &mut Terminator<'tcx> {
1280 self.terminator.as_mut().expect("invalid terminator state")
1283 pub fn retain_statements<F>(&mut self, mut f: F)
1285 F: FnMut(&mut Statement<'_>) -> bool,
1287 for s in &mut self.statements {
1294 pub fn expand_statements<F, I>(&mut self, mut f: F)
1296 F: FnMut(&mut Statement<'tcx>) -> Option<I>,
1297 I: iter::TrustedLen<Item = Statement<'tcx>>,
1299 // Gather all the iterators we'll need to splice in, and their positions.
1300 let mut splices: Vec<(usize, I)> = vec![];
1301 let mut extra_stmts = 0;
1302 for (i, s) in self.statements.iter_mut().enumerate() {
1303 if let Some(mut new_stmts) = f(s) {
1304 if let Some(first) = new_stmts.next() {
1305 // We can already store the first new statement.
1308 // Save the other statements for optimized splicing.
1309 let remaining = new_stmts.size_hint().0;
1311 splices.push((i + 1 + extra_stmts, new_stmts));
1312 extra_stmts += remaining;
1320 // Splice in the new statements, from the end of the block.
1321 // FIXME(eddyb) This could be more efficient with a "gap buffer"
1322 // where a range of elements ("gap") is left uninitialized, with
1323 // splicing adding new elements to the end of that gap and moving
1324 // existing elements from before the gap to the end of the gap.
1325 // For now, this is safe code, emulating a gap but initializing it.
1326 let mut gap = self.statements.len()..self.statements.len() + extra_stmts;
1327 self.statements.resize(
1330 source_info: SourceInfo { span: DUMMY_SP, scope: OUTERMOST_SOURCE_SCOPE },
1331 kind: StatementKind::Nop,
1334 for (splice_start, new_stmts) in splices.into_iter().rev() {
1335 let splice_end = splice_start + new_stmts.size_hint().0;
1336 while gap.end > splice_end {
1339 self.statements.swap(gap.start, gap.end);
1341 self.statements.splice(splice_start..splice_end, new_stmts);
1342 gap.end = splice_start;
1346 pub fn visitable(&self, index: usize) -> &dyn MirVisitable<'tcx> {
1347 if index < self.statements.len() {
1348 &self.statements[index]
1355 impl<'tcx> Debug for TerminatorKind<'tcx> {
1356 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1357 self.fmt_head(fmt)?;
1358 let successor_count = self.successors().count();
1359 let labels = self.fmt_successor_labels();
1360 assert_eq!(successor_count, labels.len());
1362 match successor_count {
1365 1 => write!(fmt, " -> {:?}", self.successors().nth(0).unwrap()),
1368 write!(fmt, " -> [")?;
1369 for (i, target) in self.successors().enumerate() {
1373 write!(fmt, "{}: {:?}", labels[i], target)?;
1381 impl<'tcx> TerminatorKind<'tcx> {
1382 /// Writes the "head" part of the terminator; that is, its name and the data it uses to pick the
1383 /// successor basic block, if any. The only information not included is the list of possible
1384 /// successors, which may be rendered differently between the text and the graphviz format.
1385 pub fn fmt_head<W: Write>(&self, fmt: &mut W) -> fmt::Result {
1386 use self::TerminatorKind::*;
1388 Goto { .. } => write!(fmt, "goto"),
1389 SwitchInt { discr: ref place, .. } => write!(fmt, "switchInt({:?})", place),
1390 Return => write!(fmt, "return"),
1391 GeneratorDrop => write!(fmt, "generator_drop"),
1392 Resume => write!(fmt, "resume"),
1393 Abort => write!(fmt, "abort"),
1394 Yield { ref value, .. } => write!(fmt, "_1 = suspend({:?})", value),
1395 Unreachable => write!(fmt, "unreachable"),
1396 Drop { ref location, .. } => write!(fmt, "drop({:?})", location),
1397 DropAndReplace { ref location, ref value, .. } => {
1398 write!(fmt, "replace({:?} <- {:?})", location, value)
1400 Call { ref func, ref args, ref destination, .. } => {
1401 if let Some((ref destination, _)) = *destination {
1402 write!(fmt, "{:?} = ", destination)?;
1404 write!(fmt, "{:?}(", func)?;
1405 for (index, arg) in args.iter().enumerate() {
1409 write!(fmt, "{:?}", arg)?;
1413 Assert { ref cond, expected, ref msg, .. } => {
1414 write!(fmt, "assert(")?;
1418 write!(fmt, "{:?}, \"{:?}\")", cond, msg)
1420 FalseEdges { .. } => write!(fmt, "falseEdges"),
1421 FalseUnwind { .. } => write!(fmt, "falseUnwind"),
1425 /// Returns the list of labels for the edges to the successor basic blocks.
1426 pub fn fmt_successor_labels(&self) -> Vec<Cow<'static, str>> {
1427 use self::TerminatorKind::*;
1429 Return | Resume | Abort | Unreachable | GeneratorDrop => vec![],
1430 Goto { .. } => vec!["".into()],
1431 SwitchInt { ref values, switch_ty, .. } => ty::tls::with(|tcx| {
1432 let param_env = ty::ParamEnv::empty();
1433 let switch_ty = tcx.lift(&switch_ty).unwrap();
1434 let size = tcx.layout_of(param_env.and(switch_ty)).unwrap().size;
1438 ty::Const::from_scalar(
1440 Scalar::from_uint(u, size).into(),
1446 .chain(iter::once("otherwise".into()))
1449 Call { destination: Some(_), cleanup: Some(_), .. } => {
1450 vec!["return".into(), "unwind".into()]
1452 Call { destination: Some(_), cleanup: None, .. } => vec!["return".into()],
1453 Call { destination: None, cleanup: Some(_), .. } => vec!["unwind".into()],
1454 Call { destination: None, cleanup: None, .. } => vec![],
1455 Yield { drop: Some(_), .. } => vec!["resume".into(), "drop".into()],
1456 Yield { drop: None, .. } => vec!["resume".into()],
1457 DropAndReplace { unwind: None, .. } | Drop { unwind: None, .. } => {
1458 vec!["return".into()]
1460 DropAndReplace { unwind: Some(_), .. } | Drop { unwind: Some(_), .. } => {
1461 vec!["return".into(), "unwind".into()]
1463 Assert { cleanup: None, .. } => vec!["".into()],
1464 Assert { .. } => vec!["success".into(), "unwind".into()],
1465 FalseEdges { .. } => vec!["real".into(), "imaginary".into()],
1466 FalseUnwind { unwind: Some(_), .. } => vec!["real".into(), "cleanup".into()],
1467 FalseUnwind { unwind: None, .. } => vec!["real".into()],
1472 ///////////////////////////////////////////////////////////////////////////
1475 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
1476 pub struct Statement<'tcx> {
1477 pub source_info: SourceInfo,
1478 pub kind: StatementKind<'tcx>,
1481 // `Statement` is used a lot. Make sure it doesn't unintentionally get bigger.
1482 #[cfg(target_arch = "x86_64")]
1483 static_assert_size!(Statement<'_>, 32);
1485 impl Statement<'_> {
1486 /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
1487 /// invalidating statement indices in `Location`s.
1488 pub fn make_nop(&mut self) {
1489 self.kind = StatementKind::Nop
1492 /// Changes a statement to a nop and returns the original statement.
1493 pub fn replace_nop(&mut self) -> Self {
1495 source_info: self.source_info,
1496 kind: mem::replace(&mut self.kind, StatementKind::Nop),
1501 #[derive(Clone, Debug, PartialEq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
1502 pub enum StatementKind<'tcx> {
1503 /// Write the RHS Rvalue to the LHS Place.
1504 Assign(Box<(Place<'tcx>, Rvalue<'tcx>)>),
1506 /// This represents all the reading that a pattern match may do
1507 /// (e.g., inspecting constants and discriminant values), and the
1508 /// kind of pattern it comes from. This is in order to adapt potential
1509 /// error messages to these specific patterns.
1511 /// Note that this also is emitted for regular `let` bindings to ensure that locals that are
1512 /// never accessed still get some sanity checks for, e.g., `let x: ! = ..;`
1513 FakeRead(FakeReadCause, Box<Place<'tcx>>),
1515 /// Write the discriminant for a variant to the enum Place.
1516 SetDiscriminant { place: Box<Place<'tcx>>, variant_index: VariantIdx },
1518 /// Start a live range for the storage of the local.
1521 /// End the current live range for the storage of the local.
1524 /// Executes a piece of inline Assembly. Stored in a Box to keep the size
1525 /// of `StatementKind` low.
1526 InlineAsm(Box<InlineAsm<'tcx>>),
1528 /// Retag references in the given place, ensuring they got fresh tags. This is
1529 /// part of the Stacked Borrows model. These statements are currently only interpreted
1530 /// by miri and only generated when "-Z mir-emit-retag" is passed.
1531 /// See <https://internals.rust-lang.org/t/stacked-borrows-an-aliasing-model-for-rust/8153/>
1532 /// for more details.
1533 Retag(RetagKind, Box<Place<'tcx>>),
1535 /// Encodes a user's type ascription. These need to be preserved
1536 /// intact so that NLL can respect them. For example:
1540 /// The effect of this annotation is to relate the type `T_y` of the place `y`
1541 /// to the user-given type `T`. The effect depends on the specified variance:
1543 /// - `Covariant` -- requires that `T_y <: T`
1544 /// - `Contravariant` -- requires that `T_y :> T`
1545 /// - `Invariant` -- requires that `T_y == T`
1546 /// - `Bivariant` -- no effect
1547 AscribeUserType(Box<(Place<'tcx>, UserTypeProjection)>, ty::Variance),
1549 /// No-op. Useful for deleting instructions without affecting statement indices.
1553 /// Describes what kind of retag is to be performed.
1554 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, PartialEq, Eq, HashStable)]
1555 pub enum RetagKind {
1556 /// The initial retag when entering a function.
1558 /// Retag preparing for a two-phase borrow.
1560 /// Retagging raw pointers.
1562 /// A "normal" retag.
1566 /// The `FakeReadCause` describes the type of pattern why a FakeRead statement exists.
1567 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable, PartialEq)]
1568 pub enum FakeReadCause {
1569 /// Inject a fake read of the borrowed input at the end of each guards
1572 /// This should ensure that you cannot change the variant for an enum while
1573 /// you are in the midst of matching on it.
1576 /// `let x: !; match x {}` doesn't generate any read of x so we need to
1577 /// generate a read of x to check that it is initialized and safe.
1580 /// A fake read of the RefWithinGuard version of a bind-by-value variable
1581 /// in a match guard to ensure that it's value hasn't change by the time
1582 /// we create the OutsideGuard version.
1585 /// Officially, the semantics of
1587 /// `let pattern = <expr>;`
1589 /// is that `<expr>` is evaluated into a temporary and then this temporary is
1590 /// into the pattern.
1592 /// However, if we see the simple pattern `let var = <expr>`, we optimize this to
1593 /// evaluate `<expr>` directly into the variable `var`. This is mostly unobservable,
1594 /// but in some cases it can affect the borrow checker, as in #53695.
1595 /// Therefore, we insert a "fake read" here to ensure that we get
1596 /// appropriate errors.
1599 /// If we have an index expression like
1601 /// (*x)[1][{ x = y; 4}]
1603 /// then the first bounds check is invalidated when we evaluate the second
1604 /// index expression. Thus we create a fake borrow of `x` across the second
1605 /// indexer, which will cause a borrow check error.
1609 #[derive(Clone, Debug, PartialEq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
1610 pub struct InlineAsm<'tcx> {
1611 pub asm: hir::InlineAsmInner,
1612 pub outputs: Box<[Place<'tcx>]>,
1613 pub inputs: Box<[(Span, Operand<'tcx>)]>,
1616 impl Debug for Statement<'_> {
1617 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1618 use self::StatementKind::*;
1620 Assign(box(ref place, ref rv)) => write!(fmt, "{:?} = {:?}", place, rv),
1621 FakeRead(ref cause, ref place) => write!(fmt, "FakeRead({:?}, {:?})", cause, place),
1622 Retag(ref kind, ref place) => write!(
1626 RetagKind::FnEntry => "[fn entry] ",
1627 RetagKind::TwoPhase => "[2phase] ",
1628 RetagKind::Raw => "[raw] ",
1629 RetagKind::Default => "",
1633 StorageLive(ref place) => write!(fmt, "StorageLive({:?})", place),
1634 StorageDead(ref place) => write!(fmt, "StorageDead({:?})", place),
1635 SetDiscriminant { ref place, variant_index } => {
1636 write!(fmt, "discriminant({:?}) = {:?}", place, variant_index)
1638 InlineAsm(ref asm) => {
1639 write!(fmt, "asm!({:?} : {:?} : {:?})", asm.asm, asm.outputs, asm.inputs)
1641 AscribeUserType(box(ref place, ref c_ty), ref variance) => {
1642 write!(fmt, "AscribeUserType({:?}, {:?}, {:?})", place, variance, c_ty)
1644 Nop => write!(fmt, "nop"),
1649 ///////////////////////////////////////////////////////////////////////////
1652 /// A path to a value; something that can be evaluated without
1653 /// changing or disturbing program state.
1655 Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, HashStable,
1657 pub struct Place<'tcx> {
1658 pub base: PlaceBase<'tcx>,
1660 /// projection out of a place (access a field, deref a pointer, etc)
1661 pub projection: &'tcx List<PlaceElem<'tcx>>,
1664 impl<'tcx> rustc_serialize::UseSpecializedDecodable for Place<'tcx> {}
1667 Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, HashStable,
1669 pub enum PlaceBase<'tcx> {
1673 /// static or static mut variable
1674 Static(Box<Static<'tcx>>),
1677 /// We store the normalized type to avoid requiring normalization when reading MIR
1678 #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash,
1679 RustcEncodable, RustcDecodable, HashStable)]
1680 pub struct Static<'tcx> {
1682 pub kind: StaticKind<'tcx>,
1683 /// The `DefId` of the item this static was declared in. For promoted values, usually, this is
1684 /// the same as the `DefId` of the `mir::Body` containing the `Place` this promoted appears in.
1685 /// However, after inlining, that might no longer be the case as inlined `Place`s are copied
1686 /// into the calling frame.
1691 Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, HashStable, RustcEncodable, RustcDecodable,
1693 pub enum StaticKind<'tcx> {
1694 /// Promoted references consist of an id (`Promoted`) and the substs necessary to monomorphize
1695 /// it. Usually, these substs are just the identity substs for the item. However, the inliner
1696 /// will adjust these substs when it inlines a function based on the substs at the callsite.
1697 Promoted(Promoted, SubstsRef<'tcx>),
1701 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
1702 #[derive(RustcEncodable, RustcDecodable, HashStable)]
1703 pub enum ProjectionElem<V, T> {
1708 /// These indices are generated by slice patterns. Easiest to explain
1712 /// [X, _, .._, _, _] => { offset: 0, min_length: 4, from_end: false },
1713 /// [_, X, .._, _, _] => { offset: 1, min_length: 4, from_end: false },
1714 /// [_, _, .._, X, _] => { offset: 2, min_length: 4, from_end: true },
1715 /// [_, _, .._, _, X] => { offset: 1, min_length: 4, from_end: true },
1718 /// index or -index (in Python terms), depending on from_end
1720 /// thing being indexed must be at least this long
1722 /// counting backwards from end?
1726 /// These indices are generated by slice patterns.
1728 /// slice[from:-to] in Python terms.
1734 /// "Downcast" to a variant of an ADT. Currently, we only introduce
1735 /// this for ADTs with more than one variant. It may be better to
1736 /// just introduce it always, or always for enums.
1738 /// The included Symbol is the name of the variant, used for printing MIR.
1739 Downcast(Option<Symbol>, VariantIdx),
1742 impl<V, T> ProjectionElem<V, T> {
1743 /// Returns `true` if the target of this projection may refer to a different region of memory
1745 fn is_indirect(&self) -> bool {
1747 Self::Deref => true,
1751 | Self::ConstantIndex { .. }
1752 | Self::Subslice { .. }
1753 | Self::Downcast(_, _)
1759 /// Alias for projections as they appear in places, where the base is a place
1760 /// and the index is a local.
1761 pub type PlaceElem<'tcx> = ProjectionElem<Local, Ty<'tcx>>;
1763 impl<'tcx> Copy for PlaceElem<'tcx> { }
1765 // At least on 64 bit systems, `PlaceElem` should not be larger than two pointers.
1766 #[cfg(target_arch = "x86_64")]
1767 static_assert_size!(PlaceElem<'_>, 16);
1769 /// Alias for projections as they appear in `UserTypeProjection`, where we
1770 /// need neither the `V` parameter for `Index` nor the `T` for `Field`.
1771 pub type ProjectionKind = ProjectionElem<(), ()>;
1773 rustc_index::newtype_index! {
1776 DEBUG_FORMAT = "field[{}]"
1780 #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
1781 pub struct PlaceRef<'a, 'tcx> {
1782 pub base: &'a PlaceBase<'tcx>,
1783 pub projection: &'a [PlaceElem<'tcx>],
1786 impl<'tcx> Place<'tcx> {
1787 // FIXME change this to a const fn by also making List::empty a const fn.
1788 pub fn return_place() -> Place<'tcx> {
1790 base: PlaceBase::Local(RETURN_PLACE),
1791 projection: List::empty(),
1795 /// Returns `true` if this `Place` contains a `Deref` projection.
1797 /// If `Place::is_indirect` returns false, the caller knows that the `Place` refers to the
1798 /// same region of memory as its base.
1799 pub fn is_indirect(&self) -> bool {
1800 self.projection.iter().any(|elem| elem.is_indirect())
1803 /// Finds the innermost `Local` from this `Place`, *if* it is either a local itself or
1804 /// a single deref of a local.
1806 // FIXME: can we safely swap the semantics of `fn base_local` below in here instead?
1807 pub fn local_or_deref_local(&self) -> Option<Local> {
1808 match self.as_ref() {
1810 base: &PlaceBase::Local(local),
1814 base: &PlaceBase::Local(local),
1815 projection: &[ProjectionElem::Deref],
1821 /// If this place represents a local variable like `_X` with no
1822 /// projections, return `Some(_X)`.
1823 pub fn as_local(&self) -> Option<Local> {
1824 self.as_ref().as_local()
1827 pub fn as_ref(&self) -> PlaceRef<'_, 'tcx> {
1830 projection: &self.projection,
1835 impl From<Local> for Place<'_> {
1836 fn from(local: Local) -> Self {
1839 projection: List::empty(),
1844 impl From<Local> for PlaceBase<'_> {
1845 fn from(local: Local) -> Self {
1846 PlaceBase::Local(local)
1850 impl<'a, 'tcx> PlaceRef<'a, 'tcx> {
1851 /// Finds the innermost `Local` from this `Place`, *if* it is either a local itself or
1852 /// a single deref of a local.
1854 // FIXME: can we safely swap the semantics of `fn base_local` below in here instead?
1855 pub fn local_or_deref_local(&self) -> Option<Local> {
1858 base: PlaceBase::Local(local),
1862 base: PlaceBase::Local(local),
1863 projection: [ProjectionElem::Deref],
1869 /// If this place represents a local variable like `_X` with no
1870 /// projections, return `Some(_X)`.
1871 pub fn as_local(&self) -> Option<Local> {
1873 PlaceRef { base: PlaceBase::Local(l), projection: [] } => Some(*l),
1879 impl Debug for Place<'_> {
1880 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1881 for elem in self.projection.iter().rev() {
1883 ProjectionElem::Downcast(_, _) | ProjectionElem::Field(_, _) => {
1884 write!(fmt, "(").unwrap();
1886 ProjectionElem::Deref => {
1887 write!(fmt, "(*").unwrap();
1889 ProjectionElem::Index(_)
1890 | ProjectionElem::ConstantIndex { .. }
1891 | ProjectionElem::Subslice { .. } => {}
1895 write!(fmt, "{:?}", self.base)?;
1897 for elem in self.projection.iter() {
1899 ProjectionElem::Downcast(Some(name), _index) => {
1900 write!(fmt, " as {})", name)?;
1902 ProjectionElem::Downcast(None, index) => {
1903 write!(fmt, " as variant#{:?})", index)?;
1905 ProjectionElem::Deref => {
1908 ProjectionElem::Field(field, ty) => {
1909 write!(fmt, ".{:?}: {:?})", field.index(), ty)?;
1911 ProjectionElem::Index(ref index) => {
1912 write!(fmt, "[{:?}]", index)?;
1914 ProjectionElem::ConstantIndex { offset, min_length, from_end: false } => {
1915 write!(fmt, "[{:?} of {:?}]", offset, min_length)?;
1917 ProjectionElem::ConstantIndex { offset, min_length, from_end: true } => {
1918 write!(fmt, "[-{:?} of {:?}]", offset, min_length)?;
1920 ProjectionElem::Subslice { from, to } if *to == 0 => {
1921 write!(fmt, "[{:?}:]", from)?;
1923 ProjectionElem::Subslice { from, to } if *from == 0 => {
1924 write!(fmt, "[:-{:?}]", to)?;
1926 ProjectionElem::Subslice { from, to } => {
1927 write!(fmt, "[{:?}:-{:?}]", from, to)?;
1936 impl Debug for PlaceBase<'_> {
1937 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1939 PlaceBase::Local(id) => write!(fmt, "{:?}", id),
1940 PlaceBase::Static(box self::Static { ty, kind: StaticKind::Static, def_id }) => {
1941 write!(fmt, "({}: {:?})", ty::tls::with(|tcx| tcx.def_path_str(def_id)), ty)
1943 PlaceBase::Static(box self::Static {
1944 ty, kind: StaticKind::Promoted(promoted, _), def_id: _
1946 write!(fmt, "({:?}: {:?})", promoted, ty)
1952 ///////////////////////////////////////////////////////////////////////////
1955 rustc_index::newtype_index! {
1956 pub struct SourceScope {
1958 DEBUG_FORMAT = "scope[{}]",
1959 const OUTERMOST_SOURCE_SCOPE = 0,
1963 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
1964 pub struct SourceScopeData {
1966 pub parent_scope: Option<SourceScope>,
1968 /// Crate-local information for this source scope, that can't (and
1969 /// needn't) be tracked across crates.
1970 pub local_data: ClearCrossCrate<SourceScopeLocalData>,
1973 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
1974 pub struct SourceScopeLocalData {
1975 /// An `HirId` with lint levels equivalent to this scope's lint levels.
1976 pub lint_root: hir::HirId,
1977 /// The unsafe block that contains this node.
1981 ///////////////////////////////////////////////////////////////////////////
1984 /// These are values that can appear inside an rvalue. They are intentionally
1985 /// limited to prevent rvalues from being nested in one another.
1986 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable)]
1987 pub enum Operand<'tcx> {
1988 /// Copy: The value must be available for use afterwards.
1990 /// This implies that the type of the place must be `Copy`; this is true
1991 /// by construction during build, but also checked by the MIR type checker.
1994 /// Move: The value (including old borrows of it) will not be used again.
1996 /// Safe for values of all types (modulo future developments towards `?Move`).
1997 /// Correct usage patterns are enforced by the borrow checker for safe code.
1998 /// `Copy` may be converted to `Move` to enable "last-use" optimizations.
2001 /// Synthesizes a constant value.
2002 Constant(Box<Constant<'tcx>>),
2005 impl<'tcx> Debug for Operand<'tcx> {
2006 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2007 use self::Operand::*;
2009 Constant(ref a) => write!(fmt, "{:?}", a),
2010 Copy(ref place) => write!(fmt, "{:?}", place),
2011 Move(ref place) => write!(fmt, "move {:?}", place),
2016 impl<'tcx> Operand<'tcx> {
2017 /// Convenience helper to make a constant that refers to the fn
2018 /// with given `DefId` and substs. Since this is used to synthesize
2019 /// MIR, assumes `user_ty` is None.
2020 pub fn function_handle(
2023 substs: SubstsRef<'tcx>,
2026 let ty = tcx.type_of(def_id).subst(tcx, substs);
2027 Operand::Constant(box Constant {
2030 literal: ty::Const::zero_sized(tcx, ty),
2034 pub fn to_copy(&self) -> Self {
2036 Operand::Copy(_) | Operand::Constant(_) => self.clone(),
2037 Operand::Move(ref place) => Operand::Copy(place.clone()),
2042 ///////////////////////////////////////////////////////////////////////////
2045 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable, PartialEq)]
2046 pub enum Rvalue<'tcx> {
2047 /// x (either a move or copy, depending on type of x)
2051 Repeat(Operand<'tcx>, u64),
2054 Ref(Region<'tcx>, BorrowKind, Place<'tcx>),
2056 /// length of a [X] or [X;n] value
2059 Cast(CastKind, Operand<'tcx>, Ty<'tcx>),
2061 BinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
2062 CheckedBinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
2064 NullaryOp(NullOp, Ty<'tcx>),
2065 UnaryOp(UnOp, Operand<'tcx>),
2067 /// Read the discriminant of an ADT.
2069 /// Undefined (i.e., no effort is made to make it defined, but there’s no reason why it cannot
2070 /// be defined to return, say, a 0) if ADT is not an enum.
2071 Discriminant(Place<'tcx>),
2073 /// Creates an aggregate value, like a tuple or struct. This is
2074 /// only needed because we want to distinguish `dest = Foo { x:
2075 /// ..., y: ... }` from `dest.x = ...; dest.y = ...;` in the case
2076 /// that `Foo` has a destructor. These rvalues can be optimized
2077 /// away after type-checking and before lowering.
2078 Aggregate(Box<AggregateKind<'tcx>>, Vec<Operand<'tcx>>),
2081 #[derive(Clone, Copy, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2084 Pointer(PointerCast),
2087 #[derive(Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2088 pub enum AggregateKind<'tcx> {
2089 /// The type is of the element
2093 /// The second field is the variant index. It's equal to 0 for struct
2094 /// and union expressions. The fourth field is
2095 /// active field number and is present only for union expressions
2096 /// -- e.g., for a union expression `SomeUnion { c: .. }`, the
2097 /// active field index would identity the field `c`
2098 Adt(&'tcx AdtDef, VariantIdx, SubstsRef<'tcx>, Option<UserTypeAnnotationIndex>, Option<usize>),
2100 Closure(DefId, SubstsRef<'tcx>),
2101 Generator(DefId, SubstsRef<'tcx>, hir::Movability),
2104 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2106 /// The `+` operator (addition)
2108 /// The `-` operator (subtraction)
2110 /// The `*` operator (multiplication)
2112 /// The `/` operator (division)
2114 /// The `%` operator (modulus)
2116 /// The `^` operator (bitwise xor)
2118 /// The `&` operator (bitwise and)
2120 /// The `|` operator (bitwise or)
2122 /// The `<<` operator (shift left)
2124 /// The `>>` operator (shift right)
2126 /// The `==` operator (equality)
2128 /// The `<` operator (less than)
2130 /// The `<=` operator (less than or equal to)
2132 /// The `!=` operator (not equal to)
2134 /// The `>=` operator (greater than or equal to)
2136 /// The `>` operator (greater than)
2138 /// The `ptr.offset` operator
2143 pub fn is_checkable(self) -> bool {
2146 Add | Sub | Mul | Shl | Shr => true,
2152 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2154 /// Returns the size of a value of that type
2156 /// Creates a new uninitialized box for a value of that type
2160 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2162 /// The `!` operator for logical inversion
2164 /// The `-` operator for negation
2168 impl<'tcx> Debug for Rvalue<'tcx> {
2169 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2170 use self::Rvalue::*;
2173 Use(ref place) => write!(fmt, "{:?}", place),
2174 Repeat(ref a, ref b) => write!(fmt, "[{:?}; {:?}]", a, b),
2175 Len(ref a) => write!(fmt, "Len({:?})", a),
2176 Cast(ref kind, ref place, ref ty) => {
2177 write!(fmt, "{:?} as {:?} ({:?})", place, ty, kind)
2179 BinaryOp(ref op, ref a, ref b) => write!(fmt, "{:?}({:?}, {:?})", op, a, b),
2180 CheckedBinaryOp(ref op, ref a, ref b) => {
2181 write!(fmt, "Checked{:?}({:?}, {:?})", op, a, b)
2183 UnaryOp(ref op, ref a) => write!(fmt, "{:?}({:?})", op, a),
2184 Discriminant(ref place) => write!(fmt, "discriminant({:?})", place),
2185 NullaryOp(ref op, ref t) => write!(fmt, "{:?}({:?})", op, t),
2186 Ref(region, borrow_kind, ref place) => {
2187 let kind_str = match borrow_kind {
2188 BorrowKind::Shared => "",
2189 BorrowKind::Shallow => "shallow ",
2190 BorrowKind::Mut { .. } | BorrowKind::Unique => "mut ",
2193 // When printing regions, add trailing space if necessary.
2194 let print_region = ty::tls::with(|tcx| {
2195 tcx.sess.verbose() || tcx.sess.opts.debugging_opts.identify_regions
2197 let region = if print_region {
2198 let mut region = region.to_string();
2199 if region.len() > 0 {
2204 // Do not even print 'static
2207 write!(fmt, "&{}{}{:?}", region, kind_str, place)
2210 Aggregate(ref kind, ref places) => {
2211 fn fmt_tuple(fmt: &mut Formatter<'_>, places: &[Operand<'_>]) -> fmt::Result {
2212 let mut tuple_fmt = fmt.debug_tuple("");
2213 for place in places {
2214 tuple_fmt.field(place);
2220 AggregateKind::Array(_) => write!(fmt, "{:?}", places),
2222 AggregateKind::Tuple => match places.len() {
2223 0 => write!(fmt, "()"),
2224 1 => write!(fmt, "({:?},)", places[0]),
2225 _ => fmt_tuple(fmt, places),
2228 AggregateKind::Adt(adt_def, variant, substs, _user_ty, _) => {
2229 let variant_def = &adt_def.variants[variant];
2232 ty::tls::with(|tcx| {
2233 let substs = tcx.lift(&substs).expect("could not lift for printing");
2234 FmtPrinter::new(tcx, f, Namespace::ValueNS)
2235 .print_def_path(variant_def.def_id, substs)?;
2239 match variant_def.ctor_kind {
2240 CtorKind::Const => Ok(()),
2241 CtorKind::Fn => fmt_tuple(fmt, places),
2242 CtorKind::Fictive => {
2243 let mut struct_fmt = fmt.debug_struct("");
2244 for (field, place) in variant_def.fields.iter().zip(places) {
2245 struct_fmt.field(&field.ident.as_str(), place);
2252 AggregateKind::Closure(def_id, substs) => ty::tls::with(|tcx| {
2253 if let Some(hir_id) = tcx.hir().as_local_hir_id(def_id) {
2254 let name = if tcx.sess.opts.debugging_opts.span_free_formats {
2255 let substs = tcx.lift(&substs).unwrap();
2258 tcx.def_path_str_with_substs(def_id, substs),
2261 format!("[closure@{:?}]", tcx.hir().span(hir_id))
2263 let mut struct_fmt = fmt.debug_struct(&name);
2265 if let Some(upvars) = tcx.upvars(def_id) {
2266 for (&var_id, place) in upvars.keys().zip(places) {
2267 let var_name = tcx.hir().name(var_id);
2268 struct_fmt.field(&var_name.as_str(), place);
2274 write!(fmt, "[closure]")
2278 AggregateKind::Generator(def_id, _, _) => ty::tls::with(|tcx| {
2279 if let Some(hir_id) = tcx.hir().as_local_hir_id(def_id) {
2280 let name = format!("[generator@{:?}]", tcx.hir().span(hir_id));
2281 let mut struct_fmt = fmt.debug_struct(&name);
2283 if let Some(upvars) = tcx.upvars(def_id) {
2284 for (&var_id, place) in upvars.keys().zip(places) {
2285 let var_name = tcx.hir().name(var_id);
2286 struct_fmt.field(&var_name.as_str(), place);
2292 write!(fmt, "[generator]")
2301 ///////////////////////////////////////////////////////////////////////////
2304 /// Two constants are equal if they are the same constant. Note that
2305 /// this does not necessarily mean that they are "==" in Rust -- in
2306 /// particular one must be wary of `NaN`!
2308 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable)]
2309 pub struct Constant<'tcx> {
2312 /// Optional user-given type: for something like
2313 /// `collect::<Vec<_>>`, this would be present and would
2314 /// indicate that `Vec<_>` was explicitly specified.
2316 /// Needed for NLL to impose user-given type constraints.
2317 pub user_ty: Option<UserTypeAnnotationIndex>,
2319 pub literal: &'tcx ty::Const<'tcx>,
2322 impl Constant<'tcx> {
2323 pub fn check_static_ptr(&self, tcx: TyCtxt<'_>) -> Option<DefId> {
2324 match self.literal.val.try_to_scalar() {
2325 Some(Scalar::Ptr(ptr)) => match tcx.alloc_map.lock().get(ptr.alloc_id) {
2326 Some(GlobalAlloc::Static(def_id)) => Some(def_id),
2329 tcx.sess.delay_span_bug(
2330 DUMMY_SP, "MIR cannot contain dangling const pointers",
2340 /// A collection of projections into user types.
2342 /// They are projections because a binding can occur a part of a
2343 /// parent pattern that has been ascribed a type.
2345 /// Its a collection because there can be multiple type ascriptions on
2346 /// the path from the root of the pattern down to the binding itself.
2351 /// struct S<'a>((i32, &'a str), String);
2352 /// let S((_, w): (i32, &'static str), _): S = ...;
2353 /// // ------ ^^^^^^^^^^^^^^^^^^^ (1)
2354 /// // --------------------------------- ^ (2)
2357 /// The highlights labelled `(1)` show the subpattern `(_, w)` being
2358 /// ascribed the type `(i32, &'static str)`.
2360 /// The highlights labelled `(2)` show the whole pattern being
2361 /// ascribed the type `S`.
2363 /// In this example, when we descend to `w`, we will have built up the
2364 /// following two projected types:
2366 /// * base: `S`, projection: `(base.0).1`
2367 /// * base: `(i32, &'static str)`, projection: `base.1`
2369 /// The first will lead to the constraint `w: &'1 str` (for some
2370 /// inferred region `'1`). The second will lead to the constraint `w:
2372 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
2373 pub struct UserTypeProjections {
2374 pub(crate) contents: Vec<(UserTypeProjection, Span)>,
2377 impl<'tcx> UserTypeProjections {
2378 pub fn none() -> Self {
2379 UserTypeProjections { contents: vec![] }
2382 pub fn from_projections(projs: impl Iterator<Item = (UserTypeProjection, Span)>) -> Self {
2383 UserTypeProjections { contents: projs.collect() }
2386 pub fn projections_and_spans(&self) -> impl Iterator<Item = &(UserTypeProjection, Span)> {
2387 self.contents.iter()
2390 pub fn projections(&self) -> impl Iterator<Item = &UserTypeProjection> {
2391 self.contents.iter().map(|&(ref user_type, _span)| user_type)
2394 pub fn push_projection(mut self, user_ty: &UserTypeProjection, span: Span) -> Self {
2395 self.contents.push((user_ty.clone(), span));
2401 mut f: impl FnMut(UserTypeProjection) -> UserTypeProjection,
2403 self.contents = self.contents.drain(..).map(|(proj, span)| (f(proj), span)).collect();
2407 pub fn index(self) -> Self {
2408 self.map_projections(|pat_ty_proj| pat_ty_proj.index())
2411 pub fn subslice(self, from: u32, to: u32) -> Self {
2412 self.map_projections(|pat_ty_proj| pat_ty_proj.subslice(from, to))
2415 pub fn deref(self) -> Self {
2416 self.map_projections(|pat_ty_proj| pat_ty_proj.deref())
2419 pub fn leaf(self, field: Field) -> Self {
2420 self.map_projections(|pat_ty_proj| pat_ty_proj.leaf(field))
2423 pub fn variant(self, adt_def: &'tcx AdtDef, variant_index: VariantIdx, field: Field) -> Self {
2424 self.map_projections(|pat_ty_proj| pat_ty_proj.variant(adt_def, variant_index, field))
2428 /// Encodes the effect of a user-supplied type annotation on the
2429 /// subcomponents of a pattern. The effect is determined by applying the
2430 /// given list of proejctions to some underlying base type. Often,
2431 /// the projection element list `projs` is empty, in which case this
2432 /// directly encodes a type in `base`. But in the case of complex patterns with
2433 /// subpatterns and bindings, we want to apply only a *part* of the type to a variable,
2434 /// in which case the `projs` vector is used.
2438 /// * `let x: T = ...` -- here, the `projs` vector is empty.
2440 /// * `let (x, _): T = ...` -- here, the `projs` vector would contain
2441 /// `field[0]` (aka `.0`), indicating that the type of `s` is
2442 /// determined by finding the type of the `.0` field from `T`.
2443 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable, PartialEq)]
2444 pub struct UserTypeProjection {
2445 pub base: UserTypeAnnotationIndex,
2446 pub projs: Vec<ProjectionKind>,
2449 impl Copy for ProjectionKind {}
2451 impl UserTypeProjection {
2452 pub(crate) fn index(mut self) -> Self {
2453 self.projs.push(ProjectionElem::Index(()));
2457 pub(crate) fn subslice(mut self, from: u32, to: u32) -> Self {
2458 self.projs.push(ProjectionElem::Subslice { from, to });
2462 pub(crate) fn deref(mut self) -> Self {
2463 self.projs.push(ProjectionElem::Deref);
2467 pub(crate) fn leaf(mut self, field: Field) -> Self {
2468 self.projs.push(ProjectionElem::Field(field, ()));
2472 pub(crate) fn variant(
2474 adt_def: &'tcx AdtDef,
2475 variant_index: VariantIdx,
2478 self.projs.push(ProjectionElem::Downcast(
2479 Some(adt_def.variants[variant_index].ident.name),
2482 self.projs.push(ProjectionElem::Field(field, ()));
2487 CloneTypeFoldableAndLiftImpls! { ProjectionKind, }
2489 impl<'tcx> TypeFoldable<'tcx> for UserTypeProjection {
2490 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
2491 use crate::mir::ProjectionElem::*;
2493 let base = self.base.fold_with(folder);
2494 let projs: Vec<_> = self
2497 .map(|elem| match elem {
2499 Field(f, ()) => Field(f.clone(), ()),
2500 Index(()) => Index(()),
2501 elem => elem.clone(),
2505 UserTypeProjection { base, projs }
2508 fn super_visit_with<Vs: TypeVisitor<'tcx>>(&self, visitor: &mut Vs) -> bool {
2509 self.base.visit_with(visitor)
2510 // Note: there's nothing in `self.proj` to visit.
2514 rustc_index::newtype_index! {
2515 pub struct Promoted {
2517 DEBUG_FORMAT = "promoted[{}]"
2521 impl<'tcx> Debug for Constant<'tcx> {
2522 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2523 write!(fmt, "{}", self)
2527 impl<'tcx> Display for Constant<'tcx> {
2528 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2529 write!(fmt, "const ")?;
2530 // FIXME make the default pretty printing of raw pointers more detailed. Here we output the
2531 // debug representation of raw pointers, so that the raw pointers in the mir dump output are
2532 // detailed and just not '{pointer}'.
2533 if let ty::RawPtr(_) = self.literal.ty.kind {
2534 write!(fmt, "{:?} : {}", self.literal.val, self.literal.ty)
2536 write!(fmt, "{}", self.literal)
2541 impl<'tcx> graph::DirectedGraph for Body<'tcx> {
2542 type Node = BasicBlock;
2545 impl<'tcx> graph::WithNumNodes for Body<'tcx> {
2546 fn num_nodes(&self) -> usize {
2547 self.basic_blocks.len()
2551 impl<'tcx> graph::WithStartNode for Body<'tcx> {
2552 fn start_node(&self) -> Self::Node {
2557 impl<'tcx> graph::WithSuccessors for Body<'tcx> {
2561 ) -> <Self as GraphSuccessors<'_>>::Iter {
2562 self.basic_blocks[node].terminator().successors().cloned()
2566 impl<'a, 'b> graph::GraphSuccessors<'b> for Body<'a> {
2567 type Item = BasicBlock;
2568 type Iter = iter::Cloned<Successors<'b>>;
2571 #[derive(Copy, Clone, PartialEq, Eq, Hash, Ord, PartialOrd, HashStable)]
2572 pub struct Location {
2573 /// The block that the location is within.
2574 pub block: BasicBlock,
2576 /// The location is the position of the start of the statement; or, if
2577 /// `statement_index` equals the number of statements, then the start of the
2579 pub statement_index: usize,
2582 impl fmt::Debug for Location {
2583 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2584 write!(fmt, "{:?}[{}]", self.block, self.statement_index)
2589 pub const START: Location = Location { block: START_BLOCK, statement_index: 0 };
2591 /// Returns the location immediately after this one within the enclosing block.
2593 /// Note that if this location represents a terminator, then the
2594 /// resulting location would be out of bounds and invalid.
2595 pub fn successor_within_block(&self) -> Location {
2596 Location { block: self.block, statement_index: self.statement_index + 1 }
2599 /// Returns `true` if `other` is earlier in the control flow graph than `self`.
2600 pub fn is_predecessor_of<'tcx>(
2603 mut body_cache: BodyCache<&'_ Body<'tcx>>
2605 // If we are in the same block as the other location and are an earlier statement
2606 // then we are a predecessor of `other`.
2607 if self.block == other.block && self.statement_index < other.statement_index {
2611 // If we're in another block, then we want to check that block is a predecessor of `other`.
2612 let mut queue: Vec<BasicBlock> = body_cache.predecessors_for(other.block).to_vec();
2613 let mut visited = FxHashSet::default();
2615 while let Some(block) = queue.pop() {
2616 // If we haven't visited this block before, then make sure we visit it's predecessors.
2617 if visited.insert(block) {
2618 queue.extend(body_cache.predecessors_for(block).iter().cloned());
2623 // If we found the block that `self` is in, then we are a predecessor of `other` (since
2624 // we found that block by looking at the predecessors of `other`).
2625 if self.block == block {
2633 pub fn dominates(&self, other: Location, dominators: &Dominators<BasicBlock>) -> bool {
2634 if self.block == other.block {
2635 self.statement_index <= other.statement_index
2637 dominators.is_dominated_by(other.block, self.block)
2642 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable)]
2643 pub enum UnsafetyViolationKind {
2645 /// Permitted both in `const fn`s and regular `fn`s.
2647 BorrowPacked(hir::HirId),
2650 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable)]
2651 pub struct UnsafetyViolation {
2652 pub source_info: SourceInfo,
2653 pub description: Symbol,
2654 pub details: Symbol,
2655 pub kind: UnsafetyViolationKind,
2658 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable)]
2659 pub struct UnsafetyCheckResult {
2660 /// Violations that are propagated *upwards* from this function.
2661 pub violations: Lrc<[UnsafetyViolation]>,
2662 /// `unsafe` blocks in this function, along with whether they are used. This is
2663 /// used for the "unused_unsafe" lint.
2664 pub unsafe_blocks: Lrc<[(hir::HirId, bool)]>,
2667 rustc_index::newtype_index! {
2668 pub struct GeneratorSavedLocal {
2670 DEBUG_FORMAT = "_{}",
2674 /// The layout of generator state.
2675 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
2676 pub struct GeneratorLayout<'tcx> {
2677 /// The type of every local stored inside the generator.
2678 pub field_tys: IndexVec<GeneratorSavedLocal, Ty<'tcx>>,
2680 /// Which of the above fields are in each variant. Note that one field may
2681 /// be stored in multiple variants.
2682 pub variant_fields: IndexVec<VariantIdx, IndexVec<Field, GeneratorSavedLocal>>,
2684 /// Which saved locals are storage-live at the same time. Locals that do not
2685 /// have conflicts with each other are allowed to overlap in the computed
2687 pub storage_conflicts: BitMatrix<GeneratorSavedLocal, GeneratorSavedLocal>,
2690 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
2691 pub struct BorrowCheckResult<'tcx> {
2692 pub closure_requirements: Option<ClosureRegionRequirements<'tcx>>,
2693 pub used_mut_upvars: SmallVec<[Field; 8]>,
2696 /// The result of the `mir_const_qualif` query.
2698 /// Each field corresponds to an implementer of the `Qualif` trait in
2699 /// `librustc_mir/transform/check_consts/qualifs.rs`. See that file for more information on each
2701 #[derive(Clone, Copy, Debug, Default, RustcEncodable, RustcDecodable, HashStable)]
2702 pub struct ConstQualifs {
2703 pub has_mut_interior: bool,
2704 pub needs_drop: bool,
2707 /// After we borrow check a closure, we are left with various
2708 /// requirements that we have inferred between the free regions that
2709 /// appear in the closure's signature or on its field types. These
2710 /// requirements are then verified and proved by the closure's
2711 /// creating function. This struct encodes those requirements.
2713 /// The requirements are listed as being between various
2714 /// `RegionVid`. The 0th region refers to `'static`; subsequent region
2715 /// vids refer to the free regions that appear in the closure (or
2716 /// generator's) type, in order of appearance. (This numbering is
2717 /// actually defined by the `UniversalRegions` struct in the NLL
2718 /// region checker. See for example
2719 /// `UniversalRegions::closure_mapping`.) Note that we treat the free
2720 /// regions in the closure's type "as if" they were erased, so their
2721 /// precise identity is not important, only their position.
2723 /// Example: If type check produces a closure with the closure substs:
2726 /// ClosureSubsts = [
2727 /// i8, // the "closure kind"
2728 /// for<'x> fn(&'a &'x u32) -> &'x u32, // the "closure signature"
2729 /// &'a String, // some upvar
2733 /// here, there is one unique free region (`'a`) but it appears
2734 /// twice. We would "renumber" each occurrence to a unique vid, as follows:
2737 /// ClosureSubsts = [
2738 /// i8, // the "closure kind"
2739 /// for<'x> fn(&'1 &'x u32) -> &'x u32, // the "closure signature"
2740 /// &'2 String, // some upvar
2744 /// Now the code might impose a requirement like `'1: '2`. When an
2745 /// instance of the closure is created, the corresponding free regions
2746 /// can be extracted from its type and constrained to have the given
2747 /// outlives relationship.
2749 /// In some cases, we have to record outlives requirements between
2750 /// types and regions as well. In that case, if those types include
2751 /// any regions, those regions are recorded as `ReClosureBound`
2752 /// instances assigned one of these same indices. Those regions will
2753 /// be substituted away by the creator. We use `ReClosureBound` in
2754 /// that case because the regions must be allocated in the global
2755 /// `TyCtxt`, and hence we cannot use `ReVar` (which is what we use
2756 /// internally within the rest of the NLL code).
2757 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
2758 pub struct ClosureRegionRequirements<'tcx> {
2759 /// The number of external regions defined on the closure. In our
2760 /// example above, it would be 3 -- one for `'static`, then `'1`
2761 /// and `'2`. This is just used for a sanity check later on, to
2762 /// make sure that the number of regions we see at the callsite
2764 pub num_external_vids: usize,
2766 /// Requirements between the various free regions defined in
2768 pub outlives_requirements: Vec<ClosureOutlivesRequirement<'tcx>>,
2771 /// Indicates an outlives-constraint between a type or between two
2772 /// free regions declared on the closure.
2773 #[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
2774 pub struct ClosureOutlivesRequirement<'tcx> {
2775 // This region or type ...
2776 pub subject: ClosureOutlivesSubject<'tcx>,
2778 // ... must outlive this one.
2779 pub outlived_free_region: ty::RegionVid,
2781 // If not, report an error here ...
2782 pub blame_span: Span,
2784 // ... due to this reason.
2785 pub category: ConstraintCategory,
2788 /// Outlives-constraints can be categorized to determine whether and why they
2789 /// are interesting (for error reporting). Order of variants indicates sort
2790 /// order of the category, thereby influencing diagnostic output.
2792 /// See also [rustc_mir::borrow_check::nll::constraints].
2806 pub enum ConstraintCategory {
2814 /// A constraint that came from checking the body of a closure.
2816 /// We try to get the category that the closure used when reporting this.
2824 /// A "boring" constraint (caused by the given location) is one that
2825 /// the user probably doesn't want to see described in diagnostics,
2826 /// because it is kind of an artifact of the type system setup.
2827 /// Example: `x = Foo { field: y }` technically creates
2828 /// intermediate regions representing the "type of `Foo { field: y
2829 /// }`", and data flows from `y` into those variables, but they
2830 /// are not very interesting. The assignment into `x` on the other
2833 // Boring and applicable everywhere.
2836 /// A constraint that doesn't correspond to anything the user sees.
2840 /// The subject of a `ClosureOutlivesRequirement` -- that is, the thing
2841 /// that must outlive some region.
2842 #[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
2843 pub enum ClosureOutlivesSubject<'tcx> {
2844 /// Subject is a type, typically a type parameter, but could also
2845 /// be a projection. Indicates a requirement like `T: 'a` being
2846 /// passed to the caller, where the type here is `T`.
2848 /// The type here is guaranteed not to contain any free regions at
2852 /// Subject is a free region from the closure. Indicates a requirement
2853 /// like `'a: 'b` being passed to the caller; the region here is `'a`.
2854 Region(ty::RegionVid),
2858 * `TypeFoldable` implementations for MIR types
2861 CloneTypeFoldableAndLiftImpls! {
2870 SourceScopeLocalData,
2871 UserTypeAnnotationIndex,
2874 impl<'tcx> TypeFoldable<'tcx> for Terminator<'tcx> {
2875 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
2876 use crate::mir::TerminatorKind::*;
2878 let kind = match self.kind {
2879 Goto { target } => Goto { target },
2880 SwitchInt { ref discr, switch_ty, ref values, ref targets } => SwitchInt {
2881 discr: discr.fold_with(folder),
2882 switch_ty: switch_ty.fold_with(folder),
2883 values: values.clone(),
2884 targets: targets.clone(),
2886 Drop { ref location, target, unwind } => {
2887 Drop { location: location.fold_with(folder), target, unwind }
2889 DropAndReplace { ref location, ref value, target, unwind } => DropAndReplace {
2890 location: location.fold_with(folder),
2891 value: value.fold_with(folder),
2895 Yield { ref value, resume, drop } => {
2896 Yield { value: value.fold_with(folder), resume: resume, drop: drop }
2898 Call { ref func, ref args, ref destination, cleanup, from_hir_call } => {
2900 destination.as_ref().map(|&(ref loc, dest)| (loc.fold_with(folder), dest));
2903 func: func.fold_with(folder),
2904 args: args.fold_with(folder),
2910 Assert { ref cond, expected, ref msg, target, cleanup } => {
2912 let msg = match msg {
2913 BoundsCheck { ref len, ref index } =>
2915 len: len.fold_with(folder),
2916 index: index.fold_with(folder),
2918 Panic { .. } | Overflow(_) | OverflowNeg | DivisionByZero | RemainderByZero |
2919 ResumedAfterReturn(_) | ResumedAfterPanic(_) =>
2922 Assert { cond: cond.fold_with(folder), expected, msg, target, cleanup }
2924 GeneratorDrop => GeneratorDrop,
2928 Unreachable => Unreachable,
2929 FalseEdges { real_target, imaginary_target } => {
2930 FalseEdges { real_target, imaginary_target }
2932 FalseUnwind { real_target, unwind } => FalseUnwind { real_target, unwind },
2934 Terminator { source_info: self.source_info, kind }
2937 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
2938 use crate::mir::TerminatorKind::*;
2941 SwitchInt { ref discr, switch_ty, .. } => {
2942 discr.visit_with(visitor) || switch_ty.visit_with(visitor)
2944 Drop { ref location, .. } => location.visit_with(visitor),
2945 DropAndReplace { ref location, ref value, .. } => {
2946 location.visit_with(visitor) || value.visit_with(visitor)
2948 Yield { ref value, .. } => value.visit_with(visitor),
2949 Call { ref func, ref args, ref destination, .. } => {
2950 let dest = if let Some((ref loc, _)) = *destination {
2951 loc.visit_with(visitor)
2955 dest || func.visit_with(visitor) || args.visit_with(visitor)
2957 Assert { ref cond, ref msg, .. } => {
2958 if cond.visit_with(visitor) {
2961 BoundsCheck { ref len, ref index } =>
2962 len.visit_with(visitor) || index.visit_with(visitor),
2963 Panic { .. } | Overflow(_) | OverflowNeg |
2964 DivisionByZero | RemainderByZero |
2965 ResumedAfterReturn(_) | ResumedAfterPanic(_) =>
2979 | FalseUnwind { .. } => false,
2984 impl<'tcx> TypeFoldable<'tcx> for GeneratorKind {
2985 fn super_fold_with<F: TypeFolder<'tcx>>(&self, _: &mut F) -> Self {
2989 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, _: &mut V) -> bool {
2994 impl<'tcx> TypeFoldable<'tcx> for Place<'tcx> {
2995 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
2997 base: self.base.fold_with(folder),
2998 projection: self.projection.fold_with(folder),
3002 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3003 self.base.visit_with(visitor) || self.projection.visit_with(visitor)
3007 impl<'tcx> TypeFoldable<'tcx> for PlaceBase<'tcx> {
3008 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
3010 PlaceBase::Local(local) => PlaceBase::Local(local.fold_with(folder)),
3011 PlaceBase::Static(static_) => PlaceBase::Static(static_.fold_with(folder)),
3015 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3017 PlaceBase::Local(local) => local.visit_with(visitor),
3018 PlaceBase::Static(static_) => (**static_).visit_with(visitor),
3023 impl<'tcx> TypeFoldable<'tcx> for &'tcx ty::List<PlaceElem<'tcx>> {
3024 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
3025 let v = self.iter().map(|t| t.fold_with(folder)).collect::<Vec<_>>();
3026 folder.tcx().intern_place_elems(&v)
3029 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3030 self.iter().any(|t| t.visit_with(visitor))
3034 impl<'tcx> TypeFoldable<'tcx> for Static<'tcx> {
3035 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
3037 ty: self.ty.fold_with(folder),
3038 kind: self.kind.fold_with(folder),
3039 def_id: self.def_id,
3043 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3044 let Static { ty, kind, def_id: _ } = self;
3046 ty.visit_with(visitor) || kind.visit_with(visitor)
3050 impl<'tcx> TypeFoldable<'tcx> for StaticKind<'tcx> {
3051 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
3053 StaticKind::Promoted(promoted, substs) =>
3054 StaticKind::Promoted(promoted.fold_with(folder), substs.fold_with(folder)),
3055 StaticKind::Static => StaticKind::Static
3059 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3061 StaticKind::Promoted(promoted, substs) =>
3062 promoted.visit_with(visitor) || substs.visit_with(visitor),
3063 StaticKind::Static => { false }
3068 impl<'tcx> TypeFoldable<'tcx> for Rvalue<'tcx> {
3069 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
3070 use crate::mir::Rvalue::*;
3072 Use(ref op) => Use(op.fold_with(folder)),
3073 Repeat(ref op, len) => Repeat(op.fold_with(folder), len),
3074 Ref(region, bk, ref place) => {
3075 Ref(region.fold_with(folder), bk, place.fold_with(folder))
3077 Len(ref place) => Len(place.fold_with(folder)),
3078 Cast(kind, ref op, ty) => Cast(kind, op.fold_with(folder), ty.fold_with(folder)),
3079 BinaryOp(op, ref rhs, ref lhs) => {
3080 BinaryOp(op, rhs.fold_with(folder), lhs.fold_with(folder))
3082 CheckedBinaryOp(op, ref rhs, ref lhs) => {
3083 CheckedBinaryOp(op, rhs.fold_with(folder), lhs.fold_with(folder))
3085 UnaryOp(op, ref val) => UnaryOp(op, val.fold_with(folder)),
3086 Discriminant(ref place) => Discriminant(place.fold_with(folder)),
3087 NullaryOp(op, ty) => NullaryOp(op, ty.fold_with(folder)),
3088 Aggregate(ref kind, ref fields) => {
3089 let kind = box match **kind {
3090 AggregateKind::Array(ty) => AggregateKind::Array(ty.fold_with(folder)),
3091 AggregateKind::Tuple => AggregateKind::Tuple,
3092 AggregateKind::Adt(def, v, substs, user_ty, n) => AggregateKind::Adt(
3095 substs.fold_with(folder),
3096 user_ty.fold_with(folder),
3099 AggregateKind::Closure(id, substs) => {
3100 AggregateKind::Closure(id, substs.fold_with(folder))
3102 AggregateKind::Generator(id, substs, movablity) => {
3103 AggregateKind::Generator(id, substs.fold_with(folder), movablity)
3106 Aggregate(kind, fields.fold_with(folder))
3111 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3112 use crate::mir::Rvalue::*;
3114 Use(ref op) => op.visit_with(visitor),
3115 Repeat(ref op, _) => op.visit_with(visitor),
3116 Ref(region, _, ref place) => region.visit_with(visitor) || place.visit_with(visitor),
3117 Len(ref place) => place.visit_with(visitor),
3118 Cast(_, ref op, ty) => op.visit_with(visitor) || ty.visit_with(visitor),
3119 BinaryOp(_, ref rhs, ref lhs) | CheckedBinaryOp(_, ref rhs, ref lhs) => {
3120 rhs.visit_with(visitor) || lhs.visit_with(visitor)
3122 UnaryOp(_, ref val) => val.visit_with(visitor),
3123 Discriminant(ref place) => place.visit_with(visitor),
3124 NullaryOp(_, ty) => ty.visit_with(visitor),
3125 Aggregate(ref kind, ref fields) => {
3127 AggregateKind::Array(ty) => ty.visit_with(visitor),
3128 AggregateKind::Tuple => false,
3129 AggregateKind::Adt(_, _, substs, user_ty, _) => {
3130 substs.visit_with(visitor) || user_ty.visit_with(visitor)
3132 AggregateKind::Closure(_, substs) => substs.visit_with(visitor),
3133 AggregateKind::Generator(_, substs, _) => substs.visit_with(visitor),
3134 }) || fields.visit_with(visitor)
3140 impl<'tcx> TypeFoldable<'tcx> for Operand<'tcx> {
3141 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
3143 Operand::Copy(ref place) => Operand::Copy(place.fold_with(folder)),
3144 Operand::Move(ref place) => Operand::Move(place.fold_with(folder)),
3145 Operand::Constant(ref c) => Operand::Constant(c.fold_with(folder)),
3149 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3151 Operand::Copy(ref place) | Operand::Move(ref place) => place.visit_with(visitor),
3152 Operand::Constant(ref c) => c.visit_with(visitor),
3157 impl<'tcx> TypeFoldable<'tcx> for PlaceElem<'tcx> {
3158 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
3159 use crate::mir::ProjectionElem::*;
3163 Field(f, ty) => Field(*f, ty.fold_with(folder)),
3164 Index(v) => Index(v.fold_with(folder)),
3165 elem => elem.clone(),
3169 fn super_visit_with<Vs: TypeVisitor<'tcx>>(&self, visitor: &mut Vs) -> bool {
3170 use crate::mir::ProjectionElem::*;
3173 Field(_, ty) => ty.visit_with(visitor),
3174 Index(v) => v.visit_with(visitor),
3180 impl<'tcx> TypeFoldable<'tcx> for Field {
3181 fn super_fold_with<F: TypeFolder<'tcx>>(&self, _: &mut F) -> Self {
3184 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, _: &mut V) -> bool {
3189 impl<'tcx> TypeFoldable<'tcx> for GeneratorSavedLocal {
3190 fn super_fold_with<F: TypeFolder<'tcx>>(&self, _: &mut F) -> Self {
3193 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, _: &mut V) -> bool {
3198 impl<'tcx, R: Idx, C: Idx> TypeFoldable<'tcx> for BitMatrix<R, C> {
3199 fn super_fold_with<F: TypeFolder<'tcx>>(&self, _: &mut F) -> Self {
3202 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, _: &mut V) -> bool {
3207 impl<'tcx> TypeFoldable<'tcx> for Constant<'tcx> {
3208 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
3210 span: self.span.clone(),
3211 user_ty: self.user_ty.fold_with(folder),
3212 literal: self.literal.fold_with(folder),
3215 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3216 self.literal.visit_with(visitor)