1 //! MIR datatypes and passes. See the [rustc guide] for more info.
3 //! [rustc guide]: https://rust-lang.github.io/rustc-guide/mir/index.html
5 use crate::mir::interpret::{GlobalAlloc, PanicInfo, Scalar};
6 use crate::mir::visit::MirVisitable;
7 use crate::ty::adjustment::PointerCast;
8 use crate::ty::fold::{TypeFoldable, TypeFolder, TypeVisitor};
9 use crate::ty::layout::VariantIdx;
10 use crate::ty::print::{FmtPrinter, Printer};
11 use crate::ty::subst::{Subst, SubstsRef};
13 self, AdtDef, CanonicalUserTypeAnnotations, List, Region, Ty, TyCtxt, UserTypeAnnotationIndex,
16 use rustc_hir::def::{CtorKind, Namespace};
17 use rustc_hir::def_id::DefId;
18 use rustc_hir::{self, GeneratorKind};
20 use polonius_engine::Atom;
21 use rustc_data_structures::fx::FxHashSet;
22 use rustc_data_structures::graph::dominators::Dominators;
23 use rustc_data_structures::graph::{self, GraphSuccessors};
24 use rustc_index::bit_set::BitMatrix;
25 use rustc_index::vec::{Idx, IndexVec};
26 use rustc_macros::HashStable;
27 use rustc_serialize::{Decodable, Encodable};
28 use rustc_span::symbol::Symbol;
29 use rustc_span::{Span, DUMMY_SP};
31 use std::fmt::{self, Debug, Display, Formatter, Write};
34 use std::{iter, mem, option, u32};
35 pub use syntax::ast::Mutability;
36 use syntax::ast::Name;
38 pub use self::cache::{BodyAndCache, ReadOnlyBodyAndCache};
39 pub use self::interpret::AssertMessage;
40 pub use self::query::*;
41 pub use crate::read_only;
52 type LocalDecls<'tcx> = IndexVec<Local, LocalDecl<'tcx>>;
54 pub trait HasLocalDecls<'tcx> {
55 fn local_decls(&self) -> &LocalDecls<'tcx>;
58 impl<'tcx> HasLocalDecls<'tcx> for LocalDecls<'tcx> {
59 fn local_decls(&self) -> &LocalDecls<'tcx> {
64 impl<'tcx> HasLocalDecls<'tcx> for Body<'tcx> {
65 fn local_decls(&self) -> &LocalDecls<'tcx> {
70 /// The various "big phases" that MIR goes through.
72 /// Warning: ordering of variants is significant.
93 /// Gets the index of the current MirPhase within the set of all `MirPhase`s.
94 pub fn phase_index(&self) -> usize {
99 /// The lowered representation of a single function.
100 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable, TypeFoldable)]
101 pub struct Body<'tcx> {
102 /// A list of basic blocks. References to basic block use a newtyped index type `BasicBlock`
103 /// that indexes into this vector.
104 basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
106 /// Records how far through the "desugaring and optimization" process this particular
107 /// MIR has traversed. This is particularly useful when inlining, since in that context
108 /// we instantiate the promoted constants and add them to our promoted vector -- but those
109 /// promoted items have already been optimized, whereas ours have not. This field allows
110 /// us to see the difference and forego optimization on the inlined promoted items.
113 /// A list of source scopes; these are referenced by statements
114 /// and used for debuginfo. Indexed by a `SourceScope`.
115 pub source_scopes: IndexVec<SourceScope, SourceScopeData>,
117 /// The yield type of the function, if it is a generator.
118 pub yield_ty: Option<Ty<'tcx>>,
120 /// Generator drop glue.
121 pub generator_drop: Option<Box<BodyAndCache<'tcx>>>,
123 /// The layout of a generator. Produced by the state transformation.
124 pub generator_layout: Option<GeneratorLayout<'tcx>>,
126 /// If this is a generator then record the type of source expression that caused this generator
128 pub generator_kind: Option<GeneratorKind>,
130 /// Declarations of locals.
132 /// The first local is the return value pointer, followed by `arg_count`
133 /// locals for the function arguments, followed by any user-declared
134 /// variables and temporaries.
135 pub local_decls: LocalDecls<'tcx>,
137 /// User type annotations.
138 pub user_type_annotations: CanonicalUserTypeAnnotations<'tcx>,
140 /// The number of arguments this function takes.
142 /// Starting at local 1, `arg_count` locals will be provided by the caller
143 /// and can be assumed to be initialized.
145 /// If this MIR was built for a constant, this will be 0.
146 pub arg_count: usize,
148 /// Mark an argument local (which must be a tuple) as getting passed as
149 /// its individual components at the LLVM level.
151 /// This is used for the "rust-call" ABI.
152 pub spread_arg: Option<Local>,
154 /// Debug information pertaining to user variables, including captures.
155 pub var_debug_info: Vec<VarDebugInfo<'tcx>>,
157 /// Mark this MIR of a const context other than const functions as having converted a `&&` or
158 /// `||` expression into `&` or `|` respectively. This is problematic because if we ever stop
159 /// this conversion from happening and use short circuiting, we will cause the following code
160 /// to change the value of `x`: `let mut x = 42; false && { x = 55; true };`
162 /// List of places where control flow was destroyed. Used for error reporting.
163 pub control_flow_destroyed: Vec<(Span, String)>,
165 /// A span representing this MIR, for error reporting.
168 /// The user may be writing e.g. &[(SOME_CELL, 42)][i].1 and this would get promoted, because
169 /// we'd statically know that no thing with interior mutability will ever be available to the
170 /// user without some serious unsafe code. Now this means that our promoted is actually
171 /// &[(SOME_CELL, 42)] and the MIR using it will do the &promoted[i].1 projection because the
172 /// index may be a runtime value. Such a promoted value is illegal because it has reachable
173 /// interior mutability. This flag just makes this situation very obvious where the previous
174 /// implementation without the flag hid this situation silently.
175 /// FIXME(oli-obk): rewrite the promoted during promotion to eliminate the cell components.
176 pub ignore_interior_mut_in_const_validation: bool,
179 impl<'tcx> Body<'tcx> {
181 basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
182 source_scopes: IndexVec<SourceScope, SourceScopeData>,
183 local_decls: LocalDecls<'tcx>,
184 user_type_annotations: CanonicalUserTypeAnnotations<'tcx>,
186 var_debug_info: Vec<VarDebugInfo<'tcx>>,
188 control_flow_destroyed: Vec<(Span, String)>,
189 generator_kind: Option<GeneratorKind>,
191 // We need `arg_count` locals, and one for the return place.
193 local_decls.len() >= arg_count + 1,
194 "expected at least {} locals, got {}",
200 phase: MirPhase::Build,
204 generator_drop: None,
205 generator_layout: None,
208 user_type_annotations,
213 ignore_interior_mut_in_const_validation: false,
214 control_flow_destroyed,
218 /// Returns a partially initialized MIR body containing only a list of basic blocks.
220 /// The returned MIR contains no `LocalDecl`s (even for the return place) or source scopes. It
221 /// is only useful for testing but cannot be `#[cfg(test)]` because it is used in a different
223 pub fn new_cfg_only(basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>) -> Self {
225 phase: MirPhase::Build,
227 source_scopes: IndexVec::new(),
229 generator_drop: None,
230 generator_layout: None,
231 local_decls: IndexVec::new(),
232 user_type_annotations: IndexVec::new(),
236 control_flow_destroyed: Vec::new(),
237 generator_kind: None,
238 var_debug_info: Vec::new(),
239 ignore_interior_mut_in_const_validation: false,
244 pub fn basic_blocks(&self) -> &IndexVec<BasicBlock, BasicBlockData<'tcx>> {
248 /// Returns `true` if a cycle exists in the control-flow graph that is reachable from the
250 pub fn is_cfg_cyclic(&self) -> bool {
251 graph::is_cyclic(self)
255 pub fn local_kind(&self, local: Local) -> LocalKind {
256 let index = local.as_usize();
259 self.local_decls[local].mutability == Mutability::Mut,
260 "return place should be mutable"
263 LocalKind::ReturnPointer
264 } else if index < self.arg_count + 1 {
266 } else if self.local_decls[local].is_user_variable() {
273 /// Returns an iterator over all temporaries.
275 pub fn temps_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
276 (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
277 let local = Local::new(index);
278 if self.local_decls[local].is_user_variable() { None } else { Some(local) }
282 /// Returns an iterator over all user-declared locals.
284 pub fn vars_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
285 (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
286 let local = Local::new(index);
287 self.local_decls[local].is_user_variable().then_some(local)
291 /// Returns an iterator over all user-declared mutable locals.
293 pub fn mut_vars_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
294 (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
295 let local = Local::new(index);
296 let decl = &self.local_decls[local];
297 if decl.is_user_variable() && decl.mutability == Mutability::Mut {
305 /// Returns an iterator over all user-declared mutable arguments and locals.
307 pub fn mut_vars_and_args_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
308 (1..self.local_decls.len()).filter_map(move |index| {
309 let local = Local::new(index);
310 let decl = &self.local_decls[local];
311 if (decl.is_user_variable() || index < self.arg_count + 1)
312 && decl.mutability == Mutability::Mut
321 /// Returns an iterator over all function arguments.
323 pub fn args_iter(&self) -> impl Iterator<Item = Local> + ExactSizeIterator {
324 let arg_count = self.arg_count;
325 (1..arg_count + 1).map(Local::new)
328 /// Returns an iterator over all user-defined variables and compiler-generated temporaries (all
329 /// locals that are neither arguments nor the return place).
331 pub fn vars_and_temps_iter(&self) -> impl Iterator<Item = Local> + ExactSizeIterator {
332 let arg_count = self.arg_count;
333 let local_count = self.local_decls.len();
334 (arg_count + 1..local_count).map(Local::new)
337 /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
338 /// invalidating statement indices in `Location`s.
339 pub fn make_statement_nop(&mut self, location: Location) {
340 let block = &mut self.basic_blocks[location.block];
341 debug_assert!(location.statement_index < block.statements.len());
342 block.statements[location.statement_index].make_nop()
345 /// Returns the source info associated with `location`.
346 pub fn source_info(&self, location: Location) -> &SourceInfo {
347 let block = &self[location.block];
348 let stmts = &block.statements;
349 let idx = location.statement_index;
350 if idx < stmts.len() {
351 &stmts[idx].source_info
353 assert_eq!(idx, stmts.len());
354 &block.terminator().source_info
358 /// Checks if `sub` is a sub scope of `sup`
359 pub fn is_sub_scope(&self, mut sub: SourceScope, sup: SourceScope) -> bool {
361 match self.source_scopes[sub].parent_scope {
362 None => return false,
369 /// Returns the return type; it always return first element from `local_decls` array.
370 pub fn return_ty(&self) -> Ty<'tcx> {
371 self.local_decls[RETURN_PLACE].ty
374 /// Gets the location of the terminator for the given block.
375 pub fn terminator_loc(&self, bb: BasicBlock) -> Location {
376 Location { block: bb, statement_index: self[bb].statements.len() }
380 #[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
383 /// Unsafe because of a PushUnsafeBlock
385 /// Unsafe because of an unsafe fn
387 /// Unsafe because of an `unsafe` block
388 ExplicitUnsafe(hir::HirId),
391 impl<'tcx> Index<BasicBlock> for Body<'tcx> {
392 type Output = BasicBlockData<'tcx>;
395 fn index(&self, index: BasicBlock) -> &BasicBlockData<'tcx> {
396 &self.basic_blocks()[index]
400 #[derive(Copy, Clone, Debug, HashStable, TypeFoldable)]
401 pub enum ClearCrossCrate<T> {
406 impl<T> ClearCrossCrate<T> {
407 pub fn as_ref(&'a self) -> ClearCrossCrate<&'a T> {
409 ClearCrossCrate::Clear => ClearCrossCrate::Clear,
410 ClearCrossCrate::Set(v) => ClearCrossCrate::Set(v),
414 pub fn assert_crate_local(self) -> T {
416 ClearCrossCrate::Clear => bug!("unwrapping cross-crate data"),
417 ClearCrossCrate::Set(v) => v,
422 impl<T: Encodable> rustc_serialize::UseSpecializedEncodable for ClearCrossCrate<T> {}
423 impl<T: Decodable> rustc_serialize::UseSpecializedDecodable for ClearCrossCrate<T> {}
425 /// Grouped information about the source code origin of a MIR entity.
426 /// Intended to be inspected by diagnostics and debuginfo.
427 /// Most passes can work with it as a whole, within a single function.
428 // The unofficial Cranelift backend, at least as of #65828, needs `SourceInfo` to implement `Eq` and
429 // `Hash`. Please ping @bjorn3 if removing them.
430 #[derive(Copy, Clone, Debug, Eq, PartialEq, RustcEncodable, RustcDecodable, Hash, HashStable)]
431 pub struct SourceInfo {
432 /// The source span for the AST pertaining to this MIR entity.
435 /// The source scope, keeping track of which bindings can be
436 /// seen by debuginfo, active lint levels, `unsafe {...}`, etc.
437 pub scope: SourceScope,
440 ///////////////////////////////////////////////////////////////////////////
455 pub enum BorrowKind {
456 /// Data must be immutable and is aliasable.
459 /// The immediately borrowed place must be immutable, but projections from
460 /// it don't need to be. For example, a shallow borrow of `a.b` doesn't
461 /// conflict with a mutable borrow of `a.b.c`.
463 /// This is used when lowering matches: when matching on a place we want to
464 /// ensure that place have the same value from the start of the match until
465 /// an arm is selected. This prevents this code from compiling:
467 /// let mut x = &Some(0);
470 /// Some(_) if { x = &None; false } => (),
474 /// This can't be a shared borrow because mutably borrowing (*x as Some).0
475 /// should not prevent `if let None = x { ... }`, for example, because the
476 /// mutating `(*x as Some).0` can't affect the discriminant of `x`.
477 /// We can also report errors with this kind of borrow differently.
480 /// Data must be immutable but not aliasable. This kind of borrow
481 /// cannot currently be expressed by the user and is used only in
482 /// implicit closure bindings. It is needed when the closure is
483 /// borrowing or mutating a mutable referent, e.g.:
485 /// let x: &mut isize = ...;
486 /// let y = || *x += 5;
488 /// If we were to try to translate this closure into a more explicit
489 /// form, we'd encounter an error with the code as written:
491 /// struct Env { x: & &mut isize }
492 /// let x: &mut isize = ...;
493 /// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn
494 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
496 /// This is then illegal because you cannot mutate an `&mut` found
497 /// in an aliasable location. To solve, you'd have to translate with
498 /// an `&mut` borrow:
500 /// struct Env { x: & &mut isize }
501 /// let x: &mut isize = ...;
502 /// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
503 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
505 /// Now the assignment to `**env.x` is legal, but creating a
506 /// mutable pointer to `x` is not because `x` is not mutable. We
507 /// could fix this by declaring `x` as `let mut x`. This is ok in
508 /// user code, if awkward, but extra weird for closures, since the
509 /// borrow is hidden.
511 /// So we introduce a "unique imm" borrow -- the referent is
512 /// immutable, but not aliasable. This solves the problem. For
513 /// simplicity, we don't give users the way to express this
514 /// borrow, it's just used when translating closures.
517 /// Data is mutable and not aliasable.
519 /// `true` if this borrow arose from method-call auto-ref
520 /// (i.e., `adjustment::Adjust::Borrow`).
521 allow_two_phase_borrow: bool,
526 pub fn allows_two_phase_borrow(&self) -> bool {
528 BorrowKind::Shared | BorrowKind::Shallow | BorrowKind::Unique => false,
529 BorrowKind::Mut { allow_two_phase_borrow } => allow_two_phase_borrow,
534 ///////////////////////////////////////////////////////////////////////////
535 // Variables and temps
537 rustc_index::newtype_index! {
540 DEBUG_FORMAT = "_{}",
541 const RETURN_PLACE = 0,
545 impl Atom for Local {
546 fn index(self) -> usize {
551 /// Classifies locals into categories. See `Body::local_kind`.
552 #[derive(PartialEq, Eq, Debug, HashStable)]
554 /// User-declared variable binding.
556 /// Compiler-introduced temporary.
558 /// Function argument.
560 /// Location of function's return value.
564 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
565 pub struct VarBindingForm<'tcx> {
566 /// Is variable bound via `x`, `mut x`, `ref x`, or `ref mut x`?
567 pub binding_mode: ty::BindingMode,
568 /// If an explicit type was provided for this variable binding,
569 /// this holds the source Span of that type.
571 /// NOTE: if you want to change this to a `HirId`, be wary that
572 /// doing so breaks incremental compilation (as of this writing),
573 /// while a `Span` does not cause our tests to fail.
574 pub opt_ty_info: Option<Span>,
575 /// Place of the RHS of the =, or the subject of the `match` where this
576 /// variable is initialized. None in the case of `let PATTERN;`.
577 /// Some((None, ..)) in the case of and `let [mut] x = ...` because
578 /// (a) the right-hand side isn't evaluated as a place expression.
579 /// (b) it gives a way to separate this case from the remaining cases
581 pub opt_match_place: Option<(Option<Place<'tcx>>, Span)>,
582 /// The span of the pattern in which this variable was bound.
586 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
587 pub enum BindingForm<'tcx> {
588 /// This is a binding for a non-`self` binding, or a `self` that has an explicit type.
589 Var(VarBindingForm<'tcx>),
590 /// Binding for a `self`/`&self`/`&mut self` binding where the type is implicit.
591 ImplicitSelf(ImplicitSelfKind),
592 /// Reference used in a guard expression to ensure immutability.
596 /// Represents what type of implicit self a function has, if any.
597 #[derive(Clone, Copy, PartialEq, Debug, RustcEncodable, RustcDecodable, HashStable)]
598 pub enum ImplicitSelfKind {
599 /// Represents a `fn x(self);`.
601 /// Represents a `fn x(mut self);`.
603 /// Represents a `fn x(&self);`.
605 /// Represents a `fn x(&mut self);`.
607 /// Represents when a function does not have a self argument or
608 /// when a function has a `self: X` argument.
612 CloneTypeFoldableAndLiftImpls! { BindingForm<'tcx>, }
614 mod binding_form_impl {
615 use crate::ich::StableHashingContext;
616 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
618 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for super::BindingForm<'tcx> {
619 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
620 use super::BindingForm::*;
621 ::std::mem::discriminant(self).hash_stable(hcx, hasher);
624 Var(binding) => binding.hash_stable(hcx, hasher),
625 ImplicitSelf(kind) => kind.hash_stable(hcx, hasher),
632 /// `BlockTailInfo` is attached to the `LocalDecl` for temporaries
633 /// created during evaluation of expressions in a block tail
634 /// expression; that is, a block like `{ STMT_1; STMT_2; EXPR }`.
636 /// It is used to improve diagnostics when such temporaries are
637 /// involved in borrow_check errors, e.g., explanations of where the
638 /// temporaries come from, when their destructors are run, and/or how
639 /// one might revise the code to satisfy the borrow checker's rules.
640 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
641 pub struct BlockTailInfo {
642 /// If `true`, then the value resulting from evaluating this tail
643 /// expression is ignored by the block's expression context.
645 /// Examples include `{ ...; tail };` and `let _ = { ...; tail };`
646 /// but not e.g., `let _x = { ...; tail };`
647 pub tail_result_is_ignored: bool,
652 /// This can be a binding declared by the user, a temporary inserted by the compiler, a function
653 /// argument, or the return place.
654 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
655 pub struct LocalDecl<'tcx> {
656 /// Whether this is a mutable minding (i.e., `let x` or `let mut x`).
658 /// Temporaries and the return place are always mutable.
659 pub mutability: Mutability,
661 // FIXME(matthewjasper) Don't store in this in `Body`
662 pub local_info: LocalInfo<'tcx>,
664 /// `true` if this is an internal local.
666 /// These locals are not based on types in the source code and are only used
667 /// for a few desugarings at the moment.
669 /// The generator transformation will sanity check the locals which are live
670 /// across a suspension point against the type components of the generator
671 /// which type checking knows are live across a suspension point. We need to
672 /// flag drop flags to avoid triggering this check as they are introduced
675 /// Unsafety checking will also ignore dereferences of these locals,
676 /// so they can be used for raw pointers only used in a desugaring.
678 /// This should be sound because the drop flags are fully algebraic, and
679 /// therefore don't affect the OIBIT or outlives properties of the
683 /// If this local is a temporary and `is_block_tail` is `Some`,
684 /// then it is a temporary created for evaluation of some
685 /// subexpression of some block's tail expression (with no
686 /// intervening statement context).
687 // FIXME(matthewjasper) Don't store in this in `Body`
688 pub is_block_tail: Option<BlockTailInfo>,
690 /// The type of this local.
693 /// If the user manually ascribed a type to this variable,
694 /// e.g., via `let x: T`, then we carry that type here. The MIR
695 /// borrow checker needs this information since it can affect
696 /// region inference.
697 // FIXME(matthewjasper) Don't store in this in `Body`
698 pub user_ty: UserTypeProjections,
700 /// The *syntactic* (i.e., not visibility) source scope the local is defined
701 /// in. If the local was defined in a let-statement, this
702 /// is *within* the let-statement, rather than outside
705 /// This is needed because the visibility source scope of locals within
706 /// a let-statement is weird.
708 /// The reason is that we want the local to be *within* the let-statement
709 /// for lint purposes, but we want the local to be *after* the let-statement
710 /// for names-in-scope purposes.
712 /// That's it, if we have a let-statement like the one in this
716 /// fn foo(x: &str) {
717 /// #[allow(unused_mut)]
718 /// let mut x: u32 = { // <- one unused mut
719 /// let mut y: u32 = x.parse().unwrap();
726 /// Then, from a lint point of view, the declaration of `x: u32`
727 /// (and `y: u32`) are within the `#[allow(unused_mut)]` scope - the
728 /// lint scopes are the same as the AST/HIR nesting.
730 /// However, from a name lookup point of view, the scopes look more like
731 /// as if the let-statements were `match` expressions:
734 /// fn foo(x: &str) {
736 /// match x.parse().unwrap() {
745 /// We care about the name-lookup scopes for debuginfo - if the
746 /// debuginfo instruction pointer is at the call to `x.parse()`, we
747 /// want `x` to refer to `x: &str`, but if it is at the call to
748 /// `drop(x)`, we want it to refer to `x: u32`.
750 /// To allow both uses to work, we need to have more than a single scope
751 /// for a local. We have the `source_info.scope` represent the "syntactic"
752 /// lint scope (with a variable being under its let block) while the
753 /// `var_debug_info.source_info.scope` represents the "local variable"
754 /// scope (where the "rest" of a block is under all prior let-statements).
756 /// The end result looks like this:
760 /// │{ argument x: &str }
762 /// │ │{ #[allow(unused_mut)] } // This is actually split into 2 scopes
763 /// │ │ // in practice because I'm lazy.
765 /// │ │← x.source_info.scope
766 /// │ │← `x.parse().unwrap()`
768 /// │ │ │← y.source_info.scope
770 /// │ │ │{ let y: u32 }
772 /// │ │ │← y.var_debug_info.source_info.scope
775 /// │ │{ let x: u32 }
776 /// │ │← x.var_debug_info.source_info.scope
777 /// │ │← `drop(x)` // This accesses `x: u32`.
779 pub source_info: SourceInfo,
782 /// Extra information about a local that's used for diagnostics.
783 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
784 pub enum LocalInfo<'tcx> {
785 /// A user-defined local variable or function parameter
787 /// The `BindingForm` is solely used for local diagnostics when generating
788 /// warnings/errors when compiling the current crate, and therefore it need
789 /// not be visible across crates.
790 User(ClearCrossCrate<BindingForm<'tcx>>),
791 /// A temporary created that references the static with the given `DefId`.
792 StaticRef { def_id: DefId, is_thread_local: bool },
793 /// Any other temporary, the return place, or an anonymous function parameter.
797 impl<'tcx> LocalDecl<'tcx> {
798 /// Returns `true` only if local is a binding that can itself be
799 /// made mutable via the addition of the `mut` keyword, namely
800 /// something like the occurrences of `x` in:
801 /// - `fn foo(x: Type) { ... }`,
803 /// - or `match ... { C(x) => ... }`
804 pub fn can_be_made_mutable(&self) -> bool {
805 match self.local_info {
806 LocalInfo::User(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
807 binding_mode: ty::BindingMode::BindByValue(_),
813 LocalInfo::User(ClearCrossCrate::Set(BindingForm::ImplicitSelf(
814 ImplicitSelfKind::Imm,
821 /// Returns `true` if local is definitely not a `ref ident` or
822 /// `ref mut ident` binding. (Such bindings cannot be made into
823 /// mutable bindings, but the inverse does not necessarily hold).
824 pub fn is_nonref_binding(&self) -> bool {
825 match self.local_info {
826 LocalInfo::User(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
827 binding_mode: ty::BindingMode::BindByValue(_),
833 LocalInfo::User(ClearCrossCrate::Set(BindingForm::ImplicitSelf(_))) => true,
839 /// Returns `true` if this variable is a named variable or function
840 /// parameter declared by the user.
842 pub fn is_user_variable(&self) -> bool {
843 match self.local_info {
844 LocalInfo::User(_) => true,
849 /// Returns `true` if this is a reference to a variable bound in a `match`
850 /// expression that is used to access said variable for the guard of the
852 pub fn is_ref_for_guard(&self) -> bool {
853 match self.local_info {
854 LocalInfo::User(ClearCrossCrate::Set(BindingForm::RefForGuard)) => true,
859 /// Returns `Some` if this is a reference to a static item that is used to
860 /// access that static
861 pub fn is_ref_to_static(&self) -> bool {
862 match self.local_info {
863 LocalInfo::StaticRef { .. } => true,
868 /// Returns `Some` if this is a reference to a static item that is used to
869 /// access that static
870 pub fn is_ref_to_thread_local(&self) -> bool {
871 match self.local_info {
872 LocalInfo::StaticRef { is_thread_local, .. } => is_thread_local,
877 /// Returns `true` is the local is from a compiler desugaring, e.g.,
878 /// `__next` from a `for` loop.
880 pub fn from_compiler_desugaring(&self) -> bool {
881 self.source_info.span.desugaring_kind().is_some()
884 /// Creates a new `LocalDecl` for a temporary.
886 pub fn new_temp(ty: Ty<'tcx>, span: Span) -> Self {
887 Self::new_local(ty, Mutability::Mut, false, span)
890 /// Converts `self` into same `LocalDecl` except tagged as immutable.
892 pub fn immutable(mut self) -> Self {
893 self.mutability = Mutability::Not;
897 /// Converts `self` into same `LocalDecl` except tagged as internal temporary.
899 pub fn block_tail(mut self, info: BlockTailInfo) -> Self {
900 assert!(self.is_block_tail.is_none());
901 self.is_block_tail = Some(info);
905 /// Creates a new `LocalDecl` for a internal temporary.
907 pub fn new_internal(ty: Ty<'tcx>, span: Span) -> Self {
908 Self::new_local(ty, Mutability::Mut, true, span)
912 fn new_local(ty: Ty<'tcx>, mutability: Mutability, internal: bool, span: Span) -> Self {
916 user_ty: UserTypeProjections::none(),
917 source_info: SourceInfo { span, scope: OUTERMOST_SOURCE_SCOPE },
919 local_info: LocalInfo::Other,
924 /// Builds a `LocalDecl` for the return place.
926 /// This must be inserted into the `local_decls` list as the first local.
928 pub fn new_return_place(return_ty: Ty<'_>, span: Span) -> LocalDecl<'_> {
930 mutability: Mutability::Mut,
932 user_ty: UserTypeProjections::none(),
933 source_info: SourceInfo { span, scope: OUTERMOST_SOURCE_SCOPE },
936 local_info: LocalInfo::Other,
941 /// Debug information pertaining to a user variable.
942 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
943 pub struct VarDebugInfo<'tcx> {
946 /// Source info of the user variable, including the scope
947 /// within which the variable is visible (to debuginfo)
948 /// (see `LocalDecl`'s `source_info` field for more details).
949 pub source_info: SourceInfo,
951 /// Where the data for this user variable is to be found.
952 /// NOTE(eddyb) There's an unenforced invariant that this `Place` is
953 /// based on a `Local`, not a `Static`, and contains no indexing.
954 pub place: Place<'tcx>,
957 ///////////////////////////////////////////////////////////////////////////
960 rustc_index::newtype_index! {
961 pub struct BasicBlock {
963 DEBUG_FORMAT = "bb{}",
964 const START_BLOCK = 0,
969 pub fn start_location(self) -> Location {
970 Location { block: self, statement_index: 0 }
974 ///////////////////////////////////////////////////////////////////////////
975 // BasicBlockData and Terminator
977 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
978 pub struct BasicBlockData<'tcx> {
979 /// List of statements in this block.
980 pub statements: Vec<Statement<'tcx>>,
982 /// Terminator for this block.
984 /// N.B., this should generally ONLY be `None` during construction.
985 /// Therefore, you should generally access it via the
986 /// `terminator()` or `terminator_mut()` methods. The only
987 /// exception is that certain passes, such as `simplify_cfg`, swap
988 /// out the terminator temporarily with `None` while they continue
989 /// to recurse over the set of basic blocks.
990 pub terminator: Option<Terminator<'tcx>>,
992 /// If true, this block lies on an unwind path. This is used
993 /// during codegen where distinct kinds of basic blocks may be
994 /// generated (particularly for MSVC cleanup). Unwind blocks must
995 /// only branch to other unwind blocks.
996 pub is_cleanup: bool,
999 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
1000 pub struct Terminator<'tcx> {
1001 pub source_info: SourceInfo,
1002 pub kind: TerminatorKind<'tcx>,
1005 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable, PartialEq)]
1006 pub enum TerminatorKind<'tcx> {
1007 /// Block should have one successor in the graph; we jump there.
1008 Goto { target: BasicBlock },
1010 /// Operand evaluates to an integer; jump depending on its value
1011 /// to one of the targets, and otherwise fallback to `otherwise`.
1013 /// The discriminant value being tested.
1014 discr: Operand<'tcx>,
1016 /// The type of value being tested.
1017 switch_ty: Ty<'tcx>,
1019 /// Possible values. The locations to branch to in each case
1020 /// are found in the corresponding indices from the `targets` vector.
1021 values: Cow<'tcx, [u128]>,
1023 /// Possible branch sites. The last element of this vector is used
1024 /// for the otherwise branch, so targets.len() == values.len() + 1
1027 // This invariant is quite non-obvious and also could be improved.
1028 // One way to make this invariant is to have something like this instead:
1030 // branches: Vec<(ConstInt, BasicBlock)>,
1031 // otherwise: Option<BasicBlock> // exhaustive if None
1033 // However we’ve decided to keep this as-is until we figure a case
1034 // where some other approach seems to be strictly better than other.
1035 targets: Vec<BasicBlock>,
1038 /// Indicates that the landing pad is finished and unwinding should
1039 /// continue. Emitted by `build::scope::diverge_cleanup`.
1042 /// Indicates that the landing pad is finished and that the process
1043 /// should abort. Used to prevent unwinding for foreign items.
1046 /// Indicates a normal return. The return place should have
1047 /// been filled in by now. This should occur at most once.
1050 /// Indicates a terminator that can never be reached.
1053 /// Drop the `Place`.
1054 Drop { location: Place<'tcx>, target: BasicBlock, unwind: Option<BasicBlock> },
1056 /// Drop the `Place` and assign the new value over it. This ensures
1057 /// that the assignment to `P` occurs *even if* the destructor for
1058 /// place unwinds. Its semantics are best explained by the
1063 /// DropAndReplace(P <- V, goto BB1, unwind BB2)
1071 /// Drop(P, goto BB1, unwind BB2)
1074 /// // P is now uninitialized
1078 /// // P is now uninitialized -- its dtor panicked
1083 location: Place<'tcx>,
1084 value: Operand<'tcx>,
1086 unwind: Option<BasicBlock>,
1089 /// Block ends with a call of a converging function.
1091 /// The function that’s being called.
1092 func: Operand<'tcx>,
1093 /// Arguments the function is called with.
1094 /// These are owned by the callee, which is free to modify them.
1095 /// This allows the memory occupied by "by-value" arguments to be
1096 /// reused across function calls without duplicating the contents.
1097 args: Vec<Operand<'tcx>>,
1098 /// Destination for the return value. If some, the call is converging.
1099 destination: Option<(Place<'tcx>, BasicBlock)>,
1100 /// Cleanups to be done if the call unwinds.
1101 cleanup: Option<BasicBlock>,
1102 /// `true` if this is from a call in HIR rather than from an overloaded
1103 /// operator. True for overloaded function call.
1104 from_hir_call: bool,
1107 /// Jump to the target if the condition has the expected value,
1108 /// otherwise panic with a message and a cleanup target.
1110 cond: Operand<'tcx>,
1112 msg: AssertMessage<'tcx>,
1114 cleanup: Option<BasicBlock>,
1117 /// A suspend point.
1119 /// The value to return.
1120 value: Operand<'tcx>,
1121 /// Where to resume to.
1123 /// Cleanup to be done if the generator is dropped at this suspend point.
1124 drop: Option<BasicBlock>,
1127 /// Indicates the end of the dropping of a generator.
1130 /// A block where control flow only ever takes one real path, but borrowck
1131 /// needs to be more conservative.
1133 /// The target normal control flow will take.
1134 real_target: BasicBlock,
1135 /// A block control flow could conceptually jump to, but won't in
1137 imaginary_target: BasicBlock,
1139 /// A terminator for blocks that only take one path in reality, but where we
1140 /// reserve the right to unwind in borrowck, even if it won't happen in practice.
1141 /// This can arise in infinite loops with no function calls for example.
1143 /// The target normal control flow will take.
1144 real_target: BasicBlock,
1145 /// The imaginary cleanup block link. This particular path will never be taken
1146 /// in practice, but in order to avoid fragility we want to always
1147 /// consider it in borrowck. We don't want to accept programs which
1148 /// pass borrowck only when `panic=abort` or some assertions are disabled
1149 /// due to release vs. debug mode builds. This needs to be an `Option` because
1150 /// of the `remove_noop_landing_pads` and `no_landing_pads` passes.
1151 unwind: Option<BasicBlock>,
1155 pub type Successors<'a> =
1156 iter::Chain<option::IntoIter<&'a BasicBlock>, slice::Iter<'a, BasicBlock>>;
1157 pub type SuccessorsMut<'a> =
1158 iter::Chain<option::IntoIter<&'a mut BasicBlock>, slice::IterMut<'a, BasicBlock>>;
1160 impl<'tcx> Terminator<'tcx> {
1161 pub fn successors(&self) -> Successors<'_> {
1162 self.kind.successors()
1165 pub fn successors_mut(&mut self) -> SuccessorsMut<'_> {
1166 self.kind.successors_mut()
1169 pub fn unwind(&self) -> Option<&Option<BasicBlock>> {
1173 pub fn unwind_mut(&mut self) -> Option<&mut Option<BasicBlock>> {
1174 self.kind.unwind_mut()
1178 impl<'tcx> TerminatorKind<'tcx> {
1181 cond: Operand<'tcx>,
1184 ) -> TerminatorKind<'tcx> {
1185 static BOOL_SWITCH_FALSE: &'static [u128] = &[0];
1186 TerminatorKind::SwitchInt {
1188 switch_ty: tcx.types.bool,
1189 values: From::from(BOOL_SWITCH_FALSE),
1190 targets: vec![f, t],
1194 pub fn successors(&self) -> Successors<'_> {
1195 use self::TerminatorKind::*;
1202 | Call { destination: None, cleanup: None, .. } => None.into_iter().chain(&[]),
1203 Goto { target: ref t }
1204 | Call { destination: None, cleanup: Some(ref t), .. }
1205 | Call { destination: Some((_, ref t)), cleanup: None, .. }
1206 | Yield { resume: ref t, drop: None, .. }
1207 | DropAndReplace { target: ref t, unwind: None, .. }
1208 | Drop { target: ref t, unwind: None, .. }
1209 | Assert { target: ref t, cleanup: None, .. }
1210 | FalseUnwind { real_target: ref t, unwind: None } => Some(t).into_iter().chain(&[]),
1211 Call { destination: Some((_, ref t)), cleanup: Some(ref u), .. }
1212 | Yield { resume: ref t, drop: Some(ref u), .. }
1213 | DropAndReplace { target: ref t, unwind: Some(ref u), .. }
1214 | Drop { target: ref t, unwind: Some(ref u), .. }
1215 | Assert { target: ref t, cleanup: Some(ref u), .. }
1216 | FalseUnwind { real_target: ref t, unwind: Some(ref u) } => {
1217 Some(t).into_iter().chain(slice::from_ref(u))
1219 SwitchInt { ref targets, .. } => None.into_iter().chain(&targets[..]),
1220 FalseEdges { ref real_target, ref imaginary_target } => {
1221 Some(real_target).into_iter().chain(slice::from_ref(imaginary_target))
1226 pub fn successors_mut(&mut self) -> SuccessorsMut<'_> {
1227 use self::TerminatorKind::*;
1234 | Call { destination: None, cleanup: None, .. } => None.into_iter().chain(&mut []),
1235 Goto { target: ref mut t }
1236 | Call { destination: None, cleanup: Some(ref mut t), .. }
1237 | Call { destination: Some((_, ref mut t)), cleanup: None, .. }
1238 | Yield { resume: ref mut t, drop: None, .. }
1239 | DropAndReplace { target: ref mut t, unwind: None, .. }
1240 | Drop { target: ref mut t, unwind: None, .. }
1241 | Assert { target: ref mut t, cleanup: None, .. }
1242 | FalseUnwind { real_target: ref mut t, unwind: None } => {
1243 Some(t).into_iter().chain(&mut [])
1245 Call { destination: Some((_, ref mut t)), cleanup: Some(ref mut u), .. }
1246 | Yield { resume: ref mut t, drop: Some(ref mut u), .. }
1247 | DropAndReplace { target: ref mut t, unwind: Some(ref mut u), .. }
1248 | Drop { target: ref mut t, unwind: Some(ref mut u), .. }
1249 | Assert { target: ref mut t, cleanup: Some(ref mut u), .. }
1250 | FalseUnwind { real_target: ref mut t, unwind: Some(ref mut u) } => {
1251 Some(t).into_iter().chain(slice::from_mut(u))
1253 SwitchInt { ref mut targets, .. } => None.into_iter().chain(&mut targets[..]),
1254 FalseEdges { ref mut real_target, ref mut imaginary_target } => {
1255 Some(real_target).into_iter().chain(slice::from_mut(imaginary_target))
1260 pub fn unwind(&self) -> Option<&Option<BasicBlock>> {
1262 TerminatorKind::Goto { .. }
1263 | TerminatorKind::Resume
1264 | TerminatorKind::Abort
1265 | TerminatorKind::Return
1266 | TerminatorKind::Unreachable
1267 | TerminatorKind::GeneratorDrop
1268 | TerminatorKind::Yield { .. }
1269 | TerminatorKind::SwitchInt { .. }
1270 | TerminatorKind::FalseEdges { .. } => None,
1271 TerminatorKind::Call { cleanup: ref unwind, .. }
1272 | TerminatorKind::Assert { cleanup: ref unwind, .. }
1273 | TerminatorKind::DropAndReplace { ref unwind, .. }
1274 | TerminatorKind::Drop { ref unwind, .. }
1275 | TerminatorKind::FalseUnwind { ref unwind, .. } => Some(unwind),
1279 pub fn unwind_mut(&mut self) -> Option<&mut Option<BasicBlock>> {
1281 TerminatorKind::Goto { .. }
1282 | TerminatorKind::Resume
1283 | TerminatorKind::Abort
1284 | TerminatorKind::Return
1285 | TerminatorKind::Unreachable
1286 | TerminatorKind::GeneratorDrop
1287 | TerminatorKind::Yield { .. }
1288 | TerminatorKind::SwitchInt { .. }
1289 | TerminatorKind::FalseEdges { .. } => None,
1290 TerminatorKind::Call { cleanup: ref mut unwind, .. }
1291 | TerminatorKind::Assert { cleanup: ref mut unwind, .. }
1292 | TerminatorKind::DropAndReplace { ref mut unwind, .. }
1293 | TerminatorKind::Drop { ref mut unwind, .. }
1294 | TerminatorKind::FalseUnwind { ref mut unwind, .. } => Some(unwind),
1299 impl<'tcx> BasicBlockData<'tcx> {
1300 pub fn new(terminator: Option<Terminator<'tcx>>) -> BasicBlockData<'tcx> {
1301 BasicBlockData { statements: vec![], terminator, is_cleanup: false }
1304 /// Accessor for terminator.
1306 /// Terminator may not be None after construction of the basic block is complete. This accessor
1307 /// provides a convenience way to reach the terminator.
1308 pub fn terminator(&self) -> &Terminator<'tcx> {
1309 self.terminator.as_ref().expect("invalid terminator state")
1312 pub fn terminator_mut(&mut self) -> &mut Terminator<'tcx> {
1313 self.terminator.as_mut().expect("invalid terminator state")
1316 pub fn retain_statements<F>(&mut self, mut f: F)
1318 F: FnMut(&mut Statement<'_>) -> bool,
1320 for s in &mut self.statements {
1327 pub fn expand_statements<F, I>(&mut self, mut f: F)
1329 F: FnMut(&mut Statement<'tcx>) -> Option<I>,
1330 I: iter::TrustedLen<Item = Statement<'tcx>>,
1332 // Gather all the iterators we'll need to splice in, and their positions.
1333 let mut splices: Vec<(usize, I)> = vec![];
1334 let mut extra_stmts = 0;
1335 for (i, s) in self.statements.iter_mut().enumerate() {
1336 if let Some(mut new_stmts) = f(s) {
1337 if let Some(first) = new_stmts.next() {
1338 // We can already store the first new statement.
1341 // Save the other statements for optimized splicing.
1342 let remaining = new_stmts.size_hint().0;
1344 splices.push((i + 1 + extra_stmts, new_stmts));
1345 extra_stmts += remaining;
1353 // Splice in the new statements, from the end of the block.
1354 // FIXME(eddyb) This could be more efficient with a "gap buffer"
1355 // where a range of elements ("gap") is left uninitialized, with
1356 // splicing adding new elements to the end of that gap and moving
1357 // existing elements from before the gap to the end of the gap.
1358 // For now, this is safe code, emulating a gap but initializing it.
1359 let mut gap = self.statements.len()..self.statements.len() + extra_stmts;
1360 self.statements.resize(
1363 source_info: SourceInfo { span: DUMMY_SP, scope: OUTERMOST_SOURCE_SCOPE },
1364 kind: StatementKind::Nop,
1367 for (splice_start, new_stmts) in splices.into_iter().rev() {
1368 let splice_end = splice_start + new_stmts.size_hint().0;
1369 while gap.end > splice_end {
1372 self.statements.swap(gap.start, gap.end);
1374 self.statements.splice(splice_start..splice_end, new_stmts);
1375 gap.end = splice_start;
1379 pub fn visitable(&self, index: usize) -> &dyn MirVisitable<'tcx> {
1380 if index < self.statements.len() { &self.statements[index] } else { &self.terminator }
1384 impl<'tcx> Debug for TerminatorKind<'tcx> {
1385 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1386 self.fmt_head(fmt)?;
1387 let successor_count = self.successors().count();
1388 let labels = self.fmt_successor_labels();
1389 assert_eq!(successor_count, labels.len());
1391 match successor_count {
1394 1 => write!(fmt, " -> {:?}", self.successors().nth(0).unwrap()),
1397 write!(fmt, " -> [")?;
1398 for (i, target) in self.successors().enumerate() {
1402 write!(fmt, "{}: {:?}", labels[i], target)?;
1410 impl<'tcx> TerminatorKind<'tcx> {
1411 /// Writes the "head" part of the terminator; that is, its name and the data it uses to pick the
1412 /// successor basic block, if any. The only information not included is the list of possible
1413 /// successors, which may be rendered differently between the text and the graphviz format.
1414 pub fn fmt_head<W: Write>(&self, fmt: &mut W) -> fmt::Result {
1415 use self::TerminatorKind::*;
1417 Goto { .. } => write!(fmt, "goto"),
1418 SwitchInt { discr: ref place, .. } => write!(fmt, "switchInt({:?})", place),
1419 Return => write!(fmt, "return"),
1420 GeneratorDrop => write!(fmt, "generator_drop"),
1421 Resume => write!(fmt, "resume"),
1422 Abort => write!(fmt, "abort"),
1423 Yield { ref value, .. } => write!(fmt, "_1 = suspend({:?})", value),
1424 Unreachable => write!(fmt, "unreachable"),
1425 Drop { ref location, .. } => write!(fmt, "drop({:?})", location),
1426 DropAndReplace { ref location, ref value, .. } => {
1427 write!(fmt, "replace({:?} <- {:?})", location, value)
1429 Call { ref func, ref args, ref destination, .. } => {
1430 if let Some((ref destination, _)) = *destination {
1431 write!(fmt, "{:?} = ", destination)?;
1433 write!(fmt, "{:?}(", func)?;
1434 for (index, arg) in args.iter().enumerate() {
1438 write!(fmt, "{:?}", arg)?;
1442 Assert { ref cond, expected, ref msg, .. } => {
1443 write!(fmt, "assert(")?;
1447 write!(fmt, "{:?}, \"{:?}\")", cond, msg)
1449 FalseEdges { .. } => write!(fmt, "falseEdges"),
1450 FalseUnwind { .. } => write!(fmt, "falseUnwind"),
1454 /// Returns the list of labels for the edges to the successor basic blocks.
1455 pub fn fmt_successor_labels(&self) -> Vec<Cow<'static, str>> {
1456 use self::TerminatorKind::*;
1458 Return | Resume | Abort | Unreachable | GeneratorDrop => vec![],
1459 Goto { .. } => vec!["".into()],
1460 SwitchInt { ref values, switch_ty, .. } => ty::tls::with(|tcx| {
1461 let param_env = ty::ParamEnv::empty();
1462 let switch_ty = tcx.lift(&switch_ty).unwrap();
1463 let size = tcx.layout_of(param_env.and(switch_ty)).unwrap().size;
1467 ty::Const::from_scalar(tcx, Scalar::from_uint(u, size).into(), switch_ty)
1471 .chain(iter::once("otherwise".into()))
1474 Call { destination: Some(_), cleanup: Some(_), .. } => {
1475 vec!["return".into(), "unwind".into()]
1477 Call { destination: Some(_), cleanup: None, .. } => vec!["return".into()],
1478 Call { destination: None, cleanup: Some(_), .. } => vec!["unwind".into()],
1479 Call { destination: None, cleanup: None, .. } => vec![],
1480 Yield { drop: Some(_), .. } => vec!["resume".into(), "drop".into()],
1481 Yield { drop: None, .. } => vec!["resume".into()],
1482 DropAndReplace { unwind: None, .. } | Drop { unwind: None, .. } => {
1483 vec!["return".into()]
1485 DropAndReplace { unwind: Some(_), .. } | Drop { unwind: Some(_), .. } => {
1486 vec!["return".into(), "unwind".into()]
1488 Assert { cleanup: None, .. } => vec!["".into()],
1489 Assert { .. } => vec!["success".into(), "unwind".into()],
1490 FalseEdges { .. } => vec!["real".into(), "imaginary".into()],
1491 FalseUnwind { unwind: Some(_), .. } => vec!["real".into(), "cleanup".into()],
1492 FalseUnwind { unwind: None, .. } => vec!["real".into()],
1497 ///////////////////////////////////////////////////////////////////////////
1500 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
1501 pub struct Statement<'tcx> {
1502 pub source_info: SourceInfo,
1503 pub kind: StatementKind<'tcx>,
1506 // `Statement` is used a lot. Make sure it doesn't unintentionally get bigger.
1507 #[cfg(target_arch = "x86_64")]
1508 static_assert_size!(Statement<'_>, 32);
1510 impl Statement<'_> {
1511 /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
1512 /// invalidating statement indices in `Location`s.
1513 pub fn make_nop(&mut self) {
1514 self.kind = StatementKind::Nop
1517 /// Changes a statement to a nop and returns the original statement.
1518 pub fn replace_nop(&mut self) -> Self {
1520 source_info: self.source_info,
1521 kind: mem::replace(&mut self.kind, StatementKind::Nop),
1526 #[derive(Clone, Debug, PartialEq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
1527 pub enum StatementKind<'tcx> {
1528 /// Write the RHS Rvalue to the LHS Place.
1529 Assign(Box<(Place<'tcx>, Rvalue<'tcx>)>),
1531 /// This represents all the reading that a pattern match may do
1532 /// (e.g., inspecting constants and discriminant values), and the
1533 /// kind of pattern it comes from. This is in order to adapt potential
1534 /// error messages to these specific patterns.
1536 /// Note that this also is emitted for regular `let` bindings to ensure that locals that are
1537 /// never accessed still get some sanity checks for, e.g., `let x: ! = ..;`
1538 FakeRead(FakeReadCause, Box<Place<'tcx>>),
1540 /// Write the discriminant for a variant to the enum Place.
1541 SetDiscriminant { place: Box<Place<'tcx>>, variant_index: VariantIdx },
1543 /// Start a live range for the storage of the local.
1546 /// End the current live range for the storage of the local.
1549 /// Executes a piece of inline Assembly. Stored in a Box to keep the size
1550 /// of `StatementKind` low.
1551 InlineAsm(Box<InlineAsm<'tcx>>),
1553 /// Retag references in the given place, ensuring they got fresh tags. This is
1554 /// part of the Stacked Borrows model. These statements are currently only interpreted
1555 /// by miri and only generated when "-Z mir-emit-retag" is passed.
1556 /// See <https://internals.rust-lang.org/t/stacked-borrows-an-aliasing-model-for-rust/8153/>
1557 /// for more details.
1558 Retag(RetagKind, Box<Place<'tcx>>),
1560 /// Encodes a user's type ascription. These need to be preserved
1561 /// intact so that NLL can respect them. For example:
1565 /// The effect of this annotation is to relate the type `T_y` of the place `y`
1566 /// to the user-given type `T`. The effect depends on the specified variance:
1568 /// - `Covariant` -- requires that `T_y <: T`
1569 /// - `Contravariant` -- requires that `T_y :> T`
1570 /// - `Invariant` -- requires that `T_y == T`
1571 /// - `Bivariant` -- no effect
1572 AscribeUserType(Box<(Place<'tcx>, UserTypeProjection)>, ty::Variance),
1574 /// No-op. Useful for deleting instructions without affecting statement indices.
1578 /// Describes what kind of retag is to be performed.
1579 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, PartialEq, Eq, HashStable)]
1580 pub enum RetagKind {
1581 /// The initial retag when entering a function.
1583 /// Retag preparing for a two-phase borrow.
1585 /// Retagging raw pointers.
1587 /// A "normal" retag.
1591 /// The `FakeReadCause` describes the type of pattern why a FakeRead statement exists.
1592 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable, PartialEq)]
1593 pub enum FakeReadCause {
1594 /// Inject a fake read of the borrowed input at the end of each guards
1597 /// This should ensure that you cannot change the variant for an enum while
1598 /// you are in the midst of matching on it.
1601 /// `let x: !; match x {}` doesn't generate any read of x so we need to
1602 /// generate a read of x to check that it is initialized and safe.
1605 /// A fake read of the RefWithinGuard version of a bind-by-value variable
1606 /// in a match guard to ensure that it's value hasn't change by the time
1607 /// we create the OutsideGuard version.
1610 /// Officially, the semantics of
1612 /// `let pattern = <expr>;`
1614 /// is that `<expr>` is evaluated into a temporary and then this temporary is
1615 /// into the pattern.
1617 /// However, if we see the simple pattern `let var = <expr>`, we optimize this to
1618 /// evaluate `<expr>` directly into the variable `var`. This is mostly unobservable,
1619 /// but in some cases it can affect the borrow checker, as in #53695.
1620 /// Therefore, we insert a "fake read" here to ensure that we get
1621 /// appropriate errors.
1624 /// If we have an index expression like
1626 /// (*x)[1][{ x = y; 4}]
1628 /// then the first bounds check is invalidated when we evaluate the second
1629 /// index expression. Thus we create a fake borrow of `x` across the second
1630 /// indexer, which will cause a borrow check error.
1634 #[derive(Clone, Debug, PartialEq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
1635 pub struct InlineAsm<'tcx> {
1636 pub asm: hir::InlineAsmInner,
1637 pub outputs: Box<[Place<'tcx>]>,
1638 pub inputs: Box<[(Span, Operand<'tcx>)]>,
1641 impl Debug for Statement<'_> {
1642 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1643 use self::StatementKind::*;
1645 Assign(box (ref place, ref rv)) => write!(fmt, "{:?} = {:?}", place, rv),
1646 FakeRead(ref cause, ref place) => write!(fmt, "FakeRead({:?}, {:?})", cause, place),
1647 Retag(ref kind, ref place) => write!(
1651 RetagKind::FnEntry => "[fn entry] ",
1652 RetagKind::TwoPhase => "[2phase] ",
1653 RetagKind::Raw => "[raw] ",
1654 RetagKind::Default => "",
1658 StorageLive(ref place) => write!(fmt, "StorageLive({:?})", place),
1659 StorageDead(ref place) => write!(fmt, "StorageDead({:?})", place),
1660 SetDiscriminant { ref place, variant_index } => {
1661 write!(fmt, "discriminant({:?}) = {:?}", place, variant_index)
1663 InlineAsm(ref asm) => {
1664 write!(fmt, "asm!({:?} : {:?} : {:?})", asm.asm, asm.outputs, asm.inputs)
1666 AscribeUserType(box (ref place, ref c_ty), ref variance) => {
1667 write!(fmt, "AscribeUserType({:?}, {:?}, {:?})", place, variance, c_ty)
1669 Nop => write!(fmt, "nop"),
1674 ///////////////////////////////////////////////////////////////////////////
1677 /// A path to a value; something that can be evaluated without
1678 /// changing or disturbing program state.
1679 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, HashStable)]
1680 pub struct Place<'tcx> {
1683 /// projection out of a place (access a field, deref a pointer, etc)
1684 pub projection: &'tcx List<PlaceElem<'tcx>>,
1687 impl<'tcx> rustc_serialize::UseSpecializedDecodable for Place<'tcx> {}
1689 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
1690 #[derive(RustcEncodable, RustcDecodable, HashStable)]
1691 pub enum ProjectionElem<V, T> {
1696 /// These indices are generated by slice patterns. Easiest to explain
1700 /// [X, _, .._, _, _] => { offset: 0, min_length: 4, from_end: false },
1701 /// [_, X, .._, _, _] => { offset: 1, min_length: 4, from_end: false },
1702 /// [_, _, .._, X, _] => { offset: 2, min_length: 4, from_end: true },
1703 /// [_, _, .._, _, X] => { offset: 1, min_length: 4, from_end: true },
1706 /// index or -index (in Python terms), depending on from_end
1708 /// The thing being indexed must be at least this long. For arrays this
1709 /// is always the exact length.
1711 /// Counting backwards from end? This is always false when indexing an
1716 /// These indices are generated by slice patterns.
1718 /// If `from_end` is true `slice[from..slice.len() - to]`.
1719 /// Otherwise `array[from..to]`.
1723 /// Whether `to` counts from the start or end of the array/slice.
1724 /// For `PlaceElem`s this is `true` if and only if the base is a slice.
1725 /// For `ProjectionKind`, this can also be `true` for arrays.
1729 /// "Downcast" to a variant of an ADT. Currently, we only introduce
1730 /// this for ADTs with more than one variant. It may be better to
1731 /// just introduce it always, or always for enums.
1733 /// The included Symbol is the name of the variant, used for printing MIR.
1734 Downcast(Option<Symbol>, VariantIdx),
1737 impl<V, T> ProjectionElem<V, T> {
1738 /// Returns `true` if the target of this projection may refer to a different region of memory
1740 fn is_indirect(&self) -> bool {
1742 Self::Deref => true,
1746 | Self::ConstantIndex { .. }
1747 | Self::Subslice { .. }
1748 | Self::Downcast(_, _) => false,
1753 /// Alias for projections as they appear in places, where the base is a place
1754 /// and the index is a local.
1755 pub type PlaceElem<'tcx> = ProjectionElem<Local, Ty<'tcx>>;
1757 impl<'tcx> Copy for PlaceElem<'tcx> {}
1759 // At least on 64 bit systems, `PlaceElem` should not be larger than two pointers.
1760 #[cfg(target_arch = "x86_64")]
1761 static_assert_size!(PlaceElem<'_>, 16);
1763 /// Alias for projections as they appear in `UserTypeProjection`, where we
1764 /// need neither the `V` parameter for `Index` nor the `T` for `Field`.
1765 pub type ProjectionKind = ProjectionElem<(), ()>;
1767 rustc_index::newtype_index! {
1770 DEBUG_FORMAT = "field[{}]"
1774 #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
1775 pub struct PlaceRef<'a, 'tcx> {
1776 pub local: &'a Local,
1777 pub projection: &'a [PlaceElem<'tcx>],
1780 impl<'tcx> Place<'tcx> {
1781 // FIXME change this to a const fn by also making List::empty a const fn.
1782 pub fn return_place() -> Place<'tcx> {
1783 Place { local: RETURN_PLACE, projection: List::empty() }
1786 /// Returns `true` if this `Place` contains a `Deref` projection.
1788 /// If `Place::is_indirect` returns false, the caller knows that the `Place` refers to the
1789 /// same region of memory as its base.
1790 pub fn is_indirect(&self) -> bool {
1791 self.projection.iter().any(|elem| elem.is_indirect())
1794 /// Finds the innermost `Local` from this `Place`, *if* it is either a local itself or
1795 /// a single deref of a local.
1797 // FIXME: can we safely swap the semantics of `fn base_local` below in here instead?
1798 pub fn local_or_deref_local(&self) -> Option<Local> {
1799 match self.as_ref() {
1800 PlaceRef { local, projection: &[] }
1801 | PlaceRef { local, projection: &[ProjectionElem::Deref] } => Some(*local),
1806 /// If this place represents a local variable like `_X` with no
1807 /// projections, return `Some(_X)`.
1808 pub fn as_local(&self) -> Option<Local> {
1809 self.as_ref().as_local()
1812 pub fn as_ref(&self) -> PlaceRef<'_, 'tcx> {
1813 PlaceRef { local: &self.local, projection: &self.projection }
1817 impl From<Local> for Place<'_> {
1818 fn from(local: Local) -> Self {
1819 Place { local, projection: List::empty() }
1823 impl<'a, 'tcx> PlaceRef<'a, 'tcx> {
1824 /// Finds the innermost `Local` from this `Place`, *if* it is either a local itself or
1825 /// a single deref of a local.
1827 // FIXME: can we safely swap the semantics of `fn base_local` below in here instead?
1828 pub fn local_or_deref_local(&self) -> Option<Local> {
1830 PlaceRef { local, projection: [] }
1831 | PlaceRef { local, projection: [ProjectionElem::Deref] } => Some(**local),
1836 /// If this place represents a local variable like `_X` with no
1837 /// projections, return `Some(_X)`.
1838 pub fn as_local(&self) -> Option<Local> {
1840 PlaceRef { local, projection: [] } => Some(**local),
1846 impl Debug for Place<'_> {
1847 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1848 for elem in self.projection.iter().rev() {
1850 ProjectionElem::Downcast(_, _) | ProjectionElem::Field(_, _) => {
1851 write!(fmt, "(").unwrap();
1853 ProjectionElem::Deref => {
1854 write!(fmt, "(*").unwrap();
1856 ProjectionElem::Index(_)
1857 | ProjectionElem::ConstantIndex { .. }
1858 | ProjectionElem::Subslice { .. } => {}
1862 write!(fmt, "{:?}", self.local)?;
1864 for elem in self.projection.iter() {
1866 ProjectionElem::Downcast(Some(name), _index) => {
1867 write!(fmt, " as {})", name)?;
1869 ProjectionElem::Downcast(None, index) => {
1870 write!(fmt, " as variant#{:?})", index)?;
1872 ProjectionElem::Deref => {
1875 ProjectionElem::Field(field, ty) => {
1876 write!(fmt, ".{:?}: {:?})", field.index(), ty)?;
1878 ProjectionElem::Index(ref index) => {
1879 write!(fmt, "[{:?}]", index)?;
1881 ProjectionElem::ConstantIndex { offset, min_length, from_end: false } => {
1882 write!(fmt, "[{:?} of {:?}]", offset, min_length)?;
1884 ProjectionElem::ConstantIndex { offset, min_length, from_end: true } => {
1885 write!(fmt, "[-{:?} of {:?}]", offset, min_length)?;
1887 ProjectionElem::Subslice { from, to, from_end: true } if *to == 0 => {
1888 write!(fmt, "[{:?}:]", from)?;
1890 ProjectionElem::Subslice { from, to, from_end: true } if *from == 0 => {
1891 write!(fmt, "[:-{:?}]", to)?;
1893 ProjectionElem::Subslice { from, to, from_end: true } => {
1894 write!(fmt, "[{:?}:-{:?}]", from, to)?;
1896 ProjectionElem::Subslice { from, to, from_end: false } => {
1897 write!(fmt, "[{:?}..{:?}]", from, to)?;
1906 ///////////////////////////////////////////////////////////////////////////
1909 rustc_index::newtype_index! {
1910 pub struct SourceScope {
1912 DEBUG_FORMAT = "scope[{}]",
1913 const OUTERMOST_SOURCE_SCOPE = 0,
1917 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
1918 pub struct SourceScopeData {
1920 pub parent_scope: Option<SourceScope>,
1922 /// Crate-local information for this source scope, that can't (and
1923 /// needn't) be tracked across crates.
1924 pub local_data: ClearCrossCrate<SourceScopeLocalData>,
1927 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
1928 pub struct SourceScopeLocalData {
1929 /// An `HirId` with lint levels equivalent to this scope's lint levels.
1930 pub lint_root: hir::HirId,
1931 /// The unsafe block that contains this node.
1935 ///////////////////////////////////////////////////////////////////////////
1938 /// These are values that can appear inside an rvalue. They are intentionally
1939 /// limited to prevent rvalues from being nested in one another.
1940 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable)]
1941 pub enum Operand<'tcx> {
1942 /// Copy: The value must be available for use afterwards.
1944 /// This implies that the type of the place must be `Copy`; this is true
1945 /// by construction during build, but also checked by the MIR type checker.
1948 /// Move: The value (including old borrows of it) will not be used again.
1950 /// Safe for values of all types (modulo future developments towards `?Move`).
1951 /// Correct usage patterns are enforced by the borrow checker for safe code.
1952 /// `Copy` may be converted to `Move` to enable "last-use" optimizations.
1955 /// Synthesizes a constant value.
1956 Constant(Box<Constant<'tcx>>),
1959 impl<'tcx> Debug for Operand<'tcx> {
1960 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1961 use self::Operand::*;
1963 Constant(ref a) => write!(fmt, "{:?}", a),
1964 Copy(ref place) => write!(fmt, "{:?}", place),
1965 Move(ref place) => write!(fmt, "move {:?}", place),
1970 impl<'tcx> Operand<'tcx> {
1971 /// Convenience helper to make a constant that refers to the fn
1972 /// with given `DefId` and substs. Since this is used to synthesize
1973 /// MIR, assumes `user_ty` is None.
1974 pub fn function_handle(
1977 substs: SubstsRef<'tcx>,
1980 let ty = tcx.type_of(def_id).subst(tcx, substs);
1981 Operand::Constant(box Constant {
1984 literal: ty::Const::zero_sized(tcx, ty),
1988 pub fn to_copy(&self) -> Self {
1990 Operand::Copy(_) | Operand::Constant(_) => self.clone(),
1991 Operand::Move(ref place) => Operand::Copy(place.clone()),
1996 ///////////////////////////////////////////////////////////////////////////
1999 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable, PartialEq)]
2000 pub enum Rvalue<'tcx> {
2001 /// x (either a move or copy, depending on type of x)
2005 Repeat(Operand<'tcx>, u64),
2008 Ref(Region<'tcx>, BorrowKind, Place<'tcx>),
2010 /// Create a raw pointer to the given place
2011 /// Can be generated by raw address of expressions (`&raw const x`),
2012 /// or when casting a reference to a raw pointer.
2013 AddressOf(Mutability, Place<'tcx>),
2015 /// length of a [X] or [X;n] value
2018 Cast(CastKind, Operand<'tcx>, Ty<'tcx>),
2020 BinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
2021 CheckedBinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
2023 NullaryOp(NullOp, Ty<'tcx>),
2024 UnaryOp(UnOp, Operand<'tcx>),
2026 /// Read the discriminant of an ADT.
2028 /// Undefined (i.e., no effort is made to make it defined, but there’s no reason why it cannot
2029 /// be defined to return, say, a 0) if ADT is not an enum.
2030 Discriminant(Place<'tcx>),
2032 /// Creates an aggregate value, like a tuple or struct. This is
2033 /// only needed because we want to distinguish `dest = Foo { x:
2034 /// ..., y: ... }` from `dest.x = ...; dest.y = ...;` in the case
2035 /// that `Foo` has a destructor. These rvalues can be optimized
2036 /// away after type-checking and before lowering.
2037 Aggregate(Box<AggregateKind<'tcx>>, Vec<Operand<'tcx>>),
2040 #[derive(Clone, Copy, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2043 Pointer(PointerCast),
2046 #[derive(Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2047 pub enum AggregateKind<'tcx> {
2048 /// The type is of the element
2052 /// The second field is the variant index. It's equal to 0 for struct
2053 /// and union expressions. The fourth field is
2054 /// active field number and is present only for union expressions
2055 /// -- e.g., for a union expression `SomeUnion { c: .. }`, the
2056 /// active field index would identity the field `c`
2057 Adt(&'tcx AdtDef, VariantIdx, SubstsRef<'tcx>, Option<UserTypeAnnotationIndex>, Option<usize>),
2059 Closure(DefId, SubstsRef<'tcx>),
2060 Generator(DefId, SubstsRef<'tcx>, hir::Movability),
2063 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2065 /// The `+` operator (addition)
2067 /// The `-` operator (subtraction)
2069 /// The `*` operator (multiplication)
2071 /// The `/` operator (division)
2073 /// The `%` operator (modulus)
2075 /// The `^` operator (bitwise xor)
2077 /// The `&` operator (bitwise and)
2079 /// The `|` operator (bitwise or)
2081 /// The `<<` operator (shift left)
2083 /// The `>>` operator (shift right)
2085 /// The `==` operator (equality)
2087 /// The `<` operator (less than)
2089 /// The `<=` operator (less than or equal to)
2091 /// The `!=` operator (not equal to)
2093 /// The `>=` operator (greater than or equal to)
2095 /// The `>` operator (greater than)
2097 /// The `ptr.offset` operator
2102 pub fn is_checkable(self) -> bool {
2105 Add | Sub | Mul | Shl | Shr => true,
2111 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2113 /// Returns the size of a value of that type
2115 /// Creates a new uninitialized box for a value of that type
2119 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2121 /// The `!` operator for logical inversion
2123 /// The `-` operator for negation
2127 impl<'tcx> Debug for Rvalue<'tcx> {
2128 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2129 use self::Rvalue::*;
2132 Use(ref place) => write!(fmt, "{:?}", place),
2133 Repeat(ref a, ref b) => write!(fmt, "[{:?}; {:?}]", a, b),
2134 Len(ref a) => write!(fmt, "Len({:?})", a),
2135 Cast(ref kind, ref place, ref ty) => {
2136 write!(fmt, "{:?} as {:?} ({:?})", place, ty, kind)
2138 BinaryOp(ref op, ref a, ref b) => write!(fmt, "{:?}({:?}, {:?})", op, a, b),
2139 CheckedBinaryOp(ref op, ref a, ref b) => {
2140 write!(fmt, "Checked{:?}({:?}, {:?})", op, a, b)
2142 UnaryOp(ref op, ref a) => write!(fmt, "{:?}({:?})", op, a),
2143 Discriminant(ref place) => write!(fmt, "discriminant({:?})", place),
2144 NullaryOp(ref op, ref t) => write!(fmt, "{:?}({:?})", op, t),
2145 Ref(region, borrow_kind, ref place) => {
2146 let kind_str = match borrow_kind {
2147 BorrowKind::Shared => "",
2148 BorrowKind::Shallow => "shallow ",
2149 BorrowKind::Mut { .. } | BorrowKind::Unique => "mut ",
2152 // When printing regions, add trailing space if necessary.
2153 let print_region = ty::tls::with(|tcx| {
2154 tcx.sess.verbose() || tcx.sess.opts.debugging_opts.identify_regions
2156 let region = if print_region {
2157 let mut region = region.to_string();
2158 if region.len() > 0 {
2163 // Do not even print 'static
2166 write!(fmt, "&{}{}{:?}", region, kind_str, place)
2169 AddressOf(mutability, ref place) => {
2170 let kind_str = match mutability {
2171 Mutability::Mut => "mut",
2172 Mutability::Not => "const",
2175 write!(fmt, "&raw {} {:?}", kind_str, place)
2178 Aggregate(ref kind, ref places) => {
2179 fn fmt_tuple(fmt: &mut Formatter<'_>, places: &[Operand<'_>]) -> fmt::Result {
2180 let mut tuple_fmt = fmt.debug_tuple("");
2181 for place in places {
2182 tuple_fmt.field(place);
2188 AggregateKind::Array(_) => write!(fmt, "{:?}", places),
2190 AggregateKind::Tuple => match places.len() {
2191 0 => write!(fmt, "()"),
2192 1 => write!(fmt, "({:?},)", places[0]),
2193 _ => fmt_tuple(fmt, places),
2196 AggregateKind::Adt(adt_def, variant, substs, _user_ty, _) => {
2197 let variant_def = &adt_def.variants[variant];
2200 ty::tls::with(|tcx| {
2201 let substs = tcx.lift(&substs).expect("could not lift for printing");
2202 FmtPrinter::new(tcx, f, Namespace::ValueNS)
2203 .print_def_path(variant_def.def_id, substs)?;
2207 match variant_def.ctor_kind {
2208 CtorKind::Const => Ok(()),
2209 CtorKind::Fn => fmt_tuple(fmt, places),
2210 CtorKind::Fictive => {
2211 let mut struct_fmt = fmt.debug_struct("");
2212 for (field, place) in variant_def.fields.iter().zip(places) {
2213 struct_fmt.field(&field.ident.as_str(), place);
2220 AggregateKind::Closure(def_id, substs) => ty::tls::with(|tcx| {
2221 if let Some(hir_id) = tcx.hir().as_local_hir_id(def_id) {
2222 let name = if tcx.sess.opts.debugging_opts.span_free_formats {
2223 let substs = tcx.lift(&substs).unwrap();
2226 tcx.def_path_str_with_substs(def_id, substs),
2229 format!("[closure@{:?}]", tcx.hir().span(hir_id))
2231 let mut struct_fmt = fmt.debug_struct(&name);
2233 if let Some(upvars) = tcx.upvars(def_id) {
2234 for (&var_id, place) in upvars.keys().zip(places) {
2235 let var_name = tcx.hir().name(var_id);
2236 struct_fmt.field(&var_name.as_str(), place);
2242 write!(fmt, "[closure]")
2246 AggregateKind::Generator(def_id, _, _) => ty::tls::with(|tcx| {
2247 if let Some(hir_id) = tcx.hir().as_local_hir_id(def_id) {
2248 let name = format!("[generator@{:?}]", tcx.hir().span(hir_id));
2249 let mut struct_fmt = fmt.debug_struct(&name);
2251 if let Some(upvars) = tcx.upvars(def_id) {
2252 for (&var_id, place) in upvars.keys().zip(places) {
2253 let var_name = tcx.hir().name(var_id);
2254 struct_fmt.field(&var_name.as_str(), place);
2260 write!(fmt, "[generator]")
2269 ///////////////////////////////////////////////////////////////////////////
2272 /// Two constants are equal if they are the same constant. Note that
2273 /// this does not necessarily mean that they are "==" in Rust -- in
2274 /// particular one must be wary of `NaN`!
2276 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable)]
2277 pub struct Constant<'tcx> {
2280 /// Optional user-given type: for something like
2281 /// `collect::<Vec<_>>`, this would be present and would
2282 /// indicate that `Vec<_>` was explicitly specified.
2284 /// Needed for NLL to impose user-given type constraints.
2285 pub user_ty: Option<UserTypeAnnotationIndex>,
2287 pub literal: &'tcx ty::Const<'tcx>,
2290 impl Constant<'tcx> {
2291 pub fn check_static_ptr(&self, tcx: TyCtxt<'_>) -> Option<DefId> {
2292 match self.literal.val.try_to_scalar() {
2293 Some(Scalar::Ptr(ptr)) => match tcx.alloc_map.lock().get(ptr.alloc_id) {
2294 Some(GlobalAlloc::Static(def_id)) => Some(def_id),
2297 tcx.sess.delay_span_bug(DUMMY_SP, "MIR cannot contain dangling const pointers");
2306 /// A collection of projections into user types.
2308 /// They are projections because a binding can occur a part of a
2309 /// parent pattern that has been ascribed a type.
2311 /// Its a collection because there can be multiple type ascriptions on
2312 /// the path from the root of the pattern down to the binding itself.
2317 /// struct S<'a>((i32, &'a str), String);
2318 /// let S((_, w): (i32, &'static str), _): S = ...;
2319 /// // ------ ^^^^^^^^^^^^^^^^^^^ (1)
2320 /// // --------------------------------- ^ (2)
2323 /// The highlights labelled `(1)` show the subpattern `(_, w)` being
2324 /// ascribed the type `(i32, &'static str)`.
2326 /// The highlights labelled `(2)` show the whole pattern being
2327 /// ascribed the type `S`.
2329 /// In this example, when we descend to `w`, we will have built up the
2330 /// following two projected types:
2332 /// * base: `S`, projection: `(base.0).1`
2333 /// * base: `(i32, &'static str)`, projection: `base.1`
2335 /// The first will lead to the constraint `w: &'1 str` (for some
2336 /// inferred region `'1`). The second will lead to the constraint `w:
2338 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
2339 pub struct UserTypeProjections {
2340 pub(crate) contents: Vec<(UserTypeProjection, Span)>,
2343 impl<'tcx> UserTypeProjections {
2344 pub fn none() -> Self {
2345 UserTypeProjections { contents: vec![] }
2348 pub fn from_projections(projs: impl Iterator<Item = (UserTypeProjection, Span)>) -> Self {
2349 UserTypeProjections { contents: projs.collect() }
2352 pub fn projections_and_spans(
2354 ) -> impl Iterator<Item = &(UserTypeProjection, Span)> + ExactSizeIterator {
2355 self.contents.iter()
2358 pub fn projections(&self) -> impl Iterator<Item = &UserTypeProjection> + ExactSizeIterator {
2359 self.contents.iter().map(|&(ref user_type, _span)| user_type)
2362 pub fn push_projection(mut self, user_ty: &UserTypeProjection, span: Span) -> Self {
2363 self.contents.push((user_ty.clone(), span));
2369 mut f: impl FnMut(UserTypeProjection) -> UserTypeProjection,
2371 self.contents = self.contents.drain(..).map(|(proj, span)| (f(proj), span)).collect();
2375 pub fn index(self) -> Self {
2376 self.map_projections(|pat_ty_proj| pat_ty_proj.index())
2379 pub fn subslice(self, from: u32, to: u32) -> Self {
2380 self.map_projections(|pat_ty_proj| pat_ty_proj.subslice(from, to))
2383 pub fn deref(self) -> Self {
2384 self.map_projections(|pat_ty_proj| pat_ty_proj.deref())
2387 pub fn leaf(self, field: Field) -> Self {
2388 self.map_projections(|pat_ty_proj| pat_ty_proj.leaf(field))
2391 pub fn variant(self, adt_def: &'tcx AdtDef, variant_index: VariantIdx, field: Field) -> Self {
2392 self.map_projections(|pat_ty_proj| pat_ty_proj.variant(adt_def, variant_index, field))
2396 /// Encodes the effect of a user-supplied type annotation on the
2397 /// subcomponents of a pattern. The effect is determined by applying the
2398 /// given list of proejctions to some underlying base type. Often,
2399 /// the projection element list `projs` is empty, in which case this
2400 /// directly encodes a type in `base`. But in the case of complex patterns with
2401 /// subpatterns and bindings, we want to apply only a *part* of the type to a variable,
2402 /// in which case the `projs` vector is used.
2406 /// * `let x: T = ...` -- here, the `projs` vector is empty.
2408 /// * `let (x, _): T = ...` -- here, the `projs` vector would contain
2409 /// `field[0]` (aka `.0`), indicating that the type of `s` is
2410 /// determined by finding the type of the `.0` field from `T`.
2411 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable, PartialEq)]
2412 pub struct UserTypeProjection {
2413 pub base: UserTypeAnnotationIndex,
2414 pub projs: Vec<ProjectionKind>,
2417 impl Copy for ProjectionKind {}
2419 impl UserTypeProjection {
2420 pub(crate) fn index(mut self) -> Self {
2421 self.projs.push(ProjectionElem::Index(()));
2425 pub(crate) fn subslice(mut self, from: u32, to: u32) -> Self {
2426 self.projs.push(ProjectionElem::Subslice { from, to, from_end: true });
2430 pub(crate) fn deref(mut self) -> Self {
2431 self.projs.push(ProjectionElem::Deref);
2435 pub(crate) fn leaf(mut self, field: Field) -> Self {
2436 self.projs.push(ProjectionElem::Field(field, ()));
2440 pub(crate) fn variant(
2442 adt_def: &'tcx AdtDef,
2443 variant_index: VariantIdx,
2446 self.projs.push(ProjectionElem::Downcast(
2447 Some(adt_def.variants[variant_index].ident.name),
2450 self.projs.push(ProjectionElem::Field(field, ()));
2455 CloneTypeFoldableAndLiftImpls! { ProjectionKind, }
2457 impl<'tcx> TypeFoldable<'tcx> for UserTypeProjection {
2458 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
2459 use crate::mir::ProjectionElem::*;
2461 let base = self.base.fold_with(folder);
2462 let projs: Vec<_> = self
2465 .map(|elem| match elem {
2467 Field(f, ()) => Field(f.clone(), ()),
2468 Index(()) => Index(()),
2469 elem => elem.clone(),
2473 UserTypeProjection { base, projs }
2476 fn super_visit_with<Vs: TypeVisitor<'tcx>>(&self, visitor: &mut Vs) -> bool {
2477 self.base.visit_with(visitor)
2478 // Note: there's nothing in `self.proj` to visit.
2482 rustc_index::newtype_index! {
2483 pub struct Promoted {
2485 DEBUG_FORMAT = "promoted[{}]"
2489 impl<'tcx> Debug for Constant<'tcx> {
2490 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2491 write!(fmt, "{}", self)
2495 impl<'tcx> Display for Constant<'tcx> {
2496 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2497 write!(fmt, "const ")?;
2498 // FIXME make the default pretty printing of raw pointers more detailed. Here we output the
2499 // debug representation of raw pointers, so that the raw pointers in the mir dump output are
2500 // detailed and just not '{pointer}'.
2501 if let ty::RawPtr(_) = self.literal.ty.kind {
2502 write!(fmt, "{:?} : {}", self.literal.val, self.literal.ty)
2504 write!(fmt, "{}", self.literal)
2509 impl<'tcx> graph::DirectedGraph for Body<'tcx> {
2510 type Node = BasicBlock;
2513 impl<'tcx> graph::WithNumNodes for Body<'tcx> {
2514 fn num_nodes(&self) -> usize {
2515 self.basic_blocks.len()
2519 impl<'tcx> graph::WithStartNode for Body<'tcx> {
2520 fn start_node(&self) -> Self::Node {
2525 impl<'tcx> graph::WithSuccessors for Body<'tcx> {
2526 fn successors(&self, node: Self::Node) -> <Self as GraphSuccessors<'_>>::Iter {
2527 self.basic_blocks[node].terminator().successors().cloned()
2531 impl<'a, 'b> graph::GraphSuccessors<'b> for Body<'a> {
2532 type Item = BasicBlock;
2533 type Iter = iter::Cloned<Successors<'b>>;
2536 #[derive(Copy, Clone, PartialEq, Eq, Hash, Ord, PartialOrd, HashStable)]
2537 pub struct Location {
2538 /// The block that the location is within.
2539 pub block: BasicBlock,
2541 /// The location is the position of the start of the statement; or, if
2542 /// `statement_index` equals the number of statements, then the start of the
2544 pub statement_index: usize,
2547 impl fmt::Debug for Location {
2548 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2549 write!(fmt, "{:?}[{}]", self.block, self.statement_index)
2554 pub const START: Location = Location { block: START_BLOCK, statement_index: 0 };
2556 /// Returns the location immediately after this one within the enclosing block.
2558 /// Note that if this location represents a terminator, then the
2559 /// resulting location would be out of bounds and invalid.
2560 pub fn successor_within_block(&self) -> Location {
2561 Location { block: self.block, statement_index: self.statement_index + 1 }
2564 /// Returns `true` if `other` is earlier in the control flow graph than `self`.
2565 pub fn is_predecessor_of<'tcx>(
2568 body: ReadOnlyBodyAndCache<'_, 'tcx>,
2570 // If we are in the same block as the other location and are an earlier statement
2571 // then we are a predecessor of `other`.
2572 if self.block == other.block && self.statement_index < other.statement_index {
2576 // If we're in another block, then we want to check that block is a predecessor of `other`.
2577 let mut queue: Vec<BasicBlock> = body.predecessors_for(other.block).to_vec();
2578 let mut visited = FxHashSet::default();
2580 while let Some(block) = queue.pop() {
2581 // If we haven't visited this block before, then make sure we visit it's predecessors.
2582 if visited.insert(block) {
2583 queue.extend(body.predecessors_for(block).iter().cloned());
2588 // If we found the block that `self` is in, then we are a predecessor of `other` (since
2589 // we found that block by looking at the predecessors of `other`).
2590 if self.block == block {
2598 pub fn dominates(&self, other: Location, dominators: &Dominators<BasicBlock>) -> bool {
2599 if self.block == other.block {
2600 self.statement_index <= other.statement_index
2602 dominators.is_dominated_by(other.block, self.block)
2608 * `TypeFoldable` implementations for MIR types
2611 CloneTypeFoldableAndLiftImpls! {
2619 SourceScopeLocalData,
2620 UserTypeAnnotationIndex,
2623 impl<'tcx> TypeFoldable<'tcx> for Terminator<'tcx> {
2624 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
2625 use crate::mir::TerminatorKind::*;
2627 let kind = match self.kind {
2628 Goto { target } => Goto { target },
2629 SwitchInt { ref discr, switch_ty, ref values, ref targets } => SwitchInt {
2630 discr: discr.fold_with(folder),
2631 switch_ty: switch_ty.fold_with(folder),
2632 values: values.clone(),
2633 targets: targets.clone(),
2635 Drop { ref location, target, unwind } => {
2636 Drop { location: location.fold_with(folder), target, unwind }
2638 DropAndReplace { ref location, ref value, target, unwind } => DropAndReplace {
2639 location: location.fold_with(folder),
2640 value: value.fold_with(folder),
2644 Yield { ref value, resume, drop } => {
2645 Yield { value: value.fold_with(folder), resume: resume, drop: drop }
2647 Call { ref func, ref args, ref destination, cleanup, from_hir_call } => {
2649 destination.as_ref().map(|&(ref loc, dest)| (loc.fold_with(folder), dest));
2652 func: func.fold_with(folder),
2653 args: args.fold_with(folder),
2659 Assert { ref cond, expected, ref msg, target, cleanup } => {
2661 let msg = match msg {
2662 BoundsCheck { ref len, ref index } => {
2663 BoundsCheck { len: len.fold_with(folder), index: index.fold_with(folder) }
2670 | ResumedAfterReturn(_)
2671 | ResumedAfterPanic(_) => msg.clone(),
2673 Assert { cond: cond.fold_with(folder), expected, msg, target, cleanup }
2675 GeneratorDrop => GeneratorDrop,
2679 Unreachable => Unreachable,
2680 FalseEdges { real_target, imaginary_target } => {
2681 FalseEdges { real_target, imaginary_target }
2683 FalseUnwind { real_target, unwind } => FalseUnwind { real_target, unwind },
2685 Terminator { source_info: self.source_info, kind }
2688 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
2689 use crate::mir::TerminatorKind::*;
2692 SwitchInt { ref discr, switch_ty, .. } => {
2693 discr.visit_with(visitor) || switch_ty.visit_with(visitor)
2695 Drop { ref location, .. } => location.visit_with(visitor),
2696 DropAndReplace { ref location, ref value, .. } => {
2697 location.visit_with(visitor) || value.visit_with(visitor)
2699 Yield { ref value, .. } => value.visit_with(visitor),
2700 Call { ref func, ref args, ref destination, .. } => {
2701 let dest = if let Some((ref loc, _)) = *destination {
2702 loc.visit_with(visitor)
2706 dest || func.visit_with(visitor) || args.visit_with(visitor)
2708 Assert { ref cond, ref msg, .. } => {
2709 if cond.visit_with(visitor) {
2712 BoundsCheck { ref len, ref index } => {
2713 len.visit_with(visitor) || index.visit_with(visitor)
2720 | ResumedAfterReturn(_)
2721 | ResumedAfterPanic(_) => false,
2734 | FalseUnwind { .. } => false,
2739 impl<'tcx> TypeFoldable<'tcx> for GeneratorKind {
2740 fn super_fold_with<F: TypeFolder<'tcx>>(&self, _: &mut F) -> Self {
2744 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, _: &mut V) -> bool {
2749 impl<'tcx> TypeFoldable<'tcx> for Place<'tcx> {
2750 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
2751 Place { local: self.local.fold_with(folder), projection: self.projection.fold_with(folder) }
2754 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
2755 self.local.visit_with(visitor) || self.projection.visit_with(visitor)
2759 impl<'tcx> TypeFoldable<'tcx> for &'tcx ty::List<PlaceElem<'tcx>> {
2760 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
2761 let v = self.iter().map(|t| t.fold_with(folder)).collect::<Vec<_>>();
2762 folder.tcx().intern_place_elems(&v)
2765 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
2766 self.iter().any(|t| t.visit_with(visitor))
2770 impl<'tcx> TypeFoldable<'tcx> for Rvalue<'tcx> {
2771 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
2772 use crate::mir::Rvalue::*;
2774 Use(ref op) => Use(op.fold_with(folder)),
2775 Repeat(ref op, len) => Repeat(op.fold_with(folder), len),
2776 Ref(region, bk, ref place) => {
2777 Ref(region.fold_with(folder), bk, place.fold_with(folder))
2779 AddressOf(mutability, ref place) => AddressOf(mutability, place.fold_with(folder)),
2780 Len(ref place) => Len(place.fold_with(folder)),
2781 Cast(kind, ref op, ty) => Cast(kind, op.fold_with(folder), ty.fold_with(folder)),
2782 BinaryOp(op, ref rhs, ref lhs) => {
2783 BinaryOp(op, rhs.fold_with(folder), lhs.fold_with(folder))
2785 CheckedBinaryOp(op, ref rhs, ref lhs) => {
2786 CheckedBinaryOp(op, rhs.fold_with(folder), lhs.fold_with(folder))
2788 UnaryOp(op, ref val) => UnaryOp(op, val.fold_with(folder)),
2789 Discriminant(ref place) => Discriminant(place.fold_with(folder)),
2790 NullaryOp(op, ty) => NullaryOp(op, ty.fold_with(folder)),
2791 Aggregate(ref kind, ref fields) => {
2792 let kind = box match **kind {
2793 AggregateKind::Array(ty) => AggregateKind::Array(ty.fold_with(folder)),
2794 AggregateKind::Tuple => AggregateKind::Tuple,
2795 AggregateKind::Adt(def, v, substs, user_ty, n) => AggregateKind::Adt(
2798 substs.fold_with(folder),
2799 user_ty.fold_with(folder),
2802 AggregateKind::Closure(id, substs) => {
2803 AggregateKind::Closure(id, substs.fold_with(folder))
2805 AggregateKind::Generator(id, substs, movablity) => {
2806 AggregateKind::Generator(id, substs.fold_with(folder), movablity)
2809 Aggregate(kind, fields.fold_with(folder))
2814 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
2815 use crate::mir::Rvalue::*;
2817 Use(ref op) => op.visit_with(visitor),
2818 Repeat(ref op, _) => op.visit_with(visitor),
2819 Ref(region, _, ref place) => region.visit_with(visitor) || place.visit_with(visitor),
2820 AddressOf(_, ref place) => place.visit_with(visitor),
2821 Len(ref place) => place.visit_with(visitor),
2822 Cast(_, ref op, ty) => op.visit_with(visitor) || ty.visit_with(visitor),
2823 BinaryOp(_, ref rhs, ref lhs) | CheckedBinaryOp(_, ref rhs, ref lhs) => {
2824 rhs.visit_with(visitor) || lhs.visit_with(visitor)
2826 UnaryOp(_, ref val) => val.visit_with(visitor),
2827 Discriminant(ref place) => place.visit_with(visitor),
2828 NullaryOp(_, ty) => ty.visit_with(visitor),
2829 Aggregate(ref kind, ref fields) => {
2831 AggregateKind::Array(ty) => ty.visit_with(visitor),
2832 AggregateKind::Tuple => false,
2833 AggregateKind::Adt(_, _, substs, user_ty, _) => {
2834 substs.visit_with(visitor) || user_ty.visit_with(visitor)
2836 AggregateKind::Closure(_, substs) => substs.visit_with(visitor),
2837 AggregateKind::Generator(_, substs, _) => substs.visit_with(visitor),
2838 }) || fields.visit_with(visitor)
2844 impl<'tcx> TypeFoldable<'tcx> for Operand<'tcx> {
2845 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
2847 Operand::Copy(ref place) => Operand::Copy(place.fold_with(folder)),
2848 Operand::Move(ref place) => Operand::Move(place.fold_with(folder)),
2849 Operand::Constant(ref c) => Operand::Constant(c.fold_with(folder)),
2853 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
2855 Operand::Copy(ref place) | Operand::Move(ref place) => place.visit_with(visitor),
2856 Operand::Constant(ref c) => c.visit_with(visitor),
2861 impl<'tcx> TypeFoldable<'tcx> for PlaceElem<'tcx> {
2862 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
2863 use crate::mir::ProjectionElem::*;
2867 Field(f, ty) => Field(*f, ty.fold_with(folder)),
2868 Index(v) => Index(v.fold_with(folder)),
2869 elem => elem.clone(),
2873 fn super_visit_with<Vs: TypeVisitor<'tcx>>(&self, visitor: &mut Vs) -> bool {
2874 use crate::mir::ProjectionElem::*;
2877 Field(_, ty) => ty.visit_with(visitor),
2878 Index(v) => v.visit_with(visitor),
2884 impl<'tcx> TypeFoldable<'tcx> for Field {
2885 fn super_fold_with<F: TypeFolder<'tcx>>(&self, _: &mut F) -> Self {
2888 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, _: &mut V) -> bool {
2893 impl<'tcx> TypeFoldable<'tcx> for GeneratorSavedLocal {
2894 fn super_fold_with<F: TypeFolder<'tcx>>(&self, _: &mut F) -> Self {
2897 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, _: &mut V) -> bool {
2902 impl<'tcx, R: Idx, C: Idx> TypeFoldable<'tcx> for BitMatrix<R, C> {
2903 fn super_fold_with<F: TypeFolder<'tcx>>(&self, _: &mut F) -> Self {
2906 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, _: &mut V) -> bool {
2911 impl<'tcx> TypeFoldable<'tcx> for Constant<'tcx> {
2912 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
2914 span: self.span.clone(),
2915 user_ty: self.user_ty.fold_with(folder),
2916 literal: self.literal.fold_with(folder),
2919 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
2920 self.literal.visit_with(visitor)