1 //! MIR datatypes and passes. See the [rustc dev guide] for more info.
3 //! [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/mir/index.html
5 use crate::mir::interpret::{GlobalAlloc, Scalar};
6 use crate::mir::visit::MirVisitable;
7 use crate::ty::adjustment::PointerCast;
8 use crate::ty::fold::{TypeFoldable, TypeFolder, TypeVisitor};
9 use crate::ty::print::{FmtPrinter, Printer};
10 use crate::ty::subst::{Subst, SubstsRef};
12 self, AdtDef, CanonicalUserTypeAnnotations, List, Region, Ty, TyCtxt, UserTypeAnnotationIndex,
15 use rustc_hir::def::{CtorKind, Namespace};
16 use rustc_hir::def_id::DefId;
17 use rustc_hir::{self, GeneratorKind};
18 use rustc_target::abi::VariantIdx;
20 use polonius_engine::Atom;
21 pub use rustc_ast::ast::Mutability;
22 use rustc_ast::ast::Name;
23 use rustc_data_structures::fx::FxHashSet;
24 use rustc_data_structures::graph::dominators::{dominators, Dominators};
25 use rustc_data_structures::graph::{self, GraphSuccessors};
26 use rustc_data_structures::sync::MappedLockGuard;
27 use rustc_index::bit_set::BitMatrix;
28 use rustc_index::vec::{Idx, IndexVec};
29 use rustc_macros::HashStable;
30 use rustc_serialize::{Decodable, Encodable};
31 use rustc_span::symbol::Symbol;
32 use rustc_span::{Span, DUMMY_SP};
33 use smallvec::SmallVec;
35 use std::fmt::{self, Debug, Display, Formatter, Write};
36 use std::ops::{Index, IndexMut};
38 use std::{iter, mem, option};
40 use self::predecessors::{PredecessorCache, Predecessors};
41 pub use self::query::*;
53 type LocalDecls<'tcx> = IndexVec<Local, LocalDecl<'tcx>>;
55 pub trait HasLocalDecls<'tcx> {
56 fn local_decls(&self) -> &LocalDecls<'tcx>;
59 impl<'tcx> HasLocalDecls<'tcx> for LocalDecls<'tcx> {
60 fn local_decls(&self) -> &LocalDecls<'tcx> {
65 impl<'tcx> HasLocalDecls<'tcx> for Body<'tcx> {
66 fn local_decls(&self) -> &LocalDecls<'tcx> {
71 /// The various "big phases" that MIR goes through.
73 /// Warning: ordering of variants is significant.
74 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, PartialEq, Eq, PartialOrd, Ord)]
84 /// Gets the index of the current MirPhase within the set of all `MirPhase`s.
85 pub fn phase_index(&self) -> usize {
90 /// The lowered representation of a single function.
91 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable, TypeFoldable)]
92 pub struct Body<'tcx> {
93 /// A list of basic blocks. References to basic block use a newtyped index type `BasicBlock`
94 /// that indexes into this vector.
95 basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
97 /// Records how far through the "desugaring and optimization" process this particular
98 /// MIR has traversed. This is particularly useful when inlining, since in that context
99 /// we instantiate the promoted constants and add them to our promoted vector -- but those
100 /// promoted items have already been optimized, whereas ours have not. This field allows
101 /// us to see the difference and forego optimization on the inlined promoted items.
104 /// A list of source scopes; these are referenced by statements
105 /// and used for debuginfo. Indexed by a `SourceScope`.
106 pub source_scopes: IndexVec<SourceScope, SourceScopeData>,
108 /// The yield type of the function, if it is a generator.
109 pub yield_ty: Option<Ty<'tcx>>,
111 /// Generator drop glue.
112 pub generator_drop: Option<Box<Body<'tcx>>>,
114 /// The layout of a generator. Produced by the state transformation.
115 pub generator_layout: Option<GeneratorLayout<'tcx>>,
117 /// If this is a generator then record the type of source expression that caused this generator
119 pub generator_kind: Option<GeneratorKind>,
121 /// Declarations of locals.
123 /// The first local is the return value pointer, followed by `arg_count`
124 /// locals for the function arguments, followed by any user-declared
125 /// variables and temporaries.
126 pub local_decls: LocalDecls<'tcx>,
128 /// User type annotations.
129 pub user_type_annotations: CanonicalUserTypeAnnotations<'tcx>,
131 /// The number of arguments this function takes.
133 /// Starting at local 1, `arg_count` locals will be provided by the caller
134 /// and can be assumed to be initialized.
136 /// If this MIR was built for a constant, this will be 0.
137 pub arg_count: usize,
139 /// Mark an argument local (which must be a tuple) as getting passed as
140 /// its individual components at the LLVM level.
142 /// This is used for the "rust-call" ABI.
143 pub spread_arg: Option<Local>,
145 /// Debug information pertaining to user variables, including captures.
146 pub var_debug_info: Vec<VarDebugInfo<'tcx>>,
148 /// Mark this MIR of a const context other than const functions as having converted a `&&` or
149 /// `||` expression into `&` or `|` respectively. This is problematic because if we ever stop
150 /// this conversion from happening and use short circuiting, we will cause the following code
151 /// to change the value of `x`: `let mut x = 42; false && { x = 55; true };`
153 /// List of places where control flow was destroyed. Used for error reporting.
154 pub control_flow_destroyed: Vec<(Span, String)>,
156 /// A span representing this MIR, for error reporting.
159 /// The user may be writing e.g. &[(SOME_CELL, 42)][i].1 and this would get promoted, because
160 /// we'd statically know that no thing with interior mutability will ever be available to the
161 /// user without some serious unsafe code. Now this means that our promoted is actually
162 /// &[(SOME_CELL, 42)] and the MIR using it will do the &promoted[i].1 projection because the
163 /// index may be a runtime value. Such a promoted value is illegal because it has reachable
164 /// interior mutability. This flag just makes this situation very obvious where the previous
165 /// implementation without the flag hid this situation silently.
166 /// FIXME(oli-obk): rewrite the promoted during promotion to eliminate the cell components.
167 pub ignore_interior_mut_in_const_validation: bool,
169 pub predecessor_cache: PredecessorCache,
172 impl<'tcx> Body<'tcx> {
174 basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
175 source_scopes: IndexVec<SourceScope, SourceScopeData>,
176 local_decls: LocalDecls<'tcx>,
177 user_type_annotations: CanonicalUserTypeAnnotations<'tcx>,
179 var_debug_info: Vec<VarDebugInfo<'tcx>>,
181 control_flow_destroyed: Vec<(Span, String)>,
182 generator_kind: Option<GeneratorKind>,
184 // We need `arg_count` locals, and one for the return place.
186 local_decls.len() > arg_count,
187 "expected at least {} locals, got {}",
193 phase: MirPhase::Build,
197 generator_drop: None,
198 generator_layout: None,
201 user_type_annotations,
206 ignore_interior_mut_in_const_validation: false,
207 control_flow_destroyed,
208 predecessor_cache: PredecessorCache::new(),
212 /// Returns a partially initialized MIR body containing only a list of basic blocks.
214 /// The returned MIR contains no `LocalDecl`s (even for the return place) or source scopes. It
215 /// is only useful for testing but cannot be `#[cfg(test)]` because it is used in a different
217 pub fn new_cfg_only(basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>) -> Self {
219 phase: MirPhase::Build,
221 source_scopes: IndexVec::new(),
223 generator_drop: None,
224 generator_layout: None,
225 local_decls: IndexVec::new(),
226 user_type_annotations: IndexVec::new(),
230 control_flow_destroyed: Vec::new(),
231 generator_kind: None,
232 var_debug_info: Vec::new(),
233 ignore_interior_mut_in_const_validation: false,
234 predecessor_cache: PredecessorCache::new(),
239 pub fn basic_blocks(&self) -> &IndexVec<BasicBlock, BasicBlockData<'tcx>> {
244 pub fn basic_blocks_mut(&mut self) -> &mut IndexVec<BasicBlock, BasicBlockData<'tcx>> {
245 // Because the user could mutate basic block terminators via this reference, we need to
246 // invalidate the predecessor cache.
248 // FIXME: Use a finer-grained API for this, so only transformations that alter terminators
249 // invalidate the predecessor cache.
250 self.predecessor_cache.invalidate();
251 &mut self.basic_blocks
255 pub fn basic_blocks_and_local_decls_mut(
257 ) -> (&mut IndexVec<BasicBlock, BasicBlockData<'tcx>>, &mut LocalDecls<'tcx>) {
258 self.predecessor_cache.invalidate();
259 (&mut self.basic_blocks, &mut self.local_decls)
262 /// Returns `true` if a cycle exists in the control-flow graph that is reachable from the
264 pub fn is_cfg_cyclic(&self) -> bool {
265 graph::is_cyclic(self)
269 pub fn local_kind(&self, local: Local) -> LocalKind {
270 let index = local.as_usize();
273 self.local_decls[local].mutability == Mutability::Mut,
274 "return place should be mutable"
277 LocalKind::ReturnPointer
278 } else if index < self.arg_count + 1 {
280 } else if self.local_decls[local].is_user_variable() {
287 /// Returns an iterator over all temporaries.
289 pub fn temps_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
290 (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
291 let local = Local::new(index);
292 if self.local_decls[local].is_user_variable() { None } else { Some(local) }
296 /// Returns an iterator over all user-declared locals.
298 pub fn vars_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
299 (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
300 let local = Local::new(index);
301 self.local_decls[local].is_user_variable().then_some(local)
305 /// Returns an iterator over all user-declared mutable locals.
307 pub fn mut_vars_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
308 (self.arg_count + 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() && decl.mutability == Mutability::Mut {
319 /// Returns an iterator over all user-declared mutable arguments and locals.
321 pub fn mut_vars_and_args_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
322 (1..self.local_decls.len()).filter_map(move |index| {
323 let local = Local::new(index);
324 let decl = &self.local_decls[local];
325 if (decl.is_user_variable() || index < self.arg_count + 1)
326 && decl.mutability == Mutability::Mut
335 /// Returns an iterator over all function arguments.
337 pub fn args_iter(&self) -> impl Iterator<Item = Local> + ExactSizeIterator {
338 let arg_count = self.arg_count;
339 (1..arg_count + 1).map(Local::new)
342 /// Returns an iterator over all user-defined variables and compiler-generated temporaries (all
343 /// locals that are neither arguments nor the return place).
345 pub fn vars_and_temps_iter(&self) -> impl Iterator<Item = Local> + ExactSizeIterator {
346 let arg_count = self.arg_count;
347 let local_count = self.local_decls.len();
348 (arg_count + 1..local_count).map(Local::new)
351 /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
352 /// invalidating statement indices in `Location`s.
353 pub fn make_statement_nop(&mut self, location: Location) {
354 let block = &mut self.basic_blocks[location.block];
355 debug_assert!(location.statement_index < block.statements.len());
356 block.statements[location.statement_index].make_nop()
359 /// Returns the source info associated with `location`.
360 pub fn source_info(&self, location: Location) -> &SourceInfo {
361 let block = &self[location.block];
362 let stmts = &block.statements;
363 let idx = location.statement_index;
364 if idx < stmts.len() {
365 &stmts[idx].source_info
367 assert_eq!(idx, stmts.len());
368 &block.terminator().source_info
372 /// Checks if `sub` is a sub scope of `sup`
373 pub fn is_sub_scope(&self, mut sub: SourceScope, sup: SourceScope) -> bool {
375 match self.source_scopes[sub].parent_scope {
376 None => return false,
383 /// Returns the return type; it always return first element from `local_decls` array.
385 pub fn return_ty(&self) -> Ty<'tcx> {
386 self.local_decls[RETURN_PLACE].ty
389 /// Gets the location of the terminator for the given block.
391 pub fn terminator_loc(&self, bb: BasicBlock) -> Location {
392 Location { block: bb, statement_index: self[bb].statements.len() }
396 pub fn predecessors_for(
399 ) -> impl std::ops::Deref<Target = SmallVec<[BasicBlock; 4]>> + '_ {
400 let predecessors = self.predecessor_cache.compute(&self.basic_blocks);
401 MappedLockGuard::map(predecessors, |preds| &mut preds[bb])
405 pub fn predecessors(&self) -> impl std::ops::Deref<Target = Predecessors> + '_ {
406 self.predecessor_cache.compute(&self.basic_blocks)
410 pub fn dominators(&self) -> Dominators<BasicBlock> {
415 #[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
418 /// Unsafe because of a PushUnsafeBlock
420 /// Unsafe because of an unsafe fn
422 /// Unsafe because of an `unsafe` block
423 ExplicitUnsafe(hir::HirId),
426 impl<'tcx> Index<BasicBlock> for Body<'tcx> {
427 type Output = BasicBlockData<'tcx>;
430 fn index(&self, index: BasicBlock) -> &BasicBlockData<'tcx> {
431 &self.basic_blocks()[index]
435 impl<'tcx> IndexMut<BasicBlock> for Body<'tcx> {
437 fn index_mut(&mut self, index: BasicBlock) -> &mut BasicBlockData<'tcx> {
438 &mut self.basic_blocks_mut()[index]
442 #[derive(Copy, Clone, Debug, HashStable, TypeFoldable)]
443 pub enum ClearCrossCrate<T> {
448 impl<T> ClearCrossCrate<T> {
449 pub fn as_ref(&self) -> ClearCrossCrate<&T> {
451 ClearCrossCrate::Clear => ClearCrossCrate::Clear,
452 ClearCrossCrate::Set(v) => ClearCrossCrate::Set(v),
456 pub fn assert_crate_local(self) -> T {
458 ClearCrossCrate::Clear => bug!("unwrapping cross-crate data"),
459 ClearCrossCrate::Set(v) => v,
464 impl<T: Encodable> rustc_serialize::UseSpecializedEncodable for ClearCrossCrate<T> {}
465 impl<T: Decodable> rustc_serialize::UseSpecializedDecodable for ClearCrossCrate<T> {}
467 /// Grouped information about the source code origin of a MIR entity.
468 /// Intended to be inspected by diagnostics and debuginfo.
469 /// Most passes can work with it as a whole, within a single function.
470 // The unofficial Cranelift backend, at least as of #65828, needs `SourceInfo` to implement `Eq` and
471 // `Hash`. Please ping @bjorn3 if removing them.
472 #[derive(Copy, Clone, Debug, Eq, PartialEq, RustcEncodable, RustcDecodable, Hash, HashStable)]
473 pub struct SourceInfo {
474 /// The source span for the AST pertaining to this MIR entity.
477 /// The source scope, keeping track of which bindings can be
478 /// seen by debuginfo, active lint levels, `unsafe {...}`, etc.
479 pub scope: SourceScope,
482 ///////////////////////////////////////////////////////////////////////////
485 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable)]
486 #[derive(HashStable)]
487 pub enum BorrowKind {
488 /// Data must be immutable and is aliasable.
491 /// The immediately borrowed place must be immutable, but projections from
492 /// it don't need to be. For example, a shallow borrow of `a.b` doesn't
493 /// conflict with a mutable borrow of `a.b.c`.
495 /// This is used when lowering matches: when matching on a place we want to
496 /// ensure that place have the same value from the start of the match until
497 /// an arm is selected. This prevents this code from compiling:
499 /// let mut x = &Some(0);
502 /// Some(_) if { x = &None; false } => (),
506 /// This can't be a shared borrow because mutably borrowing (*x as Some).0
507 /// should not prevent `if let None = x { ... }`, for example, because the
508 /// mutating `(*x as Some).0` can't affect the discriminant of `x`.
509 /// We can also report errors with this kind of borrow differently.
512 /// Data must be immutable but not aliasable. This kind of borrow
513 /// cannot currently be expressed by the user and is used only in
514 /// implicit closure bindings. It is needed when the closure is
515 /// borrowing or mutating a mutable referent, e.g.:
517 /// let x: &mut isize = ...;
518 /// let y = || *x += 5;
520 /// If we were to try to translate this closure into a more explicit
521 /// form, we'd encounter an error with the code as written:
523 /// struct Env { x: & &mut isize }
524 /// let x: &mut isize = ...;
525 /// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn
526 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
528 /// This is then illegal because you cannot mutate an `&mut` found
529 /// in an aliasable location. To solve, you'd have to translate with
530 /// an `&mut` borrow:
532 /// struct Env { x: & &mut isize }
533 /// let x: &mut isize = ...;
534 /// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
535 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
537 /// Now the assignment to `**env.x` is legal, but creating a
538 /// mutable pointer to `x` is not because `x` is not mutable. We
539 /// could fix this by declaring `x` as `let mut x`. This is ok in
540 /// user code, if awkward, but extra weird for closures, since the
541 /// borrow is hidden.
543 /// So we introduce a "unique imm" borrow -- the referent is
544 /// immutable, but not aliasable. This solves the problem. For
545 /// simplicity, we don't give users the way to express this
546 /// borrow, it's just used when translating closures.
549 /// Data is mutable and not aliasable.
551 /// `true` if this borrow arose from method-call auto-ref
552 /// (i.e., `adjustment::Adjust::Borrow`).
553 allow_two_phase_borrow: bool,
558 pub fn allows_two_phase_borrow(&self) -> bool {
560 BorrowKind::Shared | BorrowKind::Shallow | BorrowKind::Unique => false,
561 BorrowKind::Mut { allow_two_phase_borrow } => allow_two_phase_borrow,
566 ///////////////////////////////////////////////////////////////////////////
567 // Variables and temps
569 rustc_index::newtype_index! {
572 DEBUG_FORMAT = "_{}",
573 const RETURN_PLACE = 0,
577 impl Atom for Local {
578 fn index(self) -> usize {
583 /// Classifies locals into categories. See `Body::local_kind`.
584 #[derive(PartialEq, Eq, Debug, HashStable)]
586 /// User-declared variable binding.
588 /// Compiler-introduced temporary.
590 /// Function argument.
592 /// Location of function's return value.
596 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
597 pub struct VarBindingForm<'tcx> {
598 /// Is variable bound via `x`, `mut x`, `ref x`, or `ref mut x`?
599 pub binding_mode: ty::BindingMode,
600 /// If an explicit type was provided for this variable binding,
601 /// this holds the source Span of that type.
603 /// NOTE: if you want to change this to a `HirId`, be wary that
604 /// doing so breaks incremental compilation (as of this writing),
605 /// while a `Span` does not cause our tests to fail.
606 pub opt_ty_info: Option<Span>,
607 /// Place of the RHS of the =, or the subject of the `match` where this
608 /// variable is initialized. None in the case of `let PATTERN;`.
609 /// Some((None, ..)) in the case of and `let [mut] x = ...` because
610 /// (a) the right-hand side isn't evaluated as a place expression.
611 /// (b) it gives a way to separate this case from the remaining cases
613 pub opt_match_place: Option<(Option<Place<'tcx>>, Span)>,
614 /// The span of the pattern in which this variable was bound.
618 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
619 pub enum BindingForm<'tcx> {
620 /// This is a binding for a non-`self` binding, or a `self` that has an explicit type.
621 Var(VarBindingForm<'tcx>),
622 /// Binding for a `self`/`&self`/`&mut self` binding where the type is implicit.
623 ImplicitSelf(ImplicitSelfKind),
624 /// Reference used in a guard expression to ensure immutability.
628 /// Represents what type of implicit self a function has, if any.
629 #[derive(Clone, Copy, PartialEq, Debug, RustcEncodable, RustcDecodable, HashStable)]
630 pub enum ImplicitSelfKind {
631 /// Represents a `fn x(self);`.
633 /// Represents a `fn x(mut self);`.
635 /// Represents a `fn x(&self);`.
637 /// Represents a `fn x(&mut self);`.
639 /// Represents when a function does not have a self argument or
640 /// when a function has a `self: X` argument.
644 CloneTypeFoldableAndLiftImpls! { BindingForm<'tcx>, }
646 mod binding_form_impl {
647 use crate::ich::StableHashingContext;
648 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
650 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for super::BindingForm<'tcx> {
651 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
652 use super::BindingForm::*;
653 ::std::mem::discriminant(self).hash_stable(hcx, hasher);
656 Var(binding) => binding.hash_stable(hcx, hasher),
657 ImplicitSelf(kind) => kind.hash_stable(hcx, hasher),
664 /// `BlockTailInfo` is attached to the `LocalDecl` for temporaries
665 /// created during evaluation of expressions in a block tail
666 /// expression; that is, a block like `{ STMT_1; STMT_2; EXPR }`.
668 /// It is used to improve diagnostics when such temporaries are
669 /// involved in borrow_check errors, e.g., explanations of where the
670 /// temporaries come from, when their destructors are run, and/or how
671 /// one might revise the code to satisfy the borrow checker's rules.
672 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
673 pub struct BlockTailInfo {
674 /// If `true`, then the value resulting from evaluating this tail
675 /// expression is ignored by the block's expression context.
677 /// Examples include `{ ...; tail };` and `let _ = { ...; tail };`
678 /// but not e.g., `let _x = { ...; tail };`
679 pub tail_result_is_ignored: bool,
684 /// This can be a binding declared by the user, a temporary inserted by the compiler, a function
685 /// argument, or the return place.
686 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
687 pub struct LocalDecl<'tcx> {
688 /// Whether this is a mutable minding (i.e., `let x` or `let mut x`).
690 /// Temporaries and the return place are always mutable.
691 pub mutability: Mutability,
693 // FIXME(matthewjasper) Don't store in this in `Body`
694 pub local_info: LocalInfo<'tcx>,
696 /// `true` if this is an internal local.
698 /// These locals are not based on types in the source code and are only used
699 /// for a few desugarings at the moment.
701 /// The generator transformation will sanity check the locals which are live
702 /// across a suspension point against the type components of the generator
703 /// which type checking knows are live across a suspension point. We need to
704 /// flag drop flags to avoid triggering this check as they are introduced
707 /// Unsafety checking will also ignore dereferences of these locals,
708 /// so they can be used for raw pointers only used in a desugaring.
710 /// This should be sound because the drop flags are fully algebraic, and
711 /// therefore don't affect the OIBIT or outlives properties of the
715 /// If this local is a temporary and `is_block_tail` is `Some`,
716 /// then it is a temporary created for evaluation of some
717 /// subexpression of some block's tail expression (with no
718 /// intervening statement context).
719 // FIXME(matthewjasper) Don't store in this in `Body`
720 pub is_block_tail: Option<BlockTailInfo>,
722 /// The type of this local.
725 /// If the user manually ascribed a type to this variable,
726 /// e.g., via `let x: T`, then we carry that type here. The MIR
727 /// borrow checker needs this information since it can affect
728 /// region inference.
729 // FIXME(matthewjasper) Don't store in this in `Body`
730 pub user_ty: UserTypeProjections,
732 /// The *syntactic* (i.e., not visibility) source scope the local is defined
733 /// in. If the local was defined in a let-statement, this
734 /// is *within* the let-statement, rather than outside
737 /// This is needed because the visibility source scope of locals within
738 /// a let-statement is weird.
740 /// The reason is that we want the local to be *within* the let-statement
741 /// for lint purposes, but we want the local to be *after* the let-statement
742 /// for names-in-scope purposes.
744 /// That's it, if we have a let-statement like the one in this
748 /// fn foo(x: &str) {
749 /// #[allow(unused_mut)]
750 /// let mut x: u32 = { // <- one unused mut
751 /// let mut y: u32 = x.parse().unwrap();
758 /// Then, from a lint point of view, the declaration of `x: u32`
759 /// (and `y: u32`) are within the `#[allow(unused_mut)]` scope - the
760 /// lint scopes are the same as the AST/HIR nesting.
762 /// However, from a name lookup point of view, the scopes look more like
763 /// as if the let-statements were `match` expressions:
766 /// fn foo(x: &str) {
768 /// match x.parse().unwrap() {
777 /// We care about the name-lookup scopes for debuginfo - if the
778 /// debuginfo instruction pointer is at the call to `x.parse()`, we
779 /// want `x` to refer to `x: &str`, but if it is at the call to
780 /// `drop(x)`, we want it to refer to `x: u32`.
782 /// To allow both uses to work, we need to have more than a single scope
783 /// for a local. We have the `source_info.scope` represent the "syntactic"
784 /// lint scope (with a variable being under its let block) while the
785 /// `var_debug_info.source_info.scope` represents the "local variable"
786 /// scope (where the "rest" of a block is under all prior let-statements).
788 /// The end result looks like this:
792 /// │{ argument x: &str }
794 /// │ │{ #[allow(unused_mut)] } // This is actually split into 2 scopes
795 /// │ │ // in practice because I'm lazy.
797 /// │ │← x.source_info.scope
798 /// │ │← `x.parse().unwrap()`
800 /// │ │ │← y.source_info.scope
802 /// │ │ │{ let y: u32 }
804 /// │ │ │← y.var_debug_info.source_info.scope
807 /// │ │{ let x: u32 }
808 /// │ │← x.var_debug_info.source_info.scope
809 /// │ │← `drop(x)` // This accesses `x: u32`.
811 pub source_info: SourceInfo,
814 /// Extra information about a local that's used for diagnostics.
815 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
816 pub enum LocalInfo<'tcx> {
817 /// A user-defined local variable or function parameter
819 /// The `BindingForm` is solely used for local diagnostics when generating
820 /// warnings/errors when compiling the current crate, and therefore it need
821 /// not be visible across crates.
822 User(ClearCrossCrate<BindingForm<'tcx>>),
823 /// A temporary created that references the static with the given `DefId`.
824 StaticRef { def_id: DefId, is_thread_local: bool },
825 /// Any other temporary, the return place, or an anonymous function parameter.
829 impl<'tcx> LocalDecl<'tcx> {
830 /// Returns `true` only if local is a binding that can itself be
831 /// made mutable via the addition of the `mut` keyword, namely
832 /// something like the occurrences of `x` in:
833 /// - `fn foo(x: Type) { ... }`,
835 /// - or `match ... { C(x) => ... }`
836 pub fn can_be_made_mutable(&self) -> bool {
837 match self.local_info {
838 LocalInfo::User(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
839 binding_mode: ty::BindingMode::BindByValue(_),
845 LocalInfo::User(ClearCrossCrate::Set(BindingForm::ImplicitSelf(
846 ImplicitSelfKind::Imm,
853 /// Returns `true` if local is definitely not a `ref ident` or
854 /// `ref mut ident` binding. (Such bindings cannot be made into
855 /// mutable bindings, but the inverse does not necessarily hold).
856 pub fn is_nonref_binding(&self) -> bool {
857 match self.local_info {
858 LocalInfo::User(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
859 binding_mode: ty::BindingMode::BindByValue(_),
865 LocalInfo::User(ClearCrossCrate::Set(BindingForm::ImplicitSelf(_))) => true,
871 /// Returns `true` if this variable is a named variable or function
872 /// parameter declared by the user.
874 pub fn is_user_variable(&self) -> bool {
875 match self.local_info {
876 LocalInfo::User(_) => true,
881 /// Returns `true` if this is a reference to a variable bound in a `match`
882 /// expression that is used to access said variable for the guard of the
884 pub fn is_ref_for_guard(&self) -> bool {
885 match self.local_info {
886 LocalInfo::User(ClearCrossCrate::Set(BindingForm::RefForGuard)) => true,
891 /// Returns `Some` if this is a reference to a static item that is used to
892 /// access that static
893 pub fn is_ref_to_static(&self) -> bool {
894 match self.local_info {
895 LocalInfo::StaticRef { .. } => true,
900 /// Returns `Some` if this is a reference to a static item that is used to
901 /// access that static
902 pub fn is_ref_to_thread_local(&self) -> bool {
903 match self.local_info {
904 LocalInfo::StaticRef { is_thread_local, .. } => is_thread_local,
909 /// Returns `true` is the local is from a compiler desugaring, e.g.,
910 /// `__next` from a `for` loop.
912 pub fn from_compiler_desugaring(&self) -> bool {
913 self.source_info.span.desugaring_kind().is_some()
916 /// Creates a new `LocalDecl` for a temporary.
918 pub fn new_temp(ty: Ty<'tcx>, span: Span) -> Self {
919 Self::new_local(ty, Mutability::Mut, false, span)
922 /// Converts `self` into same `LocalDecl` except tagged as immutable.
924 pub fn immutable(mut self) -> Self {
925 self.mutability = Mutability::Not;
929 /// Converts `self` into same `LocalDecl` except tagged as internal temporary.
931 pub fn block_tail(mut self, info: BlockTailInfo) -> Self {
932 assert!(self.is_block_tail.is_none());
933 self.is_block_tail = Some(info);
937 /// Creates a new `LocalDecl` for a internal temporary.
939 pub fn new_internal(ty: Ty<'tcx>, span: Span) -> Self {
940 Self::new_local(ty, Mutability::Mut, true, span)
944 fn new_local(ty: Ty<'tcx>, mutability: Mutability, internal: bool, span: Span) -> Self {
948 user_ty: UserTypeProjections::none(),
949 source_info: SourceInfo { span, scope: OUTERMOST_SOURCE_SCOPE },
951 local_info: LocalInfo::Other,
956 /// Builds a `LocalDecl` for the return place.
958 /// This must be inserted into the `local_decls` list as the first local.
960 pub fn new_return_place(return_ty: Ty<'_>, span: Span) -> LocalDecl<'_> {
962 mutability: Mutability::Mut,
964 user_ty: UserTypeProjections::none(),
965 source_info: SourceInfo { span, scope: OUTERMOST_SOURCE_SCOPE },
968 local_info: LocalInfo::Other,
973 /// Debug information pertaining to a user variable.
974 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
975 pub struct VarDebugInfo<'tcx> {
978 /// Source info of the user variable, including the scope
979 /// within which the variable is visible (to debuginfo)
980 /// (see `LocalDecl`'s `source_info` field for more details).
981 pub source_info: SourceInfo,
983 /// Where the data for this user variable is to be found.
984 /// NOTE(eddyb) There's an unenforced invariant that this `Place` is
985 /// based on a `Local`, not a `Static`, and contains no indexing.
986 pub place: Place<'tcx>,
989 ///////////////////////////////////////////////////////////////////////////
992 rustc_index::newtype_index! {
993 pub struct BasicBlock {
995 DEBUG_FORMAT = "bb{}",
996 const START_BLOCK = 0,
1001 pub fn start_location(self) -> Location {
1002 Location { block: self, statement_index: 0 }
1006 ///////////////////////////////////////////////////////////////////////////
1007 // BasicBlockData and Terminator
1009 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
1010 pub struct BasicBlockData<'tcx> {
1011 /// List of statements in this block.
1012 pub statements: Vec<Statement<'tcx>>,
1014 /// Terminator for this block.
1016 /// N.B., this should generally ONLY be `None` during construction.
1017 /// Therefore, you should generally access it via the
1018 /// `terminator()` or `terminator_mut()` methods. The only
1019 /// exception is that certain passes, such as `simplify_cfg`, swap
1020 /// out the terminator temporarily with `None` while they continue
1021 /// to recurse over the set of basic blocks.
1022 pub terminator: Option<Terminator<'tcx>>,
1024 /// If true, this block lies on an unwind path. This is used
1025 /// during codegen where distinct kinds of basic blocks may be
1026 /// generated (particularly for MSVC cleanup). Unwind blocks must
1027 /// only branch to other unwind blocks.
1028 pub is_cleanup: bool,
1031 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
1032 pub struct Terminator<'tcx> {
1033 pub source_info: SourceInfo,
1034 pub kind: TerminatorKind<'tcx>,
1037 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable, PartialEq)]
1038 pub enum TerminatorKind<'tcx> {
1039 /// Block should have one successor in the graph; we jump there.
1040 Goto { target: BasicBlock },
1042 /// Operand evaluates to an integer; jump depending on its value
1043 /// to one of the targets, and otherwise fallback to `otherwise`.
1045 /// The discriminant value being tested.
1046 discr: Operand<'tcx>,
1048 /// The type of value being tested.
1049 switch_ty: Ty<'tcx>,
1051 /// Possible values. The locations to branch to in each case
1052 /// are found in the corresponding indices from the `targets` vector.
1053 values: Cow<'tcx, [u128]>,
1055 /// Possible branch sites. The last element of this vector is used
1056 /// for the otherwise branch, so targets.len() == values.len() + 1
1059 // This invariant is quite non-obvious and also could be improved.
1060 // One way to make this invariant is to have something like this instead:
1062 // branches: Vec<(ConstInt, BasicBlock)>,
1063 // otherwise: Option<BasicBlock> // exhaustive if None
1065 // However we’ve decided to keep this as-is until we figure a case
1066 // where some other approach seems to be strictly better than other.
1067 targets: Vec<BasicBlock>,
1070 /// Indicates that the landing pad is finished and unwinding should
1071 /// continue. Emitted by `build::scope::diverge_cleanup`.
1074 /// Indicates that the landing pad is finished and that the process
1075 /// should abort. Used to prevent unwinding for foreign items.
1078 /// Indicates a normal return. The return place should have
1079 /// been filled in by now. This should occur at most once.
1082 /// Indicates a terminator that can never be reached.
1085 /// Drop the `Place`.
1086 Drop { location: Place<'tcx>, target: BasicBlock, unwind: Option<BasicBlock> },
1088 /// Drop the `Place` and assign the new value over it. This ensures
1089 /// that the assignment to `P` occurs *even if* the destructor for
1090 /// place unwinds. Its semantics are best explained by the
1095 /// DropAndReplace(P <- V, goto BB1, unwind BB2)
1103 /// Drop(P, goto BB1, unwind BB2)
1106 /// // P is now uninitialized
1110 /// // P is now uninitialized -- its dtor panicked
1115 location: Place<'tcx>,
1116 value: Operand<'tcx>,
1118 unwind: Option<BasicBlock>,
1121 /// Block ends with a call of a converging function.
1123 /// The function that’s being called.
1124 func: Operand<'tcx>,
1125 /// Arguments the function is called with.
1126 /// These are owned by the callee, which is free to modify them.
1127 /// This allows the memory occupied by "by-value" arguments to be
1128 /// reused across function calls without duplicating the contents.
1129 args: Vec<Operand<'tcx>>,
1130 /// Destination for the return value. If some, the call is converging.
1131 destination: Option<(Place<'tcx>, BasicBlock)>,
1132 /// Cleanups to be done if the call unwinds.
1133 cleanup: Option<BasicBlock>,
1134 /// `true` if this is from a call in HIR rather than from an overloaded
1135 /// operator. True for overloaded function call.
1136 from_hir_call: bool,
1139 /// Jump to the target if the condition has the expected value,
1140 /// otherwise panic with a message and a cleanup target.
1142 cond: Operand<'tcx>,
1144 msg: AssertMessage<'tcx>,
1146 cleanup: Option<BasicBlock>,
1149 /// A suspend point.
1151 /// The value to return.
1152 value: Operand<'tcx>,
1153 /// Where to resume to.
1155 /// The place to store the resume argument in.
1156 resume_arg: Place<'tcx>,
1157 /// Cleanup to be done if the generator is dropped at this suspend point.
1158 drop: Option<BasicBlock>,
1161 /// Indicates the end of the dropping of a generator.
1164 /// A block where control flow only ever takes one real path, but borrowck
1165 /// needs to be more conservative.
1167 /// The target normal control flow will take.
1168 real_target: BasicBlock,
1169 /// A block control flow could conceptually jump to, but won't in
1171 imaginary_target: BasicBlock,
1173 /// A terminator for blocks that only take one path in reality, but where we
1174 /// reserve the right to unwind in borrowck, even if it won't happen in practice.
1175 /// This can arise in infinite loops with no function calls for example.
1177 /// The target normal control flow will take.
1178 real_target: BasicBlock,
1179 /// The imaginary cleanup block link. This particular path will never be taken
1180 /// in practice, but in order to avoid fragility we want to always
1181 /// consider it in borrowck. We don't want to accept programs which
1182 /// pass borrowck only when `panic=abort` or some assertions are disabled
1183 /// due to release vs. debug mode builds. This needs to be an `Option` because
1184 /// of the `remove_noop_landing_pads` and `no_landing_pads` passes.
1185 unwind: Option<BasicBlock>,
1189 /// Information about an assertion failure.
1190 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable, PartialEq)]
1191 pub enum AssertKind<O> {
1192 BoundsCheck { len: O, index: O },
1197 ResumedAfterReturn(GeneratorKind),
1198 ResumedAfterPanic(GeneratorKind),
1201 /// Type for MIR `Assert` terminator error messages.
1202 pub type AssertMessage<'tcx> = AssertKind<Operand<'tcx>>;
1204 pub type Successors<'a> =
1205 iter::Chain<option::IntoIter<&'a BasicBlock>, slice::Iter<'a, BasicBlock>>;
1206 pub type SuccessorsMut<'a> =
1207 iter::Chain<option::IntoIter<&'a mut BasicBlock>, slice::IterMut<'a, BasicBlock>>;
1209 impl<'tcx> Terminator<'tcx> {
1210 pub fn successors(&self) -> Successors<'_> {
1211 self.kind.successors()
1214 pub fn successors_mut(&mut self) -> SuccessorsMut<'_> {
1215 self.kind.successors_mut()
1218 pub fn unwind(&self) -> Option<&Option<BasicBlock>> {
1222 pub fn unwind_mut(&mut self) -> Option<&mut Option<BasicBlock>> {
1223 self.kind.unwind_mut()
1227 impl<'tcx> TerminatorKind<'tcx> {
1230 cond: Operand<'tcx>,
1233 ) -> TerminatorKind<'tcx> {
1234 static BOOL_SWITCH_FALSE: &[u128] = &[0];
1235 TerminatorKind::SwitchInt {
1237 switch_ty: tcx.types.bool,
1238 values: From::from(BOOL_SWITCH_FALSE),
1239 targets: vec![f, t],
1243 pub fn successors(&self) -> Successors<'_> {
1244 use self::TerminatorKind::*;
1251 | Call { destination: None, cleanup: None, .. } => None.into_iter().chain(&[]),
1252 Goto { target: ref t }
1253 | Call { destination: None, cleanup: Some(ref t), .. }
1254 | Call { destination: Some((_, ref t)), cleanup: None, .. }
1255 | Yield { resume: ref t, drop: None, .. }
1256 | DropAndReplace { target: ref t, unwind: None, .. }
1257 | Drop { target: ref t, unwind: None, .. }
1258 | Assert { target: ref t, cleanup: None, .. }
1259 | FalseUnwind { real_target: ref t, unwind: None } => Some(t).into_iter().chain(&[]),
1260 Call { destination: Some((_, ref t)), cleanup: Some(ref u), .. }
1261 | Yield { resume: ref t, drop: Some(ref u), .. }
1262 | DropAndReplace { target: ref t, unwind: Some(ref u), .. }
1263 | Drop { target: ref t, unwind: Some(ref u), .. }
1264 | Assert { target: ref t, cleanup: Some(ref u), .. }
1265 | FalseUnwind { real_target: ref t, unwind: Some(ref u) } => {
1266 Some(t).into_iter().chain(slice::from_ref(u))
1268 SwitchInt { ref targets, .. } => None.into_iter().chain(&targets[..]),
1269 FalseEdges { ref real_target, ref imaginary_target } => {
1270 Some(real_target).into_iter().chain(slice::from_ref(imaginary_target))
1275 pub fn successors_mut(&mut self) -> SuccessorsMut<'_> {
1276 use self::TerminatorKind::*;
1283 | Call { destination: None, cleanup: None, .. } => None.into_iter().chain(&mut []),
1284 Goto { target: ref mut t }
1285 | Call { destination: None, cleanup: Some(ref mut t), .. }
1286 | Call { destination: Some((_, ref mut t)), cleanup: None, .. }
1287 | Yield { resume: ref mut t, drop: None, .. }
1288 | DropAndReplace { target: ref mut t, unwind: None, .. }
1289 | Drop { target: ref mut t, unwind: None, .. }
1290 | Assert { target: ref mut t, cleanup: None, .. }
1291 | FalseUnwind { real_target: ref mut t, unwind: None } => {
1292 Some(t).into_iter().chain(&mut [])
1294 Call { destination: Some((_, ref mut t)), cleanup: Some(ref mut u), .. }
1295 | Yield { resume: ref mut t, drop: Some(ref mut u), .. }
1296 | DropAndReplace { target: ref mut t, unwind: Some(ref mut u), .. }
1297 | Drop { target: ref mut t, unwind: Some(ref mut u), .. }
1298 | Assert { target: ref mut t, cleanup: Some(ref mut u), .. }
1299 | FalseUnwind { real_target: ref mut t, unwind: Some(ref mut u) } => {
1300 Some(t).into_iter().chain(slice::from_mut(u))
1302 SwitchInt { ref mut targets, .. } => None.into_iter().chain(&mut targets[..]),
1303 FalseEdges { ref mut real_target, ref mut imaginary_target } => {
1304 Some(real_target).into_iter().chain(slice::from_mut(imaginary_target))
1309 pub fn unwind(&self) -> Option<&Option<BasicBlock>> {
1311 TerminatorKind::Goto { .. }
1312 | TerminatorKind::Resume
1313 | TerminatorKind::Abort
1314 | TerminatorKind::Return
1315 | TerminatorKind::Unreachable
1316 | TerminatorKind::GeneratorDrop
1317 | TerminatorKind::Yield { .. }
1318 | TerminatorKind::SwitchInt { .. }
1319 | TerminatorKind::FalseEdges { .. } => None,
1320 TerminatorKind::Call { cleanup: ref unwind, .. }
1321 | TerminatorKind::Assert { cleanup: ref unwind, .. }
1322 | TerminatorKind::DropAndReplace { ref unwind, .. }
1323 | TerminatorKind::Drop { ref unwind, .. }
1324 | TerminatorKind::FalseUnwind { ref unwind, .. } => Some(unwind),
1328 pub fn unwind_mut(&mut self) -> Option<&mut Option<BasicBlock>> {
1330 TerminatorKind::Goto { .. }
1331 | TerminatorKind::Resume
1332 | TerminatorKind::Abort
1333 | TerminatorKind::Return
1334 | TerminatorKind::Unreachable
1335 | TerminatorKind::GeneratorDrop
1336 | TerminatorKind::Yield { .. }
1337 | TerminatorKind::SwitchInt { .. }
1338 | TerminatorKind::FalseEdges { .. } => None,
1339 TerminatorKind::Call { cleanup: ref mut unwind, .. }
1340 | TerminatorKind::Assert { cleanup: ref mut unwind, .. }
1341 | TerminatorKind::DropAndReplace { ref mut unwind, .. }
1342 | TerminatorKind::Drop { ref mut unwind, .. }
1343 | TerminatorKind::FalseUnwind { ref mut unwind, .. } => Some(unwind),
1348 impl<'tcx> BasicBlockData<'tcx> {
1349 pub fn new(terminator: Option<Terminator<'tcx>>) -> BasicBlockData<'tcx> {
1350 BasicBlockData { statements: vec![], terminator, is_cleanup: false }
1353 /// Accessor for terminator.
1355 /// Terminator may not be None after construction of the basic block is complete. This accessor
1356 /// provides a convenience way to reach the terminator.
1357 pub fn terminator(&self) -> &Terminator<'tcx> {
1358 self.terminator.as_ref().expect("invalid terminator state")
1361 pub fn terminator_mut(&mut self) -> &mut Terminator<'tcx> {
1362 self.terminator.as_mut().expect("invalid terminator state")
1365 pub fn retain_statements<F>(&mut self, mut f: F)
1367 F: FnMut(&mut Statement<'_>) -> bool,
1369 for s in &mut self.statements {
1376 pub fn expand_statements<F, I>(&mut self, mut f: F)
1378 F: FnMut(&mut Statement<'tcx>) -> Option<I>,
1379 I: iter::TrustedLen<Item = Statement<'tcx>>,
1381 // Gather all the iterators we'll need to splice in, and their positions.
1382 let mut splices: Vec<(usize, I)> = vec![];
1383 let mut extra_stmts = 0;
1384 for (i, s) in self.statements.iter_mut().enumerate() {
1385 if let Some(mut new_stmts) = f(s) {
1386 if let Some(first) = new_stmts.next() {
1387 // We can already store the first new statement.
1390 // Save the other statements for optimized splicing.
1391 let remaining = new_stmts.size_hint().0;
1393 splices.push((i + 1 + extra_stmts, new_stmts));
1394 extra_stmts += remaining;
1402 // Splice in the new statements, from the end of the block.
1403 // FIXME(eddyb) This could be more efficient with a "gap buffer"
1404 // where a range of elements ("gap") is left uninitialized, with
1405 // splicing adding new elements to the end of that gap and moving
1406 // existing elements from before the gap to the end of the gap.
1407 // For now, this is safe code, emulating a gap but initializing it.
1408 let mut gap = self.statements.len()..self.statements.len() + extra_stmts;
1409 self.statements.resize(
1412 source_info: SourceInfo { span: DUMMY_SP, scope: OUTERMOST_SOURCE_SCOPE },
1413 kind: StatementKind::Nop,
1416 for (splice_start, new_stmts) in splices.into_iter().rev() {
1417 let splice_end = splice_start + new_stmts.size_hint().0;
1418 while gap.end > splice_end {
1421 self.statements.swap(gap.start, gap.end);
1423 self.statements.splice(splice_start..splice_end, new_stmts);
1424 gap.end = splice_start;
1428 pub fn visitable(&self, index: usize) -> &dyn MirVisitable<'tcx> {
1429 if index < self.statements.len() { &self.statements[index] } else { &self.terminator }
1433 impl<O> AssertKind<O> {
1434 /// Getting a description does not require `O` to be printable, and does not
1435 /// require allocation.
1436 /// The caller is expected to handle `BoundsCheck` separately.
1437 pub fn description(&self) -> &'static str {
1440 Overflow(BinOp::Add) => "attempt to add with overflow",
1441 Overflow(BinOp::Sub) => "attempt to subtract with overflow",
1442 Overflow(BinOp::Mul) => "attempt to multiply with overflow",
1443 Overflow(BinOp::Div) => "attempt to divide with overflow",
1444 Overflow(BinOp::Rem) => "attempt to calculate the remainder with overflow",
1445 OverflowNeg => "attempt to negate with overflow",
1446 Overflow(BinOp::Shr) => "attempt to shift right with overflow",
1447 Overflow(BinOp::Shl) => "attempt to shift left with overflow",
1448 Overflow(op) => bug!("{:?} cannot overflow", op),
1449 DivisionByZero => "attempt to divide by zero",
1450 RemainderByZero => "attempt to calculate the remainder with a divisor of zero",
1451 ResumedAfterReturn(GeneratorKind::Gen) => "generator resumed after completion",
1452 ResumedAfterReturn(GeneratorKind::Async(_)) => "`async fn` resumed after completion",
1453 ResumedAfterPanic(GeneratorKind::Gen) => "generator resumed after panicking",
1454 ResumedAfterPanic(GeneratorKind::Async(_)) => "`async fn` resumed after panicking",
1455 BoundsCheck { .. } => bug!("Unexpected AssertKind"),
1459 /// Format the message arguments for the `assert(cond, msg..)` terminator in MIR printing.
1460 fn fmt_assert_args<W: Write>(&self, f: &mut W) -> fmt::Result
1465 AssertKind::BoundsCheck { ref len, ref index } => write!(
1467 "\"index out of bounds: the len is {{}} but the index is {{}}\", {:?}, {:?}",
1470 _ => write!(f, "\"{}\"", self.description()),
1475 impl<O: fmt::Debug> fmt::Debug for AssertKind<O> {
1476 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1479 BoundsCheck { ref len, ref index } => {
1480 write!(f, "index out of bounds: the len is {:?} but the index is {:?}", len, index)
1482 _ => write!(f, "{}", self.description()),
1487 impl<'tcx> Debug for TerminatorKind<'tcx> {
1488 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1489 self.fmt_head(fmt)?;
1490 let successor_count = self.successors().count();
1491 let labels = self.fmt_successor_labels();
1492 assert_eq!(successor_count, labels.len());
1494 match successor_count {
1497 1 => write!(fmt, " -> {:?}", self.successors().next().unwrap()),
1500 write!(fmt, " -> [")?;
1501 for (i, target) in self.successors().enumerate() {
1505 write!(fmt, "{}: {:?}", labels[i], target)?;
1513 impl<'tcx> TerminatorKind<'tcx> {
1514 /// Writes the "head" part of the terminator; that is, its name and the data it uses to pick the
1515 /// successor basic block, if any. The only information not included is the list of possible
1516 /// successors, which may be rendered differently between the text and the graphviz format.
1517 pub fn fmt_head<W: Write>(&self, fmt: &mut W) -> fmt::Result {
1518 use self::TerminatorKind::*;
1520 Goto { .. } => write!(fmt, "goto"),
1521 SwitchInt { discr, .. } => write!(fmt, "switchInt({:?})", discr),
1522 Return => write!(fmt, "return"),
1523 GeneratorDrop => write!(fmt, "generator_drop"),
1524 Resume => write!(fmt, "resume"),
1525 Abort => write!(fmt, "abort"),
1526 Yield { value, resume_arg, .. } => write!(fmt, "{:?} = yield({:?})", resume_arg, value),
1527 Unreachable => write!(fmt, "unreachable"),
1528 Drop { location, .. } => write!(fmt, "drop({:?})", location),
1529 DropAndReplace { location, value, .. } => {
1530 write!(fmt, "replace({:?} <- {:?})", location, value)
1532 Call { func, args, destination, .. } => {
1533 if let Some((destination, _)) = destination {
1534 write!(fmt, "{:?} = ", destination)?;
1536 write!(fmt, "{:?}(", func)?;
1537 for (index, arg) in args.iter().enumerate() {
1541 write!(fmt, "{:?}", arg)?;
1545 Assert { cond, expected, msg, .. } => {
1546 write!(fmt, "assert(")?;
1550 write!(fmt, "{:?}, ", cond)?;
1551 msg.fmt_assert_args(fmt)?;
1554 FalseEdges { .. } => write!(fmt, "falseEdges"),
1555 FalseUnwind { .. } => write!(fmt, "falseUnwind"),
1559 /// Returns the list of labels for the edges to the successor basic blocks.
1560 pub fn fmt_successor_labels(&self) -> Vec<Cow<'static, str>> {
1561 use self::TerminatorKind::*;
1563 Return | Resume | Abort | Unreachable | GeneratorDrop => vec![],
1564 Goto { .. } => vec!["".into()],
1565 SwitchInt { ref values, switch_ty, .. } => ty::tls::with(|tcx| {
1566 let param_env = ty::ParamEnv::empty();
1567 let switch_ty = tcx.lift(&switch_ty).unwrap();
1568 let size = tcx.layout_of(param_env.and(switch_ty)).unwrap().size;
1572 ty::Const::from_scalar(tcx, Scalar::from_uint(u, size), switch_ty)
1576 .chain(iter::once("otherwise".into()))
1579 Call { destination: Some(_), cleanup: Some(_), .. } => {
1580 vec!["return".into(), "unwind".into()]
1582 Call { destination: Some(_), cleanup: None, .. } => vec!["return".into()],
1583 Call { destination: None, cleanup: Some(_), .. } => vec!["unwind".into()],
1584 Call { destination: None, cleanup: None, .. } => vec![],
1585 Yield { drop: Some(_), .. } => vec!["resume".into(), "drop".into()],
1586 Yield { drop: None, .. } => vec!["resume".into()],
1587 DropAndReplace { unwind: None, .. } | Drop { unwind: None, .. } => {
1588 vec!["return".into()]
1590 DropAndReplace { unwind: Some(_), .. } | Drop { unwind: Some(_), .. } => {
1591 vec!["return".into(), "unwind".into()]
1593 Assert { cleanup: None, .. } => vec!["".into()],
1594 Assert { .. } => vec!["success".into(), "unwind".into()],
1595 FalseEdges { .. } => vec!["real".into(), "imaginary".into()],
1596 FalseUnwind { unwind: Some(_), .. } => vec!["real".into(), "cleanup".into()],
1597 FalseUnwind { unwind: None, .. } => vec!["real".into()],
1602 ///////////////////////////////////////////////////////////////////////////
1605 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
1606 pub struct Statement<'tcx> {
1607 pub source_info: SourceInfo,
1608 pub kind: StatementKind<'tcx>,
1611 // `Statement` is used a lot. Make sure it doesn't unintentionally get bigger.
1612 #[cfg(target_arch = "x86_64")]
1613 static_assert_size!(Statement<'_>, 32);
1615 impl Statement<'_> {
1616 /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
1617 /// invalidating statement indices in `Location`s.
1618 pub fn make_nop(&mut self) {
1619 self.kind = StatementKind::Nop
1622 /// Changes a statement to a nop and returns the original statement.
1623 pub fn replace_nop(&mut self) -> Self {
1625 source_info: self.source_info,
1626 kind: mem::replace(&mut self.kind, StatementKind::Nop),
1631 #[derive(Clone, Debug, PartialEq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
1632 pub enum StatementKind<'tcx> {
1633 /// Write the RHS Rvalue to the LHS Place.
1634 Assign(Box<(Place<'tcx>, Rvalue<'tcx>)>),
1636 /// This represents all the reading that a pattern match may do
1637 /// (e.g., inspecting constants and discriminant values), and the
1638 /// kind of pattern it comes from. This is in order to adapt potential
1639 /// error messages to these specific patterns.
1641 /// Note that this also is emitted for regular `let` bindings to ensure that locals that are
1642 /// never accessed still get some sanity checks for, e.g., `let x: ! = ..;`
1643 FakeRead(FakeReadCause, Box<Place<'tcx>>),
1645 /// Write the discriminant for a variant to the enum Place.
1646 SetDiscriminant { place: Box<Place<'tcx>>, variant_index: VariantIdx },
1648 /// Start a live range for the storage of the local.
1651 /// End the current live range for the storage of the local.
1654 /// Executes a piece of inline Assembly. Stored in a Box to keep the size
1655 /// of `StatementKind` low.
1656 LlvmInlineAsm(Box<LlvmInlineAsm<'tcx>>),
1658 /// Retag references in the given place, ensuring they got fresh tags. This is
1659 /// part of the Stacked Borrows model. These statements are currently only interpreted
1660 /// by miri and only generated when "-Z mir-emit-retag" is passed.
1661 /// See <https://internals.rust-lang.org/t/stacked-borrows-an-aliasing-model-for-rust/8153/>
1662 /// for more details.
1663 Retag(RetagKind, Box<Place<'tcx>>),
1665 /// Encodes a user's type ascription. These need to be preserved
1666 /// intact so that NLL can respect them. For example:
1670 /// The effect of this annotation is to relate the type `T_y` of the place `y`
1671 /// to the user-given type `T`. The effect depends on the specified variance:
1673 /// - `Covariant` -- requires that `T_y <: T`
1674 /// - `Contravariant` -- requires that `T_y :> T`
1675 /// - `Invariant` -- requires that `T_y == T`
1676 /// - `Bivariant` -- no effect
1677 AscribeUserType(Box<(Place<'tcx>, UserTypeProjection)>, ty::Variance),
1679 /// No-op. Useful for deleting instructions without affecting statement indices.
1683 /// Describes what kind of retag is to be performed.
1684 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, PartialEq, Eq, HashStable)]
1685 pub enum RetagKind {
1686 /// The initial retag when entering a function.
1688 /// Retag preparing for a two-phase borrow.
1690 /// Retagging raw pointers.
1692 /// A "normal" retag.
1696 /// The `FakeReadCause` describes the type of pattern why a FakeRead statement exists.
1697 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable, PartialEq)]
1698 pub enum FakeReadCause {
1699 /// Inject a fake read of the borrowed input at the end of each guards
1702 /// This should ensure that you cannot change the variant for an enum while
1703 /// you are in the midst of matching on it.
1706 /// `let x: !; match x {}` doesn't generate any read of x so we need to
1707 /// generate a read of x to check that it is initialized and safe.
1710 /// A fake read of the RefWithinGuard version of a bind-by-value variable
1711 /// in a match guard to ensure that it's value hasn't change by the time
1712 /// we create the OutsideGuard version.
1715 /// Officially, the semantics of
1717 /// `let pattern = <expr>;`
1719 /// is that `<expr>` is evaluated into a temporary and then this temporary is
1720 /// into the pattern.
1722 /// However, if we see the simple pattern `let var = <expr>`, we optimize this to
1723 /// evaluate `<expr>` directly into the variable `var`. This is mostly unobservable,
1724 /// but in some cases it can affect the borrow checker, as in #53695.
1725 /// Therefore, we insert a "fake read" here to ensure that we get
1726 /// appropriate errors.
1729 /// If we have an index expression like
1731 /// (*x)[1][{ x = y; 4}]
1733 /// then the first bounds check is invalidated when we evaluate the second
1734 /// index expression. Thus we create a fake borrow of `x` across the second
1735 /// indexer, which will cause a borrow check error.
1739 #[derive(Clone, Debug, PartialEq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
1740 pub struct LlvmInlineAsm<'tcx> {
1741 pub asm: hir::LlvmInlineAsmInner,
1742 pub outputs: Box<[Place<'tcx>]>,
1743 pub inputs: Box<[(Span, Operand<'tcx>)]>,
1746 impl Debug for Statement<'_> {
1747 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1748 use self::StatementKind::*;
1750 Assign(box (ref place, ref rv)) => write!(fmt, "{:?} = {:?}", place, rv),
1751 FakeRead(ref cause, ref place) => write!(fmt, "FakeRead({:?}, {:?})", cause, place),
1752 Retag(ref kind, ref place) => write!(
1756 RetagKind::FnEntry => "[fn entry] ",
1757 RetagKind::TwoPhase => "[2phase] ",
1758 RetagKind::Raw => "[raw] ",
1759 RetagKind::Default => "",
1763 StorageLive(ref place) => write!(fmt, "StorageLive({:?})", place),
1764 StorageDead(ref place) => write!(fmt, "StorageDead({:?})", place),
1765 SetDiscriminant { ref place, variant_index } => {
1766 write!(fmt, "discriminant({:?}) = {:?}", place, variant_index)
1768 LlvmInlineAsm(ref asm) => {
1769 write!(fmt, "llvm_asm!({:?} : {:?} : {:?})", asm.asm, asm.outputs, asm.inputs)
1771 AscribeUserType(box (ref place, ref c_ty), ref variance) => {
1772 write!(fmt, "AscribeUserType({:?}, {:?}, {:?})", place, variance, c_ty)
1774 Nop => write!(fmt, "nop"),
1779 ///////////////////////////////////////////////////////////////////////////
1782 /// A path to a value; something that can be evaluated without
1783 /// changing or disturbing program state.
1784 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, HashStable)]
1785 pub struct Place<'tcx> {
1788 /// projection out of a place (access a field, deref a pointer, etc)
1789 pub projection: &'tcx List<PlaceElem<'tcx>>,
1792 impl<'tcx> rustc_serialize::UseSpecializedDecodable for Place<'tcx> {}
1794 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
1795 #[derive(RustcEncodable, RustcDecodable, HashStable)]
1796 pub enum ProjectionElem<V, T> {
1801 /// These indices are generated by slice patterns. Easiest to explain
1805 /// [X, _, .._, _, _] => { offset: 0, min_length: 4, from_end: false },
1806 /// [_, X, .._, _, _] => { offset: 1, min_length: 4, from_end: false },
1807 /// [_, _, .._, X, _] => { offset: 2, min_length: 4, from_end: true },
1808 /// [_, _, .._, _, X] => { offset: 1, min_length: 4, from_end: true },
1811 /// index or -index (in Python terms), depending on from_end
1813 /// The thing being indexed must be at least this long. For arrays this
1814 /// is always the exact length.
1816 /// Counting backwards from end? This is always false when indexing an
1821 /// These indices are generated by slice patterns.
1823 /// If `from_end` is true `slice[from..slice.len() - to]`.
1824 /// Otherwise `array[from..to]`.
1828 /// Whether `to` counts from the start or end of the array/slice.
1829 /// For `PlaceElem`s this is `true` if and only if the base is a slice.
1830 /// For `ProjectionKind`, this can also be `true` for arrays.
1834 /// "Downcast" to a variant of an ADT. Currently, we only introduce
1835 /// this for ADTs with more than one variant. It may be better to
1836 /// just introduce it always, or always for enums.
1838 /// The included Symbol is the name of the variant, used for printing MIR.
1839 Downcast(Option<Symbol>, VariantIdx),
1842 impl<V, T> ProjectionElem<V, T> {
1843 /// Returns `true` if the target of this projection may refer to a different region of memory
1845 fn is_indirect(&self) -> bool {
1847 Self::Deref => true,
1851 | Self::ConstantIndex { .. }
1852 | Self::Subslice { .. }
1853 | Self::Downcast(_, _) => false,
1858 /// Alias for projections as they appear in places, where the base is a place
1859 /// and the index is a local.
1860 pub type PlaceElem<'tcx> = ProjectionElem<Local, Ty<'tcx>>;
1862 impl<'tcx> Copy for PlaceElem<'tcx> {}
1864 // At least on 64 bit systems, `PlaceElem` should not be larger than two pointers.
1865 #[cfg(target_arch = "x86_64")]
1866 static_assert_size!(PlaceElem<'_>, 16);
1868 /// Alias for projections as they appear in `UserTypeProjection`, where we
1869 /// need neither the `V` parameter for `Index` nor the `T` for `Field`.
1870 pub type ProjectionKind = ProjectionElem<(), ()>;
1872 rustc_index::newtype_index! {
1875 DEBUG_FORMAT = "field[{}]"
1879 #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
1880 pub struct PlaceRef<'tcx> {
1882 pub projection: &'tcx [PlaceElem<'tcx>],
1885 impl<'tcx> Place<'tcx> {
1886 // FIXME change this to a const fn by also making List::empty a const fn.
1887 pub fn return_place() -> Place<'tcx> {
1888 Place { local: RETURN_PLACE, projection: List::empty() }
1891 /// Returns `true` if this `Place` contains a `Deref` projection.
1893 /// If `Place::is_indirect` returns false, the caller knows that the `Place` refers to the
1894 /// same region of memory as its base.
1895 pub fn is_indirect(&self) -> bool {
1896 self.projection.iter().any(|elem| elem.is_indirect())
1899 /// Finds the innermost `Local` from this `Place`, *if* it is either a local itself or
1900 /// a single deref of a local.
1902 // FIXME: can we safely swap the semantics of `fn base_local` below in here instead?
1903 pub fn local_or_deref_local(&self) -> Option<Local> {
1904 match self.as_ref() {
1905 PlaceRef { local, projection: [] }
1906 | PlaceRef { local, projection: [ProjectionElem::Deref] } => Some(local),
1911 /// If this place represents a local variable like `_X` with no
1912 /// projections, return `Some(_X)`.
1913 pub fn as_local(&self) -> Option<Local> {
1914 self.as_ref().as_local()
1917 pub fn as_ref(&self) -> PlaceRef<'tcx> {
1918 PlaceRef { local: self.local, projection: &self.projection }
1922 impl From<Local> for Place<'_> {
1923 fn from(local: Local) -> Self {
1924 Place { local, projection: List::empty() }
1928 impl<'tcx> PlaceRef<'tcx> {
1929 /// Finds the innermost `Local` from this `Place`, *if* it is either a local itself or
1930 /// a single deref of a local.
1932 // FIXME: can we safely swap the semantics of `fn base_local` below in here instead?
1933 pub fn local_or_deref_local(&self) -> Option<Local> {
1935 PlaceRef { local, projection: [] }
1936 | PlaceRef { local, projection: [ProjectionElem::Deref] } => Some(local),
1941 /// If this place represents a local variable like `_X` with no
1942 /// projections, return `Some(_X)`.
1943 pub fn as_local(&self) -> Option<Local> {
1945 PlaceRef { local, projection: [] } => Some(local),
1951 impl Debug for Place<'_> {
1952 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1953 for elem in self.projection.iter().rev() {
1955 ProjectionElem::Downcast(_, _) | ProjectionElem::Field(_, _) => {
1956 write!(fmt, "(").unwrap();
1958 ProjectionElem::Deref => {
1959 write!(fmt, "(*").unwrap();
1961 ProjectionElem::Index(_)
1962 | ProjectionElem::ConstantIndex { .. }
1963 | ProjectionElem::Subslice { .. } => {}
1967 write!(fmt, "{:?}", self.local)?;
1969 for elem in self.projection.iter() {
1971 ProjectionElem::Downcast(Some(name), _index) => {
1972 write!(fmt, " as {})", name)?;
1974 ProjectionElem::Downcast(None, index) => {
1975 write!(fmt, " as variant#{:?})", index)?;
1977 ProjectionElem::Deref => {
1980 ProjectionElem::Field(field, ty) => {
1981 write!(fmt, ".{:?}: {:?})", field.index(), ty)?;
1983 ProjectionElem::Index(ref index) => {
1984 write!(fmt, "[{:?}]", index)?;
1986 ProjectionElem::ConstantIndex { offset, min_length, from_end: false } => {
1987 write!(fmt, "[{:?} of {:?}]", offset, min_length)?;
1989 ProjectionElem::ConstantIndex { offset, min_length, from_end: true } => {
1990 write!(fmt, "[-{:?} of {:?}]", offset, min_length)?;
1992 ProjectionElem::Subslice { from, to, from_end: true } if *to == 0 => {
1993 write!(fmt, "[{:?}:]", from)?;
1995 ProjectionElem::Subslice { from, to, from_end: true } if *from == 0 => {
1996 write!(fmt, "[:-{:?}]", to)?;
1998 ProjectionElem::Subslice { from, to, from_end: true } => {
1999 write!(fmt, "[{:?}:-{:?}]", from, to)?;
2001 ProjectionElem::Subslice { from, to, from_end: false } => {
2002 write!(fmt, "[{:?}..{:?}]", from, to)?;
2011 ///////////////////////////////////////////////////////////////////////////
2014 rustc_index::newtype_index! {
2015 pub struct SourceScope {
2017 DEBUG_FORMAT = "scope[{}]",
2018 const OUTERMOST_SOURCE_SCOPE = 0,
2022 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
2023 pub struct SourceScopeData {
2025 pub parent_scope: Option<SourceScope>,
2027 /// Crate-local information for this source scope, that can't (and
2028 /// needn't) be tracked across crates.
2029 pub local_data: ClearCrossCrate<SourceScopeLocalData>,
2032 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
2033 pub struct SourceScopeLocalData {
2034 /// An `HirId` with lint levels equivalent to this scope's lint levels.
2035 pub lint_root: hir::HirId,
2036 /// The unsafe block that contains this node.
2040 ///////////////////////////////////////////////////////////////////////////
2043 /// These are values that can appear inside an rvalue. They are intentionally
2044 /// limited to prevent rvalues from being nested in one another.
2045 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable)]
2046 pub enum Operand<'tcx> {
2047 /// Copy: The value must be available for use afterwards.
2049 /// This implies that the type of the place must be `Copy`; this is true
2050 /// by construction during build, but also checked by the MIR type checker.
2053 /// Move: The value (including old borrows of it) will not be used again.
2055 /// Safe for values of all types (modulo future developments towards `?Move`).
2056 /// Correct usage patterns are enforced by the borrow checker for safe code.
2057 /// `Copy` may be converted to `Move` to enable "last-use" optimizations.
2060 /// Synthesizes a constant value.
2061 Constant(Box<Constant<'tcx>>),
2064 impl<'tcx> Debug for Operand<'tcx> {
2065 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2066 use self::Operand::*;
2068 Constant(ref a) => write!(fmt, "{:?}", a),
2069 Copy(ref place) => write!(fmt, "{:?}", place),
2070 Move(ref place) => write!(fmt, "move {:?}", place),
2075 impl<'tcx> Operand<'tcx> {
2076 /// Convenience helper to make a constant that refers to the fn
2077 /// with given `DefId` and substs. Since this is used to synthesize
2078 /// MIR, assumes `user_ty` is None.
2079 pub fn function_handle(
2082 substs: SubstsRef<'tcx>,
2085 let ty = tcx.type_of(def_id).subst(tcx, substs);
2086 Operand::Constant(box Constant {
2089 literal: ty::Const::zero_sized(tcx, ty),
2093 pub fn to_copy(&self) -> Self {
2095 Operand::Copy(_) | Operand::Constant(_) => self.clone(),
2096 Operand::Move(place) => Operand::Copy(place),
2100 /// Returns the `Place` that is the target of this `Operand`, or `None` if this `Operand` is a
2102 pub fn place(&self) -> Option<Place<'tcx>> {
2104 Operand::Copy(place) | Operand::Move(place) => Some(*place),
2105 Operand::Constant(_) => None,
2110 ///////////////////////////////////////////////////////////////////////////
2113 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable, PartialEq)]
2114 pub enum Rvalue<'tcx> {
2115 /// x (either a move or copy, depending on type of x)
2119 Repeat(Operand<'tcx>, &'tcx ty::Const<'tcx>),
2122 Ref(Region<'tcx>, BorrowKind, Place<'tcx>),
2124 /// Create a raw pointer to the given place
2125 /// Can be generated by raw address of expressions (`&raw const x`),
2126 /// or when casting a reference to a raw pointer.
2127 AddressOf(Mutability, Place<'tcx>),
2129 /// length of a [X] or [X;n] value
2132 Cast(CastKind, Operand<'tcx>, Ty<'tcx>),
2134 BinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
2135 CheckedBinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
2137 NullaryOp(NullOp, Ty<'tcx>),
2138 UnaryOp(UnOp, Operand<'tcx>),
2140 /// Read the discriminant of an ADT.
2142 /// Undefined (i.e., no effort is made to make it defined, but there’s no reason why it cannot
2143 /// be defined to return, say, a 0) if ADT is not an enum.
2144 Discriminant(Place<'tcx>),
2146 /// Creates an aggregate value, like a tuple or struct. This is
2147 /// only needed because we want to distinguish `dest = Foo { x:
2148 /// ..., y: ... }` from `dest.x = ...; dest.y = ...;` in the case
2149 /// that `Foo` has a destructor. These rvalues can be optimized
2150 /// away after type-checking and before lowering.
2151 Aggregate(Box<AggregateKind<'tcx>>, Vec<Operand<'tcx>>),
2154 #[derive(Clone, Copy, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2157 Pointer(PointerCast),
2160 #[derive(Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2161 pub enum AggregateKind<'tcx> {
2162 /// The type is of the element
2166 /// The second field is the variant index. It's equal to 0 for struct
2167 /// and union expressions. The fourth field is
2168 /// active field number and is present only for union expressions
2169 /// -- e.g., for a union expression `SomeUnion { c: .. }`, the
2170 /// active field index would identity the field `c`
2171 Adt(&'tcx AdtDef, VariantIdx, SubstsRef<'tcx>, Option<UserTypeAnnotationIndex>, Option<usize>),
2173 Closure(DefId, SubstsRef<'tcx>),
2174 Generator(DefId, SubstsRef<'tcx>, hir::Movability),
2177 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2179 /// The `+` operator (addition)
2181 /// The `-` operator (subtraction)
2183 /// The `*` operator (multiplication)
2185 /// The `/` operator (division)
2187 /// The `%` operator (modulus)
2189 /// The `^` operator (bitwise xor)
2191 /// The `&` operator (bitwise and)
2193 /// The `|` operator (bitwise or)
2195 /// The `<<` operator (shift left)
2197 /// The `>>` operator (shift right)
2199 /// The `==` operator (equality)
2201 /// The `<` operator (less than)
2203 /// The `<=` operator (less than or equal to)
2205 /// The `!=` operator (not equal to)
2207 /// The `>=` operator (greater than or equal to)
2209 /// The `>` operator (greater than)
2211 /// The `ptr.offset` operator
2216 pub fn is_checkable(self) -> bool {
2219 Add | Sub | Mul | Shl | Shr => true,
2225 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2227 /// Returns the size of a value of that type
2229 /// Creates a new uninitialized box for a value of that type
2233 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2235 /// The `!` operator for logical inversion
2237 /// The `-` operator for negation
2241 impl<'tcx> Debug for Rvalue<'tcx> {
2242 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2243 use self::Rvalue::*;
2246 Use(ref place) => write!(fmt, "{:?}", place),
2247 Repeat(ref a, ref b) => {
2248 write!(fmt, "[{:?}; ", a)?;
2249 pretty_print_const(b, fmt, false)?;
2252 Len(ref a) => write!(fmt, "Len({:?})", a),
2253 Cast(ref kind, ref place, ref ty) => {
2254 write!(fmt, "{:?} as {:?} ({:?})", place, ty, kind)
2256 BinaryOp(ref op, ref a, ref b) => write!(fmt, "{:?}({:?}, {:?})", op, a, b),
2257 CheckedBinaryOp(ref op, ref a, ref b) => {
2258 write!(fmt, "Checked{:?}({:?}, {:?})", op, a, b)
2260 UnaryOp(ref op, ref a) => write!(fmt, "{:?}({:?})", op, a),
2261 Discriminant(ref place) => write!(fmt, "discriminant({:?})", place),
2262 NullaryOp(ref op, ref t) => write!(fmt, "{:?}({:?})", op, t),
2263 Ref(region, borrow_kind, ref place) => {
2264 let kind_str = match borrow_kind {
2265 BorrowKind::Shared => "",
2266 BorrowKind::Shallow => "shallow ",
2267 BorrowKind::Mut { .. } | BorrowKind::Unique => "mut ",
2270 // When printing regions, add trailing space if necessary.
2271 let print_region = ty::tls::with(|tcx| {
2272 tcx.sess.verbose() || tcx.sess.opts.debugging_opts.identify_regions
2274 let region = if print_region {
2275 let mut region = region.to_string();
2276 if !region.is_empty() {
2281 // Do not even print 'static
2284 write!(fmt, "&{}{}{:?}", region, kind_str, place)
2287 AddressOf(mutability, ref place) => {
2288 let kind_str = match mutability {
2289 Mutability::Mut => "mut",
2290 Mutability::Not => "const",
2293 write!(fmt, "&raw {} {:?}", kind_str, place)
2296 Aggregate(ref kind, ref places) => {
2297 let fmt_tuple = |fmt: &mut Formatter<'_>, name: &str| {
2298 let mut tuple_fmt = fmt.debug_tuple(name);
2299 for place in places {
2300 tuple_fmt.field(place);
2306 AggregateKind::Array(_) => write!(fmt, "{:?}", places),
2308 AggregateKind::Tuple => {
2309 if places.is_empty() {
2316 AggregateKind::Adt(adt_def, variant, substs, _user_ty, _) => {
2317 let variant_def = &adt_def.variants[variant];
2319 let name = ty::tls::with(|tcx| {
2320 let mut name = String::new();
2321 let substs = tcx.lift(&substs).expect("could not lift for printing");
2322 FmtPrinter::new(tcx, &mut name, Namespace::ValueNS)
2323 .print_def_path(variant_def.def_id, substs)?;
2327 match variant_def.ctor_kind {
2328 CtorKind::Const => fmt.write_str(&name),
2329 CtorKind::Fn => fmt_tuple(fmt, &name),
2330 CtorKind::Fictive => {
2331 let mut struct_fmt = fmt.debug_struct(&name);
2332 for (field, place) in variant_def.fields.iter().zip(places) {
2333 struct_fmt.field(&field.ident.as_str(), place);
2340 AggregateKind::Closure(def_id, substs) => ty::tls::with(|tcx| {
2341 if let Some(hir_id) = tcx.hir().as_local_hir_id(def_id) {
2342 let name = if tcx.sess.opts.debugging_opts.span_free_formats {
2343 let substs = tcx.lift(&substs).unwrap();
2346 tcx.def_path_str_with_substs(def_id, substs),
2349 format!("[closure@{:?}]", tcx.hir().span(hir_id))
2351 let mut struct_fmt = fmt.debug_struct(&name);
2353 if let Some(upvars) = tcx.upvars(def_id) {
2354 for (&var_id, place) in upvars.keys().zip(places) {
2355 let var_name = tcx.hir().name(var_id);
2356 struct_fmt.field(&var_name.as_str(), place);
2362 write!(fmt, "[closure]")
2366 AggregateKind::Generator(def_id, _, _) => ty::tls::with(|tcx| {
2367 if let Some(hir_id) = tcx.hir().as_local_hir_id(def_id) {
2368 let name = format!("[generator@{:?}]", tcx.hir().span(hir_id));
2369 let mut struct_fmt = fmt.debug_struct(&name);
2371 if let Some(upvars) = tcx.upvars(def_id) {
2372 for (&var_id, place) in upvars.keys().zip(places) {
2373 let var_name = tcx.hir().name(var_id);
2374 struct_fmt.field(&var_name.as_str(), place);
2380 write!(fmt, "[generator]")
2389 ///////////////////////////////////////////////////////////////////////////
2392 /// Two constants are equal if they are the same constant. Note that
2393 /// this does not necessarily mean that they are "==" in Rust -- in
2394 /// particular one must be wary of `NaN`!
2396 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable)]
2397 pub struct Constant<'tcx> {
2400 /// Optional user-given type: for something like
2401 /// `collect::<Vec<_>>`, this would be present and would
2402 /// indicate that `Vec<_>` was explicitly specified.
2404 /// Needed for NLL to impose user-given type constraints.
2405 pub user_ty: Option<UserTypeAnnotationIndex>,
2407 pub literal: &'tcx ty::Const<'tcx>,
2410 impl Constant<'tcx> {
2411 pub fn check_static_ptr(&self, tcx: TyCtxt<'_>) -> Option<DefId> {
2412 match self.literal.val.try_to_scalar() {
2413 Some(Scalar::Ptr(ptr)) => match tcx.alloc_map.lock().get(ptr.alloc_id) {
2414 Some(GlobalAlloc::Static(def_id)) => Some(def_id),
2417 tcx.sess.delay_span_bug(DUMMY_SP, "MIR cannot contain dangling const pointers");
2426 /// A collection of projections into user types.
2428 /// They are projections because a binding can occur a part of a
2429 /// parent pattern that has been ascribed a type.
2431 /// Its a collection because there can be multiple type ascriptions on
2432 /// the path from the root of the pattern down to the binding itself.
2437 /// struct S<'a>((i32, &'a str), String);
2438 /// let S((_, w): (i32, &'static str), _): S = ...;
2439 /// // ------ ^^^^^^^^^^^^^^^^^^^ (1)
2440 /// // --------------------------------- ^ (2)
2443 /// The highlights labelled `(1)` show the subpattern `(_, w)` being
2444 /// ascribed the type `(i32, &'static str)`.
2446 /// The highlights labelled `(2)` show the whole pattern being
2447 /// ascribed the type `S`.
2449 /// In this example, when we descend to `w`, we will have built up the
2450 /// following two projected types:
2452 /// * base: `S`, projection: `(base.0).1`
2453 /// * base: `(i32, &'static str)`, projection: `base.1`
2455 /// The first will lead to the constraint `w: &'1 str` (for some
2456 /// inferred region `'1`). The second will lead to the constraint `w:
2458 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
2459 pub struct UserTypeProjections {
2460 pub(crate) contents: Vec<(UserTypeProjection, Span)>,
2463 impl<'tcx> UserTypeProjections {
2464 pub fn none() -> Self {
2465 UserTypeProjections { contents: vec![] }
2468 pub fn from_projections(projs: impl Iterator<Item = (UserTypeProjection, Span)>) -> Self {
2469 UserTypeProjections { contents: projs.collect() }
2472 pub fn projections_and_spans(
2474 ) -> impl Iterator<Item = &(UserTypeProjection, Span)> + ExactSizeIterator {
2475 self.contents.iter()
2478 pub fn projections(&self) -> impl Iterator<Item = &UserTypeProjection> + ExactSizeIterator {
2479 self.contents.iter().map(|&(ref user_type, _span)| user_type)
2482 pub fn push_projection(mut self, user_ty: &UserTypeProjection, span: Span) -> Self {
2483 self.contents.push((user_ty.clone(), span));
2489 mut f: impl FnMut(UserTypeProjection) -> UserTypeProjection,
2491 self.contents = self.contents.drain(..).map(|(proj, span)| (f(proj), span)).collect();
2495 pub fn index(self) -> Self {
2496 self.map_projections(|pat_ty_proj| pat_ty_proj.index())
2499 pub fn subslice(self, from: u32, to: u32) -> Self {
2500 self.map_projections(|pat_ty_proj| pat_ty_proj.subslice(from, to))
2503 pub fn deref(self) -> Self {
2504 self.map_projections(|pat_ty_proj| pat_ty_proj.deref())
2507 pub fn leaf(self, field: Field) -> Self {
2508 self.map_projections(|pat_ty_proj| pat_ty_proj.leaf(field))
2511 pub fn variant(self, adt_def: &'tcx AdtDef, variant_index: VariantIdx, field: Field) -> Self {
2512 self.map_projections(|pat_ty_proj| pat_ty_proj.variant(adt_def, variant_index, field))
2516 /// Encodes the effect of a user-supplied type annotation on the
2517 /// subcomponents of a pattern. The effect is determined by applying the
2518 /// given list of proejctions to some underlying base type. Often,
2519 /// the projection element list `projs` is empty, in which case this
2520 /// directly encodes a type in `base`. But in the case of complex patterns with
2521 /// subpatterns and bindings, we want to apply only a *part* of the type to a variable,
2522 /// in which case the `projs` vector is used.
2526 /// * `let x: T = ...` -- here, the `projs` vector is empty.
2528 /// * `let (x, _): T = ...` -- here, the `projs` vector would contain
2529 /// `field[0]` (aka `.0`), indicating that the type of `s` is
2530 /// determined by finding the type of the `.0` field from `T`.
2531 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable, PartialEq)]
2532 pub struct UserTypeProjection {
2533 pub base: UserTypeAnnotationIndex,
2534 pub projs: Vec<ProjectionKind>,
2537 impl Copy for ProjectionKind {}
2539 impl UserTypeProjection {
2540 pub(crate) fn index(mut self) -> Self {
2541 self.projs.push(ProjectionElem::Index(()));
2545 pub(crate) fn subslice(mut self, from: u32, to: u32) -> Self {
2546 self.projs.push(ProjectionElem::Subslice { from, to, from_end: true });
2550 pub(crate) fn deref(mut self) -> Self {
2551 self.projs.push(ProjectionElem::Deref);
2555 pub(crate) fn leaf(mut self, field: Field) -> Self {
2556 self.projs.push(ProjectionElem::Field(field, ()));
2560 pub(crate) fn variant(
2563 variant_index: VariantIdx,
2566 self.projs.push(ProjectionElem::Downcast(
2567 Some(adt_def.variants[variant_index].ident.name),
2570 self.projs.push(ProjectionElem::Field(field, ()));
2575 CloneTypeFoldableAndLiftImpls! { ProjectionKind, }
2577 impl<'tcx> TypeFoldable<'tcx> for UserTypeProjection {
2578 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
2579 use crate::mir::ProjectionElem::*;
2581 let base = self.base.fold_with(folder);
2582 let projs: Vec<_> = self
2585 .map(|&elem| match elem {
2587 Field(f, ()) => Field(f, ()),
2588 Index(()) => Index(()),
2589 Downcast(symbol, variantidx) => Downcast(symbol, variantidx),
2590 ConstantIndex { offset, min_length, from_end } => {
2591 ConstantIndex { offset, min_length, from_end }
2593 Subslice { from, to, from_end } => Subslice { from, to, from_end },
2597 UserTypeProjection { base, projs }
2600 fn super_visit_with<Vs: TypeVisitor<'tcx>>(&self, visitor: &mut Vs) -> bool {
2601 self.base.visit_with(visitor)
2602 // Note: there's nothing in `self.proj` to visit.
2606 rustc_index::newtype_index! {
2607 pub struct Promoted {
2609 DEBUG_FORMAT = "promoted[{}]"
2613 impl<'tcx> Debug for Constant<'tcx> {
2614 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2615 write!(fmt, "{}", self)
2619 impl<'tcx> Display for Constant<'tcx> {
2620 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2621 write!(fmt, "const ")?;
2622 pretty_print_const(self.literal, fmt, true)
2626 fn pretty_print_const(
2627 c: &ty::Const<'tcx>,
2628 fmt: &mut Formatter<'_>,
2631 use crate::ty::print::PrettyPrinter;
2632 ty::tls::with(|tcx| {
2633 let literal = tcx.lift(&c).unwrap();
2634 let mut cx = FmtPrinter::new(tcx, fmt, Namespace::ValueNS);
2635 cx.print_alloc_ids = true;
2636 cx.pretty_print_const(literal, print_types)?;
2641 impl<'tcx> graph::DirectedGraph for Body<'tcx> {
2642 type Node = BasicBlock;
2645 impl<'tcx> graph::WithNumNodes for Body<'tcx> {
2647 fn num_nodes(&self) -> usize {
2648 self.basic_blocks.len()
2652 impl<'tcx> graph::WithStartNode for Body<'tcx> {
2654 fn start_node(&self) -> Self::Node {
2659 impl<'tcx> graph::WithSuccessors for Body<'tcx> {
2661 fn successors(&self, node: Self::Node) -> <Self as GraphSuccessors<'_>>::Iter {
2662 self.basic_blocks[node].terminator().successors().cloned()
2666 impl<'a, 'b> graph::GraphSuccessors<'b> for Body<'a> {
2667 type Item = BasicBlock;
2668 type Iter = iter::Cloned<Successors<'b>>;
2671 impl graph::GraphPredecessors<'graph> for Body<'tcx> {
2672 type Item = BasicBlock;
2673 type Iter = smallvec::IntoIter<[BasicBlock; 4]>;
2676 impl graph::WithPredecessors for Body<'tcx> {
2678 fn predecessors(&self, node: Self::Node) -> <Self as graph::GraphPredecessors<'_>>::Iter {
2679 self.predecessors_for(node).clone().into_iter()
2683 /// `Location` represents the position of the start of the statement; or, if
2684 /// `statement_index` equals the number of statements, then the start of the
2686 #[derive(Copy, Clone, PartialEq, Eq, Hash, Ord, PartialOrd, HashStable)]
2687 pub struct Location {
2688 /// The block that the location is within.
2689 pub block: BasicBlock,
2691 pub statement_index: usize,
2694 impl fmt::Debug for Location {
2695 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2696 write!(fmt, "{:?}[{}]", self.block, self.statement_index)
2701 pub const START: Location = Location { block: START_BLOCK, statement_index: 0 };
2703 /// Returns the location immediately after this one within the enclosing block.
2705 /// Note that if this location represents a terminator, then the
2706 /// resulting location would be out of bounds and invalid.
2707 pub fn successor_within_block(&self) -> Location {
2708 Location { block: self.block, statement_index: self.statement_index + 1 }
2711 /// Returns `true` if `other` is earlier in the control flow graph than `self`.
2712 pub fn is_predecessor_of<'tcx>(&self, other: Location, body: &Body<'tcx>) -> bool {
2713 // If we are in the same block as the other location and are an earlier statement
2714 // then we are a predecessor of `other`.
2715 if self.block == other.block && self.statement_index < other.statement_index {
2719 let predecessors = body.predecessors();
2721 // If we're in another block, then we want to check that block is a predecessor of `other`.
2722 let mut queue: Vec<BasicBlock> = predecessors[other.block].to_vec();
2723 let mut visited = FxHashSet::default();
2725 while let Some(block) = queue.pop() {
2726 // If we haven't visited this block before, then make sure we visit it's predecessors.
2727 if visited.insert(block) {
2728 queue.extend(predecessors[block].iter().cloned());
2733 // If we found the block that `self` is in, then we are a predecessor of `other` (since
2734 // we found that block by looking at the predecessors of `other`).
2735 if self.block == block {
2743 pub fn dominates(&self, other: Location, dominators: &Dominators<BasicBlock>) -> bool {
2744 if self.block == other.block {
2745 self.statement_index <= other.statement_index
2747 dominators.is_dominated_by(other.block, self.block)