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_data_structures::fx::FxHashSet;
23 use rustc_data_structures::graph::dominators::{dominators, Dominators};
24 use rustc_data_structures::graph::{self, GraphSuccessors};
25 use rustc_index::bit_set::BitMatrix;
26 use rustc_index::vec::{Idx, IndexVec};
27 use rustc_macros::HashStable;
28 use rustc_serialize::{Decodable, Encodable};
29 use rustc_span::symbol::Symbol;
30 use rustc_span::{Span, DUMMY_SP};
31 use rustc_target::abi;
32 use rustc_target::asm::InlineAsmRegOrRegClass;
34 use std::fmt::{self, Debug, Display, Formatter, Write};
35 use std::ops::{Index, IndexMut};
37 use std::{iter, mem, option};
39 use self::predecessors::{PredecessorCache, Predecessors};
40 pub use self::query::*;
48 pub use terminator::*;
54 type LocalDecls<'tcx> = IndexVec<Local, LocalDecl<'tcx>>;
56 pub trait HasLocalDecls<'tcx> {
57 fn local_decls(&self) -> &LocalDecls<'tcx>;
60 impl<'tcx> HasLocalDecls<'tcx> for LocalDecls<'tcx> {
61 fn local_decls(&self) -> &LocalDecls<'tcx> {
66 impl<'tcx> HasLocalDecls<'tcx> for Body<'tcx> {
67 fn local_decls(&self) -> &LocalDecls<'tcx> {
72 /// The various "big phases" that MIR goes through.
74 /// Warning: ordering of variants is significant.
75 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, PartialEq, Eq, PartialOrd, Ord)]
86 /// Gets the index of the current MirPhase within the set of all `MirPhase`s.
87 pub fn phase_index(&self) -> usize {
92 /// The lowered representation of a single function.
93 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable, TypeFoldable)]
94 pub struct Body<'tcx> {
95 /// A list of basic blocks. References to basic block use a newtyped index type `BasicBlock`
96 /// that indexes into this vector.
97 basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
99 /// Records how far through the "desugaring and optimization" process this particular
100 /// MIR has traversed. This is particularly useful when inlining, since in that context
101 /// we instantiate the promoted constants and add them to our promoted vector -- but those
102 /// promoted items have already been optimized, whereas ours have not. This field allows
103 /// us to see the difference and forego optimization on the inlined promoted items.
106 /// A list of source scopes; these are referenced by statements
107 /// and used for debuginfo. Indexed by a `SourceScope`.
108 pub source_scopes: IndexVec<SourceScope, SourceScopeData>,
110 /// The yield type of the function, if it is a generator.
111 pub yield_ty: Option<Ty<'tcx>>,
113 /// Generator drop glue.
114 pub generator_drop: Option<Box<Body<'tcx>>>,
116 /// The layout of a generator. Produced by the state transformation.
117 pub generator_layout: Option<GeneratorLayout<'tcx>>,
119 /// If this is a generator then record the type of source expression that caused this generator
121 pub generator_kind: Option<GeneratorKind>,
123 /// Declarations of locals.
125 /// The first local is the return value pointer, followed by `arg_count`
126 /// locals for the function arguments, followed by any user-declared
127 /// variables and temporaries.
128 pub local_decls: LocalDecls<'tcx>,
130 /// User type annotations.
131 pub user_type_annotations: CanonicalUserTypeAnnotations<'tcx>,
133 /// The number of arguments this function takes.
135 /// Starting at local 1, `arg_count` locals will be provided by the caller
136 /// and can be assumed to be initialized.
138 /// If this MIR was built for a constant, this will be 0.
139 pub arg_count: usize,
141 /// Mark an argument local (which must be a tuple) as getting passed as
142 /// its individual components at the LLVM level.
144 /// This is used for the "rust-call" ABI.
145 pub spread_arg: Option<Local>,
147 /// Debug information pertaining to user variables, including captures.
148 pub var_debug_info: Vec<VarDebugInfo<'tcx>>,
150 /// A span representing this MIR, for error reporting.
153 /// Constants that are required to evaluate successfully for this MIR to be well-formed.
154 /// We hold in this field all the constants we are not able to evaluate yet.
155 pub required_consts: Vec<Constant<'tcx>>,
157 /// The user may be writing e.g. `&[(SOME_CELL, 42)][i].1` and this would get promoted, because
158 /// we'd statically know that no thing with interior mutability will ever be available to the
159 /// user without some serious unsafe code. Now this means that our promoted is actually
160 /// `&[(SOME_CELL, 42)]` and the MIR using it will do the `&promoted[i].1` projection because
161 /// the index may be a runtime value. Such a promoted value is illegal because it has reachable
162 /// interior mutability. This flag just makes this situation very obvious where the previous
163 /// implementation without the flag hid this situation silently.
164 /// FIXME(oli-obk): rewrite the promoted during promotion to eliminate the cell components.
165 pub ignore_interior_mut_in_const_validation: bool,
167 predecessor_cache: PredecessorCache,
170 impl<'tcx> Body<'tcx> {
172 basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
173 source_scopes: IndexVec<SourceScope, SourceScopeData>,
174 local_decls: LocalDecls<'tcx>,
175 user_type_annotations: CanonicalUserTypeAnnotations<'tcx>,
177 var_debug_info: Vec<VarDebugInfo<'tcx>>,
179 generator_kind: Option<GeneratorKind>,
181 // We need `arg_count` locals, and one for the return place.
183 local_decls.len() > arg_count,
184 "expected at least {} locals, got {}",
190 phase: MirPhase::Build,
194 generator_drop: None,
195 generator_layout: None,
198 user_type_annotations,
203 required_consts: Vec::new(),
204 ignore_interior_mut_in_const_validation: false,
205 predecessor_cache: PredecessorCache::new(),
209 /// Returns a partially initialized MIR body containing only a list of basic blocks.
211 /// The returned MIR contains no `LocalDecl`s (even for the return place) or source scopes. It
212 /// is only useful for testing but cannot be `#[cfg(test)]` because it is used in a different
214 pub fn new_cfg_only(basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>) -> Self {
216 phase: MirPhase::Build,
218 source_scopes: IndexVec::new(),
220 generator_drop: None,
221 generator_layout: None,
222 local_decls: IndexVec::new(),
223 user_type_annotations: IndexVec::new(),
227 required_consts: Vec::new(),
228 generator_kind: None,
229 var_debug_info: Vec::new(),
230 ignore_interior_mut_in_const_validation: false,
231 predecessor_cache: PredecessorCache::new(),
236 pub fn basic_blocks(&self) -> &IndexVec<BasicBlock, BasicBlockData<'tcx>> {
241 pub fn basic_blocks_mut(&mut self) -> &mut IndexVec<BasicBlock, BasicBlockData<'tcx>> {
242 // Because the user could mutate basic block terminators via this reference, we need to
243 // invalidate the predecessor cache.
245 // FIXME: Use a finer-grained API for this, so only transformations that alter terminators
246 // invalidate the predecessor cache.
247 self.predecessor_cache.invalidate();
248 &mut self.basic_blocks
252 pub fn basic_blocks_and_local_decls_mut(
254 ) -> (&mut IndexVec<BasicBlock, BasicBlockData<'tcx>>, &mut LocalDecls<'tcx>) {
255 self.predecessor_cache.invalidate();
256 (&mut self.basic_blocks, &mut self.local_decls)
259 /// Returns `true` if a cycle exists in the control-flow graph that is reachable from the
261 pub fn is_cfg_cyclic(&self) -> bool {
262 graph::is_cyclic(self)
266 pub fn local_kind(&self, local: Local) -> LocalKind {
267 let index = local.as_usize();
270 self.local_decls[local].mutability == Mutability::Mut,
271 "return place should be mutable"
274 LocalKind::ReturnPointer
275 } else if index < self.arg_count + 1 {
277 } else if self.local_decls[local].is_user_variable() {
284 /// Returns an iterator over all temporaries.
286 pub fn temps_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
287 (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
288 let local = Local::new(index);
289 if self.local_decls[local].is_user_variable() { None } else { Some(local) }
293 /// Returns an iterator over all user-declared locals.
295 pub fn vars_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
296 (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
297 let local = Local::new(index);
298 self.local_decls[local].is_user_variable().then_some(local)
302 /// Returns an iterator over all user-declared mutable locals.
304 pub fn mut_vars_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
305 (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
306 let local = Local::new(index);
307 let decl = &self.local_decls[local];
308 if decl.is_user_variable() && decl.mutability == Mutability::Mut {
316 /// Returns an iterator over all user-declared mutable arguments and locals.
318 pub fn mut_vars_and_args_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
319 (1..self.local_decls.len()).filter_map(move |index| {
320 let local = Local::new(index);
321 let decl = &self.local_decls[local];
322 if (decl.is_user_variable() || index < self.arg_count + 1)
323 && decl.mutability == Mutability::Mut
332 /// Returns an iterator over all function arguments.
334 pub fn args_iter(&self) -> impl Iterator<Item = Local> + ExactSizeIterator {
335 let arg_count = self.arg_count;
336 (1..arg_count + 1).map(Local::new)
339 /// Returns an iterator over all user-defined variables and compiler-generated temporaries (all
340 /// locals that are neither arguments nor the return place).
342 pub fn vars_and_temps_iter(&self) -> impl Iterator<Item = Local> + ExactSizeIterator {
343 let arg_count = self.arg_count;
344 let local_count = self.local_decls.len();
345 (arg_count + 1..local_count).map(Local::new)
348 /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
349 /// invalidating statement indices in `Location`s.
350 pub fn make_statement_nop(&mut self, location: Location) {
351 let block = &mut self.basic_blocks[location.block];
352 debug_assert!(location.statement_index < block.statements.len());
353 block.statements[location.statement_index].make_nop()
356 /// Returns the source info associated with `location`.
357 pub fn source_info(&self, location: Location) -> &SourceInfo {
358 let block = &self[location.block];
359 let stmts = &block.statements;
360 let idx = location.statement_index;
361 if idx < stmts.len() {
362 &stmts[idx].source_info
364 assert_eq!(idx, stmts.len());
365 &block.terminator().source_info
369 /// Checks if `sub` is a sub scope of `sup`
370 pub fn is_sub_scope(&self, mut sub: SourceScope, sup: SourceScope) -> bool {
372 match self.source_scopes[sub].parent_scope {
373 None => return false,
380 /// Returns the return type; it always return first element from `local_decls` array.
382 pub fn return_ty(&self) -> Ty<'tcx> {
383 self.local_decls[RETURN_PLACE].ty
386 /// Gets the location of the terminator for the given block.
388 pub fn terminator_loc(&self, bb: BasicBlock) -> Location {
389 Location { block: bb, statement_index: self[bb].statements.len() }
393 pub fn predecessors(&self) -> impl std::ops::Deref<Target = Predecessors> + '_ {
394 self.predecessor_cache.compute(&self.basic_blocks)
398 pub fn dominators(&self) -> Dominators<BasicBlock> {
403 #[derive(Copy, Clone, PartialEq, Eq, Debug, RustcEncodable, RustcDecodable, HashStable)]
406 /// Unsafe because of a PushUnsafeBlock
408 /// Unsafe because of an unsafe fn
410 /// Unsafe because of an `unsafe` block
411 ExplicitUnsafe(hir::HirId),
414 impl<'tcx> Index<BasicBlock> for Body<'tcx> {
415 type Output = BasicBlockData<'tcx>;
418 fn index(&self, index: BasicBlock) -> &BasicBlockData<'tcx> {
419 &self.basic_blocks()[index]
423 impl<'tcx> IndexMut<BasicBlock> for Body<'tcx> {
425 fn index_mut(&mut self, index: BasicBlock) -> &mut BasicBlockData<'tcx> {
426 &mut self.basic_blocks_mut()[index]
430 #[derive(Copy, Clone, Debug, HashStable, TypeFoldable)]
431 pub enum ClearCrossCrate<T> {
436 impl<T> ClearCrossCrate<T> {
437 pub fn as_ref(&self) -> ClearCrossCrate<&T> {
439 ClearCrossCrate::Clear => ClearCrossCrate::Clear,
440 ClearCrossCrate::Set(v) => ClearCrossCrate::Set(v),
444 pub fn assert_crate_local(self) -> T {
446 ClearCrossCrate::Clear => bug!("unwrapping cross-crate data"),
447 ClearCrossCrate::Set(v) => v,
452 const TAG_CLEAR_CROSS_CRATE_CLEAR: u8 = 0;
453 const TAG_CLEAR_CROSS_CRATE_SET: u8 = 1;
455 impl<T: Encodable> rustc_serialize::UseSpecializedEncodable for ClearCrossCrate<T> {
457 fn default_encode<E: rustc_serialize::Encoder>(&self, e: &mut E) -> Result<(), E::Error> {
459 ClearCrossCrate::Clear => TAG_CLEAR_CROSS_CRATE_CLEAR.encode(e),
460 ClearCrossCrate::Set(ref val) => {
461 TAG_CLEAR_CROSS_CRATE_SET.encode(e)?;
467 impl<T: Decodable> rustc_serialize::UseSpecializedDecodable for ClearCrossCrate<T> {
469 fn default_decode<D>(d: &mut D) -> Result<ClearCrossCrate<T>, D::Error>
471 D: rustc_serialize::Decoder,
473 let discr = u8::decode(d)?;
476 TAG_CLEAR_CROSS_CRATE_CLEAR => Ok(ClearCrossCrate::Clear),
477 TAG_CLEAR_CROSS_CRATE_SET => {
478 let val = T::decode(d)?;
479 Ok(ClearCrossCrate::Set(val))
486 /// Grouped information about the source code origin of a MIR entity.
487 /// Intended to be inspected by diagnostics and debuginfo.
488 /// Most passes can work with it as a whole, within a single function.
489 // The unofficial Cranelift backend, at least as of #65828, needs `SourceInfo` to implement `Eq` and
490 // `Hash`. Please ping @bjorn3 if removing them.
491 #[derive(Copy, Clone, Debug, Eq, PartialEq, RustcEncodable, RustcDecodable, Hash, HashStable)]
492 pub struct SourceInfo {
493 /// The source span for the AST pertaining to this MIR entity.
496 /// The source scope, keeping track of which bindings can be
497 /// seen by debuginfo, active lint levels, `unsafe {...}`, etc.
498 pub scope: SourceScope,
503 pub fn outermost(span: Span) -> Self {
504 SourceInfo { span, scope: OUTERMOST_SOURCE_SCOPE }
508 ///////////////////////////////////////////////////////////////////////////
511 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable)]
512 #[derive(HashStable)]
513 pub enum BorrowKind {
514 /// Data must be immutable and is aliasable.
517 /// The immediately borrowed place must be immutable, but projections from
518 /// it don't need to be. For example, a shallow borrow of `a.b` doesn't
519 /// conflict with a mutable borrow of `a.b.c`.
521 /// This is used when lowering matches: when matching on a place we want to
522 /// ensure that place have the same value from the start of the match until
523 /// an arm is selected. This prevents this code from compiling:
525 /// let mut x = &Some(0);
528 /// Some(_) if { x = &None; false } => (),
532 /// This can't be a shared borrow because mutably borrowing (*x as Some).0
533 /// should not prevent `if let None = x { ... }`, for example, because the
534 /// mutating `(*x as Some).0` can't affect the discriminant of `x`.
535 /// We can also report errors with this kind of borrow differently.
538 /// Data must be immutable but not aliasable. This kind of borrow
539 /// cannot currently be expressed by the user and is used only in
540 /// implicit closure bindings. It is needed when the closure is
541 /// borrowing or mutating a mutable referent, e.g.:
543 /// let x: &mut isize = ...;
544 /// let y = || *x += 5;
546 /// If we were to try to translate this closure into a more explicit
547 /// form, we'd encounter an error with the code as written:
549 /// struct Env { x: & &mut isize }
550 /// let x: &mut isize = ...;
551 /// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn
552 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
554 /// This is then illegal because you cannot mutate an `&mut` found
555 /// in an aliasable location. To solve, you'd have to translate with
556 /// an `&mut` borrow:
558 /// struct Env { x: & &mut isize }
559 /// let x: &mut isize = ...;
560 /// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
561 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
563 /// Now the assignment to `**env.x` is legal, but creating a
564 /// mutable pointer to `x` is not because `x` is not mutable. We
565 /// could fix this by declaring `x` as `let mut x`. This is ok in
566 /// user code, if awkward, but extra weird for closures, since the
567 /// borrow is hidden.
569 /// So we introduce a "unique imm" borrow -- the referent is
570 /// immutable, but not aliasable. This solves the problem. For
571 /// simplicity, we don't give users the way to express this
572 /// borrow, it's just used when translating closures.
575 /// Data is mutable and not aliasable.
577 /// `true` if this borrow arose from method-call auto-ref
578 /// (i.e., `adjustment::Adjust::Borrow`).
579 allow_two_phase_borrow: bool,
584 pub fn allows_two_phase_borrow(&self) -> bool {
586 BorrowKind::Shared | BorrowKind::Shallow | BorrowKind::Unique => false,
587 BorrowKind::Mut { allow_two_phase_borrow } => allow_two_phase_borrow,
592 ///////////////////////////////////////////////////////////////////////////
593 // Variables and temps
595 rustc_index::newtype_index! {
598 DEBUG_FORMAT = "_{}",
599 const RETURN_PLACE = 0,
603 impl Atom for Local {
604 fn index(self) -> usize {
609 /// Classifies locals into categories. See `Body::local_kind`.
610 #[derive(PartialEq, Eq, Debug, HashStable)]
612 /// User-declared variable binding.
614 /// Compiler-introduced temporary.
616 /// Function argument.
618 /// Location of function's return value.
622 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
623 pub struct VarBindingForm<'tcx> {
624 /// Is variable bound via `x`, `mut x`, `ref x`, or `ref mut x`?
625 pub binding_mode: ty::BindingMode,
626 /// If an explicit type was provided for this variable binding,
627 /// this holds the source Span of that type.
629 /// NOTE: if you want to change this to a `HirId`, be wary that
630 /// doing so breaks incremental compilation (as of this writing),
631 /// while a `Span` does not cause our tests to fail.
632 pub opt_ty_info: Option<Span>,
633 /// Place of the RHS of the =, or the subject of the `match` where this
634 /// variable is initialized. None in the case of `let PATTERN;`.
635 /// Some((None, ..)) in the case of and `let [mut] x = ...` because
636 /// (a) the right-hand side isn't evaluated as a place expression.
637 /// (b) it gives a way to separate this case from the remaining cases
639 pub opt_match_place: Option<(Option<Place<'tcx>>, Span)>,
640 /// The span of the pattern in which this variable was bound.
644 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
645 pub enum BindingForm<'tcx> {
646 /// This is a binding for a non-`self` binding, or a `self` that has an explicit type.
647 Var(VarBindingForm<'tcx>),
648 /// Binding for a `self`/`&self`/`&mut self` binding where the type is implicit.
649 ImplicitSelf(ImplicitSelfKind),
650 /// Reference used in a guard expression to ensure immutability.
654 /// Represents what type of implicit self a function has, if any.
655 #[derive(Clone, Copy, PartialEq, Debug, RustcEncodable, RustcDecodable, HashStable)]
656 pub enum ImplicitSelfKind {
657 /// Represents a `fn x(self);`.
659 /// Represents a `fn x(mut self);`.
661 /// Represents a `fn x(&self);`.
663 /// Represents a `fn x(&mut self);`.
665 /// Represents when a function does not have a self argument or
666 /// when a function has a `self: X` argument.
670 CloneTypeFoldableAndLiftImpls! { BindingForm<'tcx>, }
672 mod binding_form_impl {
673 use crate::ich::StableHashingContext;
674 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
676 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for super::BindingForm<'tcx> {
677 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
678 use super::BindingForm::*;
679 ::std::mem::discriminant(self).hash_stable(hcx, hasher);
682 Var(binding) => binding.hash_stable(hcx, hasher),
683 ImplicitSelf(kind) => kind.hash_stable(hcx, hasher),
690 /// `BlockTailInfo` is attached to the `LocalDecl` for temporaries
691 /// created during evaluation of expressions in a block tail
692 /// expression; that is, a block like `{ STMT_1; STMT_2; EXPR }`.
694 /// It is used to improve diagnostics when such temporaries are
695 /// involved in borrow_check errors, e.g., explanations of where the
696 /// temporaries come from, when their destructors are run, and/or how
697 /// one might revise the code to satisfy the borrow checker's rules.
698 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
699 pub struct BlockTailInfo {
700 /// If `true`, then the value resulting from evaluating this tail
701 /// expression is ignored by the block's expression context.
703 /// Examples include `{ ...; tail };` and `let _ = { ...; tail };`
704 /// but not e.g., `let _x = { ...; tail };`
705 pub tail_result_is_ignored: bool,
707 /// `Span` of the tail expression.
713 /// This can be a binding declared by the user, a temporary inserted by the compiler, a function
714 /// argument, or the return place.
715 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
716 pub struct LocalDecl<'tcx> {
717 /// Whether this is a mutable minding (i.e., `let x` or `let mut x`).
719 /// Temporaries and the return place are always mutable.
720 pub mutability: Mutability,
722 // FIXME(matthewjasper) Don't store in this in `Body`
723 pub local_info: Option<Box<LocalInfo<'tcx>>>,
725 /// `true` if this is an internal local.
727 /// These locals are not based on types in the source code and are only used
728 /// for a few desugarings at the moment.
730 /// The generator transformation will sanity check the locals which are live
731 /// across a suspension point against the type components of the generator
732 /// which type checking knows are live across a suspension point. We need to
733 /// flag drop flags to avoid triggering this check as they are introduced
736 /// Unsafety checking will also ignore dereferences of these locals,
737 /// so they can be used for raw pointers only used in a desugaring.
739 /// This should be sound because the drop flags are fully algebraic, and
740 /// therefore don't affect the OIBIT or outlives properties of the
744 /// If this local is a temporary and `is_block_tail` is `Some`,
745 /// then it is a temporary created for evaluation of some
746 /// subexpression of some block's tail expression (with no
747 /// intervening statement context).
748 // FIXME(matthewjasper) Don't store in this in `Body`
749 pub is_block_tail: Option<BlockTailInfo>,
751 /// The type of this local.
754 /// If the user manually ascribed a type to this variable,
755 /// e.g., via `let x: T`, then we carry that type here. The MIR
756 /// borrow checker needs this information since it can affect
757 /// region inference.
758 // FIXME(matthewjasper) Don't store in this in `Body`
759 pub user_ty: Option<Box<UserTypeProjections>>,
761 /// The *syntactic* (i.e., not visibility) source scope the local is defined
762 /// in. If the local was defined in a let-statement, this
763 /// is *within* the let-statement, rather than outside
766 /// This is needed because the visibility source scope of locals within
767 /// a let-statement is weird.
769 /// The reason is that we want the local to be *within* the let-statement
770 /// for lint purposes, but we want the local to be *after* the let-statement
771 /// for names-in-scope purposes.
773 /// That's it, if we have a let-statement like the one in this
777 /// fn foo(x: &str) {
778 /// #[allow(unused_mut)]
779 /// let mut x: u32 = { // <- one unused mut
780 /// let mut y: u32 = x.parse().unwrap();
787 /// Then, from a lint point of view, the declaration of `x: u32`
788 /// (and `y: u32`) are within the `#[allow(unused_mut)]` scope - the
789 /// lint scopes are the same as the AST/HIR nesting.
791 /// However, from a name lookup point of view, the scopes look more like
792 /// as if the let-statements were `match` expressions:
795 /// fn foo(x: &str) {
797 /// match x.parse().unwrap() {
806 /// We care about the name-lookup scopes for debuginfo - if the
807 /// debuginfo instruction pointer is at the call to `x.parse()`, we
808 /// want `x` to refer to `x: &str`, but if it is at the call to
809 /// `drop(x)`, we want it to refer to `x: u32`.
811 /// To allow both uses to work, we need to have more than a single scope
812 /// for a local. We have the `source_info.scope` represent the "syntactic"
813 /// lint scope (with a variable being under its let block) while the
814 /// `var_debug_info.source_info.scope` represents the "local variable"
815 /// scope (where the "rest" of a block is under all prior let-statements).
817 /// The end result looks like this:
821 /// │{ argument x: &str }
823 /// │ │{ #[allow(unused_mut)] } // This is actually split into 2 scopes
824 /// │ │ // in practice because I'm lazy.
826 /// │ │← x.source_info.scope
827 /// │ │← `x.parse().unwrap()`
829 /// │ │ │← y.source_info.scope
831 /// │ │ │{ let y: u32 }
833 /// │ │ │← y.var_debug_info.source_info.scope
836 /// │ │{ let x: u32 }
837 /// │ │← x.var_debug_info.source_info.scope
838 /// │ │← `drop(x)` // This accesses `x: u32`.
840 pub source_info: SourceInfo,
843 // `LocalDecl` is used a lot. Make sure it doesn't unintentionally get bigger.
844 #[cfg(target_arch = "x86_64")]
845 static_assert_size!(LocalDecl<'_>, 56);
847 /// Extra information about a some locals that's used for diagnostics. (Not
848 /// used for non-StaticRef temporaries, the return place, or anonymous function
850 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
851 pub enum LocalInfo<'tcx> {
852 /// A user-defined local variable or function parameter
854 /// The `BindingForm` is solely used for local diagnostics when generating
855 /// warnings/errors when compiling the current crate, and therefore it need
856 /// not be visible across crates.
857 User(ClearCrossCrate<BindingForm<'tcx>>),
858 /// A temporary created that references the static with the given `DefId`.
859 StaticRef { def_id: DefId, is_thread_local: bool },
862 impl<'tcx> LocalDecl<'tcx> {
863 /// Returns `true` only if local is a binding that can itself be
864 /// made mutable via the addition of the `mut` keyword, namely
865 /// something like the occurrences of `x` in:
866 /// - `fn foo(x: Type) { ... }`,
868 /// - or `match ... { C(x) => ... }`
869 pub fn can_be_made_mutable(&self) -> bool {
870 match self.local_info {
871 Some(box LocalInfo::User(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
872 binding_mode: ty::BindingMode::BindByValue(_),
878 Some(box LocalInfo::User(ClearCrossCrate::Set(BindingForm::ImplicitSelf(
879 ImplicitSelfKind::Imm,
886 /// Returns `true` if local is definitely not a `ref ident` or
887 /// `ref mut ident` binding. (Such bindings cannot be made into
888 /// mutable bindings, but the inverse does not necessarily hold).
889 pub fn is_nonref_binding(&self) -> bool {
890 match self.local_info {
891 Some(box LocalInfo::User(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
892 binding_mode: ty::BindingMode::BindByValue(_),
898 Some(box LocalInfo::User(ClearCrossCrate::Set(BindingForm::ImplicitSelf(_)))) => true,
904 /// Returns `true` if this variable is a named variable or function
905 /// parameter declared by the user.
907 pub fn is_user_variable(&self) -> bool {
908 match self.local_info {
909 Some(box LocalInfo::User(_)) => true,
914 /// Returns `true` if this is a reference to a variable bound in a `match`
915 /// expression that is used to access said variable for the guard of the
917 pub fn is_ref_for_guard(&self) -> bool {
918 match self.local_info {
919 Some(box LocalInfo::User(ClearCrossCrate::Set(BindingForm::RefForGuard))) => true,
924 /// Returns `Some` if this is a reference to a static item that is used to
925 /// access that static
926 pub fn is_ref_to_static(&self) -> bool {
927 match self.local_info {
928 Some(box LocalInfo::StaticRef { .. }) => true,
933 /// Returns `Some` if this is a reference to a static item that is used to
934 /// access that static
935 pub fn is_ref_to_thread_local(&self) -> bool {
936 match self.local_info {
937 Some(box LocalInfo::StaticRef { is_thread_local, .. }) => is_thread_local,
942 /// Returns `true` is the local is from a compiler desugaring, e.g.,
943 /// `__next` from a `for` loop.
945 pub fn from_compiler_desugaring(&self) -> bool {
946 self.source_info.span.desugaring_kind().is_some()
949 /// Creates a new `LocalDecl` for a temporary: mutable, non-internal.
951 pub fn new(ty: Ty<'tcx>, span: Span) -> Self {
952 Self::with_source_info(ty, SourceInfo::outermost(span))
955 /// Like `LocalDecl::new`, but takes a `SourceInfo` instead of a `Span`.
957 pub fn with_source_info(ty: Ty<'tcx>, source_info: SourceInfo) -> Self {
959 mutability: Mutability::Mut,
969 /// Converts `self` into same `LocalDecl` except tagged as internal.
971 pub fn internal(mut self) -> Self {
972 self.internal = true;
976 /// Converts `self` into same `LocalDecl` except tagged as immutable.
978 pub fn immutable(mut self) -> Self {
979 self.mutability = Mutability::Not;
983 /// Converts `self` into same `LocalDecl` except tagged as internal temporary.
985 pub fn block_tail(mut self, info: BlockTailInfo) -> Self {
986 assert!(self.is_block_tail.is_none());
987 self.is_block_tail = Some(info);
992 /// Debug information pertaining to a user variable.
993 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
994 pub struct VarDebugInfo<'tcx> {
997 /// Source info of the user variable, including the scope
998 /// within which the variable is visible (to debuginfo)
999 /// (see `LocalDecl`'s `source_info` field for more details).
1000 pub source_info: SourceInfo,
1002 /// Where the data for this user variable is to be found.
1003 /// NOTE(eddyb) There's an unenforced invariant that this `Place` is
1004 /// based on a `Local`, not a `Static`, and contains no indexing.
1005 pub place: Place<'tcx>,
1008 ///////////////////////////////////////////////////////////////////////////
1011 rustc_index::newtype_index! {
1012 pub struct BasicBlock {
1014 DEBUG_FORMAT = "bb{}",
1015 const START_BLOCK = 0,
1020 pub fn start_location(self) -> Location {
1021 Location { block: self, statement_index: 0 }
1025 ///////////////////////////////////////////////////////////////////////////
1026 // BasicBlockData and Terminator
1028 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
1029 pub struct BasicBlockData<'tcx> {
1030 /// List of statements in this block.
1031 pub statements: Vec<Statement<'tcx>>,
1033 /// Terminator for this block.
1035 /// N.B., this should generally ONLY be `None` during construction.
1036 /// Therefore, you should generally access it via the
1037 /// `terminator()` or `terminator_mut()` methods. The only
1038 /// exception is that certain passes, such as `simplify_cfg`, swap
1039 /// out the terminator temporarily with `None` while they continue
1040 /// to recurse over the set of basic blocks.
1041 pub terminator: Option<Terminator<'tcx>>,
1043 /// If true, this block lies on an unwind path. This is used
1044 /// during codegen where distinct kinds of basic blocks may be
1045 /// generated (particularly for MSVC cleanup). Unwind blocks must
1046 /// only branch to other unwind blocks.
1047 pub is_cleanup: bool,
1050 /// Information about an assertion failure.
1051 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable, PartialEq)]
1052 pub enum AssertKind<O> {
1053 BoundsCheck { len: O, index: O },
1054 Overflow(BinOp, O, O),
1058 ResumedAfterReturn(GeneratorKind),
1059 ResumedAfterPanic(GeneratorKind),
1062 #[derive(Clone, Debug, PartialEq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
1063 pub enum InlineAsmOperand<'tcx> {
1065 reg: InlineAsmRegOrRegClass,
1066 value: Operand<'tcx>,
1069 reg: InlineAsmRegOrRegClass,
1071 place: Option<Place<'tcx>>,
1074 reg: InlineAsmRegOrRegClass,
1076 in_value: Operand<'tcx>,
1077 out_place: Option<Place<'tcx>>,
1080 value: Operand<'tcx>,
1083 value: Box<Constant<'tcx>>,
1090 /// Type for MIR `Assert` terminator error messages.
1091 pub type AssertMessage<'tcx> = AssertKind<Operand<'tcx>>;
1093 pub type Successors<'a> =
1094 iter::Chain<option::IntoIter<&'a BasicBlock>, slice::Iter<'a, BasicBlock>>;
1095 pub type SuccessorsMut<'a> =
1096 iter::Chain<option::IntoIter<&'a mut BasicBlock>, slice::IterMut<'a, BasicBlock>>;
1098 impl<'tcx> BasicBlockData<'tcx> {
1099 pub fn new(terminator: Option<Terminator<'tcx>>) -> BasicBlockData<'tcx> {
1100 BasicBlockData { statements: vec![], terminator, is_cleanup: false }
1103 /// Accessor for terminator.
1105 /// Terminator may not be None after construction of the basic block is complete. This accessor
1106 /// provides a convenience way to reach the terminator.
1107 pub fn terminator(&self) -> &Terminator<'tcx> {
1108 self.terminator.as_ref().expect("invalid terminator state")
1111 pub fn terminator_mut(&mut self) -> &mut Terminator<'tcx> {
1112 self.terminator.as_mut().expect("invalid terminator state")
1115 pub fn retain_statements<F>(&mut self, mut f: F)
1117 F: FnMut(&mut Statement<'_>) -> bool,
1119 for s in &mut self.statements {
1126 pub fn expand_statements<F, I>(&mut self, mut f: F)
1128 F: FnMut(&mut Statement<'tcx>) -> Option<I>,
1129 I: iter::TrustedLen<Item = Statement<'tcx>>,
1131 // Gather all the iterators we'll need to splice in, and their positions.
1132 let mut splices: Vec<(usize, I)> = vec![];
1133 let mut extra_stmts = 0;
1134 for (i, s) in self.statements.iter_mut().enumerate() {
1135 if let Some(mut new_stmts) = f(s) {
1136 if let Some(first) = new_stmts.next() {
1137 // We can already store the first new statement.
1140 // Save the other statements for optimized splicing.
1141 let remaining = new_stmts.size_hint().0;
1143 splices.push((i + 1 + extra_stmts, new_stmts));
1144 extra_stmts += remaining;
1152 // Splice in the new statements, from the end of the block.
1153 // FIXME(eddyb) This could be more efficient with a "gap buffer"
1154 // where a range of elements ("gap") is left uninitialized, with
1155 // splicing adding new elements to the end of that gap and moving
1156 // existing elements from before the gap to the end of the gap.
1157 // For now, this is safe code, emulating a gap but initializing it.
1158 let mut gap = self.statements.len()..self.statements.len() + extra_stmts;
1159 self.statements.resize(
1161 Statement { source_info: SourceInfo::outermost(DUMMY_SP), kind: StatementKind::Nop },
1163 for (splice_start, new_stmts) in splices.into_iter().rev() {
1164 let splice_end = splice_start + new_stmts.size_hint().0;
1165 while gap.end > splice_end {
1168 self.statements.swap(gap.start, gap.end);
1170 self.statements.splice(splice_start..splice_end, new_stmts);
1171 gap.end = splice_start;
1175 pub fn visitable(&self, index: usize) -> &dyn MirVisitable<'tcx> {
1176 if index < self.statements.len() { &self.statements[index] } else { &self.terminator }
1180 impl<O> AssertKind<O> {
1181 /// Getting a description does not require `O` to be printable, and does not
1182 /// require allocation.
1183 /// The caller is expected to handle `BoundsCheck` separately.
1184 pub fn description(&self) -> &'static str {
1187 Overflow(BinOp::Add, _, _) => "attempt to add with overflow",
1188 Overflow(BinOp::Sub, _, _) => "attempt to subtract with overflow",
1189 Overflow(BinOp::Mul, _, _) => "attempt to multiply with overflow",
1190 Overflow(BinOp::Div, _, _) => "attempt to divide with overflow",
1191 Overflow(BinOp::Rem, _, _) => "attempt to calculate the remainder with overflow",
1192 OverflowNeg(_) => "attempt to negate with overflow",
1193 Overflow(BinOp::Shr, _, _) => "attempt to shift right with overflow",
1194 Overflow(BinOp::Shl, _, _) => "attempt to shift left with overflow",
1195 Overflow(op, _, _) => bug!("{:?} cannot overflow", op),
1196 DivisionByZero(_) => "attempt to divide by zero",
1197 RemainderByZero(_) => "attempt to calculate the remainder with a divisor of zero",
1198 ResumedAfterReturn(GeneratorKind::Gen) => "generator resumed after completion",
1199 ResumedAfterReturn(GeneratorKind::Async(_)) => "`async fn` resumed after completion",
1200 ResumedAfterPanic(GeneratorKind::Gen) => "generator resumed after panicking",
1201 ResumedAfterPanic(GeneratorKind::Async(_)) => "`async fn` resumed after panicking",
1202 BoundsCheck { .. } => bug!("Unexpected AssertKind"),
1206 /// Format the message arguments for the `assert(cond, msg..)` terminator in MIR printing.
1207 fn fmt_assert_args<W: Write>(&self, f: &mut W) -> fmt::Result
1213 BoundsCheck { ref len, ref index } => write!(
1215 "\"index out of bounds: the len is {{}} but the index is {{}}\", {:?}, {:?}",
1219 OverflowNeg(op) => {
1220 write!(f, "\"attempt to negate {{}} which would overflow\", {:?}", op)
1222 DivisionByZero(op) => write!(f, "\"attempt to divide {{}} by zero\", {:?}", op),
1223 RemainderByZero(op) => write!(
1225 "\"attempt to calculate the remainder of {{}} with a divisor of zero\", {:?}",
1228 Overflow(BinOp::Add, l, r) => write!(
1230 "\"attempt to compute `{{}} + {{}}` which would overflow\", {:?}, {:?}",
1233 Overflow(BinOp::Sub, l, r) => write!(
1235 "\"attempt to compute `{{}} - {{}}` which would overflow\", {:?}, {:?}",
1238 Overflow(BinOp::Mul, l, r) => write!(
1240 "\"attempt to compute `{{}} * {{}}` which would overflow\", {:?}, {:?}",
1243 Overflow(BinOp::Div, l, r) => write!(
1245 "\"attempt to compute `{{}} / {{}}` which would overflow\", {:?}, {:?}",
1248 Overflow(BinOp::Rem, l, r) => write!(
1250 "\"attempt to compute the remainder of `{{}} % {{}}` which would overflow\", {:?}, {:?}",
1253 Overflow(BinOp::Shr, _, r) => {
1254 write!(f, "\"attempt to shift right by {{}} which would overflow\", {:?}", r)
1256 Overflow(BinOp::Shl, _, r) => {
1257 write!(f, "\"attempt to shift left by {{}} which would overflow\", {:?}", r)
1259 _ => write!(f, "\"{}\"", self.description()),
1264 impl<O: fmt::Debug> fmt::Debug for AssertKind<O> {
1265 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1268 BoundsCheck { ref len, ref index } => {
1269 write!(f, "index out of bounds: the len is {:?} but the index is {:?}", len, index)
1271 OverflowNeg(op) => write!(f, "attempt to negate {:#?} which would overflow", op),
1272 DivisionByZero(op) => write!(f, "attempt to divide {:#?} by zero", op),
1273 RemainderByZero(op) => {
1274 write!(f, "attempt to calculate the remainder of {:#?} with a divisor of zero", op)
1276 Overflow(BinOp::Add, l, r) => {
1277 write!(f, "attempt to compute `{:#?} + {:#?}` which would overflow", l, r)
1279 Overflow(BinOp::Sub, l, r) => {
1280 write!(f, "attempt to compute `{:#?} - {:#?}` which would overflow", l, r)
1282 Overflow(BinOp::Mul, l, r) => {
1283 write!(f, "attempt to compute `{:#?} * {:#?}` which would overflow", l, r)
1285 Overflow(BinOp::Div, l, r) => {
1286 write!(f, "attempt to compute `{:#?} / {:#?}` which would overflow", l, r)
1288 Overflow(BinOp::Rem, l, r) => write!(
1290 "attempt to compute the remainder of `{:#?} % {:#?}` which would overflow",
1293 Overflow(BinOp::Shr, _, r) => {
1294 write!(f, "attempt to shift right by {:#?} which would overflow", r)
1296 Overflow(BinOp::Shl, _, r) => {
1297 write!(f, "attempt to shift left by {:#?} which would overflow", r)
1299 _ => write!(f, "{}", self.description()),
1304 ///////////////////////////////////////////////////////////////////////////
1307 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
1308 pub struct Statement<'tcx> {
1309 pub source_info: SourceInfo,
1310 pub kind: StatementKind<'tcx>,
1313 // `Statement` is used a lot. Make sure it doesn't unintentionally get bigger.
1314 #[cfg(target_arch = "x86_64")]
1315 static_assert_size!(Statement<'_>, 32);
1317 impl Statement<'_> {
1318 /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
1319 /// invalidating statement indices in `Location`s.
1320 pub fn make_nop(&mut self) {
1321 self.kind = StatementKind::Nop
1324 /// Changes a statement to a nop and returns the original statement.
1325 pub fn replace_nop(&mut self) -> Self {
1327 source_info: self.source_info,
1328 kind: mem::replace(&mut self.kind, StatementKind::Nop),
1333 #[derive(Clone, Debug, PartialEq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
1334 pub enum StatementKind<'tcx> {
1335 /// Write the RHS Rvalue to the LHS Place.
1336 Assign(Box<(Place<'tcx>, Rvalue<'tcx>)>),
1338 /// This represents all the reading that a pattern match may do
1339 /// (e.g., inspecting constants and discriminant values), and the
1340 /// kind of pattern it comes from. This is in order to adapt potential
1341 /// error messages to these specific patterns.
1343 /// Note that this also is emitted for regular `let` bindings to ensure that locals that are
1344 /// never accessed still get some sanity checks for, e.g., `let x: ! = ..;`
1345 FakeRead(FakeReadCause, Box<Place<'tcx>>),
1347 /// Write the discriminant for a variant to the enum Place.
1348 SetDiscriminant { place: Box<Place<'tcx>>, variant_index: VariantIdx },
1350 /// Start a live range for the storage of the local.
1353 /// End the current live range for the storage of the local.
1356 /// Executes a piece of inline Assembly. Stored in a Box to keep the size
1357 /// of `StatementKind` low.
1358 LlvmInlineAsm(Box<LlvmInlineAsm<'tcx>>),
1360 /// Retag references in the given place, ensuring they got fresh tags. This is
1361 /// part of the Stacked Borrows model. These statements are currently only interpreted
1362 /// by miri and only generated when "-Z mir-emit-retag" is passed.
1363 /// See <https://internals.rust-lang.org/t/stacked-borrows-an-aliasing-model-for-rust/8153/>
1364 /// for more details.
1365 Retag(RetagKind, Box<Place<'tcx>>),
1367 /// Encodes a user's type ascription. These need to be preserved
1368 /// intact so that NLL can respect them. For example:
1372 /// The effect of this annotation is to relate the type `T_y` of the place `y`
1373 /// to the user-given type `T`. The effect depends on the specified variance:
1375 /// - `Covariant` -- requires that `T_y <: T`
1376 /// - `Contravariant` -- requires that `T_y :> T`
1377 /// - `Invariant` -- requires that `T_y == T`
1378 /// - `Bivariant` -- no effect
1379 AscribeUserType(Box<(Place<'tcx>, UserTypeProjection)>, ty::Variance),
1381 /// No-op. Useful for deleting instructions without affecting statement indices.
1385 /// Describes what kind of retag is to be performed.
1386 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, PartialEq, Eq, HashStable)]
1387 pub enum RetagKind {
1388 /// The initial retag when entering a function.
1390 /// Retag preparing for a two-phase borrow.
1392 /// Retagging raw pointers.
1394 /// A "normal" retag.
1398 /// The `FakeReadCause` describes the type of pattern why a FakeRead statement exists.
1399 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable, PartialEq)]
1400 pub enum FakeReadCause {
1401 /// Inject a fake read of the borrowed input at the end of each guards
1404 /// This should ensure that you cannot change the variant for an enum while
1405 /// you are in the midst of matching on it.
1408 /// `let x: !; match x {}` doesn't generate any read of x so we need to
1409 /// generate a read of x to check that it is initialized and safe.
1412 /// A fake read of the RefWithinGuard version of a bind-by-value variable
1413 /// in a match guard to ensure that it's value hasn't change by the time
1414 /// we create the OutsideGuard version.
1417 /// Officially, the semantics of
1419 /// `let pattern = <expr>;`
1421 /// is that `<expr>` is evaluated into a temporary and then this temporary is
1422 /// into the pattern.
1424 /// However, if we see the simple pattern `let var = <expr>`, we optimize this to
1425 /// evaluate `<expr>` directly into the variable `var`. This is mostly unobservable,
1426 /// but in some cases it can affect the borrow checker, as in #53695.
1427 /// Therefore, we insert a "fake read" here to ensure that we get
1428 /// appropriate errors.
1431 /// If we have an index expression like
1433 /// (*x)[1][{ x = y; 4}]
1435 /// then the first bounds check is invalidated when we evaluate the second
1436 /// index expression. Thus we create a fake borrow of `x` across the second
1437 /// indexer, which will cause a borrow check error.
1441 #[derive(Clone, Debug, PartialEq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
1442 pub struct LlvmInlineAsm<'tcx> {
1443 pub asm: hir::LlvmInlineAsmInner,
1444 pub outputs: Box<[Place<'tcx>]>,
1445 pub inputs: Box<[(Span, Operand<'tcx>)]>,
1448 impl Debug for Statement<'_> {
1449 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1450 use self::StatementKind::*;
1452 Assign(box (ref place, ref rv)) => write!(fmt, "{:?} = {:?}", place, rv),
1453 FakeRead(ref cause, ref place) => write!(fmt, "FakeRead({:?}, {:?})", cause, place),
1454 Retag(ref kind, ref place) => write!(
1458 RetagKind::FnEntry => "[fn entry] ",
1459 RetagKind::TwoPhase => "[2phase] ",
1460 RetagKind::Raw => "[raw] ",
1461 RetagKind::Default => "",
1465 StorageLive(ref place) => write!(fmt, "StorageLive({:?})", place),
1466 StorageDead(ref place) => write!(fmt, "StorageDead({:?})", place),
1467 SetDiscriminant { ref place, variant_index } => {
1468 write!(fmt, "discriminant({:?}) = {:?}", place, variant_index)
1470 LlvmInlineAsm(ref asm) => {
1471 write!(fmt, "llvm_asm!({:?} : {:?} : {:?})", asm.asm, asm.outputs, asm.inputs)
1473 AscribeUserType(box (ref place, ref c_ty), ref variance) => {
1474 write!(fmt, "AscribeUserType({:?}, {:?}, {:?})", place, variance, c_ty)
1476 Nop => write!(fmt, "nop"),
1481 ///////////////////////////////////////////////////////////////////////////
1484 /// A path to a value; something that can be evaluated without
1485 /// changing or disturbing program state.
1486 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, HashStable)]
1487 pub struct Place<'tcx> {
1490 /// projection out of a place (access a field, deref a pointer, etc)
1491 pub projection: &'tcx List<PlaceElem<'tcx>>,
1494 impl<'tcx> rustc_serialize::UseSpecializedDecodable for Place<'tcx> {}
1496 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
1497 #[derive(RustcEncodable, RustcDecodable, HashStable)]
1498 pub enum ProjectionElem<V, T> {
1503 /// These indices are generated by slice patterns. Easiest to explain
1507 /// [X, _, .._, _, _] => { offset: 0, min_length: 4, from_end: false },
1508 /// [_, X, .._, _, _] => { offset: 1, min_length: 4, from_end: false },
1509 /// [_, _, .._, X, _] => { offset: 2, min_length: 4, from_end: true },
1510 /// [_, _, .._, _, X] => { offset: 1, min_length: 4, from_end: true },
1513 /// index or -index (in Python terms), depending on from_end
1515 /// The thing being indexed must be at least this long. For arrays this
1516 /// is always the exact length.
1518 /// Counting backwards from end? This is always false when indexing an
1523 /// These indices are generated by slice patterns.
1525 /// If `from_end` is true `slice[from..slice.len() - to]`.
1526 /// Otherwise `array[from..to]`.
1530 /// Whether `to` counts from the start or end of the array/slice.
1531 /// For `PlaceElem`s this is `true` if and only if the base is a slice.
1532 /// For `ProjectionKind`, this can also be `true` for arrays.
1536 /// "Downcast" to a variant of an ADT. Currently, we only introduce
1537 /// this for ADTs with more than one variant. It may be better to
1538 /// just introduce it always, or always for enums.
1540 /// The included Symbol is the name of the variant, used for printing MIR.
1541 Downcast(Option<Symbol>, VariantIdx),
1544 impl<V, T> ProjectionElem<V, T> {
1545 /// Returns `true` if the target of this projection may refer to a different region of memory
1547 fn is_indirect(&self) -> bool {
1549 Self::Deref => true,
1553 | Self::ConstantIndex { .. }
1554 | Self::Subslice { .. }
1555 | Self::Downcast(_, _) => false,
1560 /// Alias for projections as they appear in places, where the base is a place
1561 /// and the index is a local.
1562 pub type PlaceElem<'tcx> = ProjectionElem<Local, Ty<'tcx>>;
1564 // At least on 64 bit systems, `PlaceElem` should not be larger than two pointers.
1565 #[cfg(target_arch = "x86_64")]
1566 static_assert_size!(PlaceElem<'_>, 16);
1568 /// Alias for projections as they appear in `UserTypeProjection`, where we
1569 /// need neither the `V` parameter for `Index` nor the `T` for `Field`.
1570 pub type ProjectionKind = ProjectionElem<(), ()>;
1572 rustc_index::newtype_index! {
1575 DEBUG_FORMAT = "field[{}]"
1579 #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
1580 pub struct PlaceRef<'tcx> {
1582 pub projection: &'tcx [PlaceElem<'tcx>],
1585 impl<'tcx> Place<'tcx> {
1586 // FIXME change this to a const fn by also making List::empty a const fn.
1587 pub fn return_place() -> Place<'tcx> {
1588 Place { local: RETURN_PLACE, projection: List::empty() }
1591 /// Returns `true` if this `Place` contains a `Deref` projection.
1593 /// If `Place::is_indirect` returns false, the caller knows that the `Place` refers to the
1594 /// same region of memory as its base.
1595 pub fn is_indirect(&self) -> bool {
1596 self.projection.iter().any(|elem| elem.is_indirect())
1599 /// Finds the innermost `Local` from this `Place`, *if* it is either a local itself or
1600 /// a single deref of a local.
1602 // FIXME: can we safely swap the semantics of `fn base_local` below in here instead?
1603 pub fn local_or_deref_local(&self) -> Option<Local> {
1604 match self.as_ref() {
1605 PlaceRef { local, projection: [] }
1606 | PlaceRef { local, projection: [ProjectionElem::Deref] } => Some(local),
1611 /// If this place represents a local variable like `_X` with no
1612 /// projections, return `Some(_X)`.
1613 pub fn as_local(&self) -> Option<Local> {
1614 self.as_ref().as_local()
1617 pub fn as_ref(&self) -> PlaceRef<'tcx> {
1618 PlaceRef { local: self.local, projection: &self.projection }
1622 impl From<Local> for Place<'_> {
1623 fn from(local: Local) -> Self {
1624 Place { local, projection: List::empty() }
1628 impl<'tcx> PlaceRef<'tcx> {
1629 /// Finds the innermost `Local` from this `Place`, *if* it is either a local itself or
1630 /// a single deref of a local.
1632 // FIXME: can we safely swap the semantics of `fn base_local` below in here instead?
1633 pub fn local_or_deref_local(&self) -> Option<Local> {
1635 PlaceRef { local, projection: [] }
1636 | PlaceRef { local, projection: [ProjectionElem::Deref] } => Some(local),
1641 /// If this place represents a local variable like `_X` with no
1642 /// projections, return `Some(_X)`.
1643 pub fn as_local(&self) -> Option<Local> {
1645 PlaceRef { local, projection: [] } => Some(local),
1651 impl Debug for Place<'_> {
1652 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1653 for elem in self.projection.iter().rev() {
1655 ProjectionElem::Downcast(_, _) | ProjectionElem::Field(_, _) => {
1656 write!(fmt, "(").unwrap();
1658 ProjectionElem::Deref => {
1659 write!(fmt, "(*").unwrap();
1661 ProjectionElem::Index(_)
1662 | ProjectionElem::ConstantIndex { .. }
1663 | ProjectionElem::Subslice { .. } => {}
1667 write!(fmt, "{:?}", self.local)?;
1669 for elem in self.projection.iter() {
1671 ProjectionElem::Downcast(Some(name), _index) => {
1672 write!(fmt, " as {})", name)?;
1674 ProjectionElem::Downcast(None, index) => {
1675 write!(fmt, " as variant#{:?})", index)?;
1677 ProjectionElem::Deref => {
1680 ProjectionElem::Field(field, ty) => {
1681 write!(fmt, ".{:?}: {:?})", field.index(), ty)?;
1683 ProjectionElem::Index(ref index) => {
1684 write!(fmt, "[{:?}]", index)?;
1686 ProjectionElem::ConstantIndex { offset, min_length, from_end: false } => {
1687 write!(fmt, "[{:?} of {:?}]", offset, min_length)?;
1689 ProjectionElem::ConstantIndex { offset, min_length, from_end: true } => {
1690 write!(fmt, "[-{:?} of {:?}]", offset, min_length)?;
1692 ProjectionElem::Subslice { from, to, from_end: true } if to == 0 => {
1693 write!(fmt, "[{:?}:]", from)?;
1695 ProjectionElem::Subslice { from, to, from_end: true } if from == 0 => {
1696 write!(fmt, "[:-{:?}]", to)?;
1698 ProjectionElem::Subslice { from, to, from_end: true } => {
1699 write!(fmt, "[{:?}:-{:?}]", from, to)?;
1701 ProjectionElem::Subslice { from, to, from_end: false } => {
1702 write!(fmt, "[{:?}..{:?}]", from, to)?;
1711 ///////////////////////////////////////////////////////////////////////////
1714 rustc_index::newtype_index! {
1715 pub struct SourceScope {
1717 DEBUG_FORMAT = "scope[{}]",
1718 const OUTERMOST_SOURCE_SCOPE = 0,
1722 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
1723 pub struct SourceScopeData {
1725 pub parent_scope: Option<SourceScope>,
1727 /// Crate-local information for this source scope, that can't (and
1728 /// needn't) be tracked across crates.
1729 pub local_data: ClearCrossCrate<SourceScopeLocalData>,
1732 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
1733 pub struct SourceScopeLocalData {
1734 /// An `HirId` with lint levels equivalent to this scope's lint levels.
1735 pub lint_root: hir::HirId,
1736 /// The unsafe block that contains this node.
1740 ///////////////////////////////////////////////////////////////////////////
1743 /// These are values that can appear inside an rvalue. They are intentionally
1744 /// limited to prevent rvalues from being nested in one another.
1745 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable)]
1746 pub enum Operand<'tcx> {
1747 /// Copy: The value must be available for use afterwards.
1749 /// This implies that the type of the place must be `Copy`; this is true
1750 /// by construction during build, but also checked by the MIR type checker.
1753 /// Move: The value (including old borrows of it) will not be used again.
1755 /// Safe for values of all types (modulo future developments towards `?Move`).
1756 /// Correct usage patterns are enforced by the borrow checker for safe code.
1757 /// `Copy` may be converted to `Move` to enable "last-use" optimizations.
1760 /// Synthesizes a constant value.
1761 Constant(Box<Constant<'tcx>>),
1764 impl<'tcx> Debug for Operand<'tcx> {
1765 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1766 use self::Operand::*;
1768 Constant(ref a) => write!(fmt, "{:?}", a),
1769 Copy(ref place) => write!(fmt, "{:?}", place),
1770 Move(ref place) => write!(fmt, "move {:?}", place),
1775 impl<'tcx> Operand<'tcx> {
1776 /// Convenience helper to make a constant that refers to the fn
1777 /// with given `DefId` and substs. Since this is used to synthesize
1778 /// MIR, assumes `user_ty` is None.
1779 pub fn function_handle(
1782 substs: SubstsRef<'tcx>,
1785 let ty = tcx.type_of(def_id).subst(tcx, substs);
1786 Operand::Constant(box Constant {
1789 literal: ty::Const::zero_sized(tcx, ty),
1793 /// Convenience helper to make a literal-like constant from a given scalar value.
1794 /// Since this is used to synthesize MIR, assumes `user_ty` is None.
1795 pub fn const_from_scalar(
1800 ) -> Operand<'tcx> {
1802 let param_env_and_ty = ty::ParamEnv::empty().and(ty);
1804 .layout_of(param_env_and_ty)
1805 .unwrap_or_else(|e| panic!("could not compute layout for {:?}: {:?}", ty, e))
1807 let scalar_size = abi::Size::from_bytes(match val {
1808 Scalar::Raw { size, .. } => size,
1809 _ => panic!("Invalid scalar type {:?}", val),
1811 scalar_size == type_size
1813 Operand::Constant(box Constant {
1816 literal: ty::Const::from_scalar(tcx, val, ty),
1820 pub fn to_copy(&self) -> Self {
1822 Operand::Copy(_) | Operand::Constant(_) => self.clone(),
1823 Operand::Move(place) => Operand::Copy(place),
1827 /// Returns the `Place` that is the target of this `Operand`, or `None` if this `Operand` is a
1829 pub fn place(&self) -> Option<Place<'tcx>> {
1831 Operand::Copy(place) | Operand::Move(place) => Some(*place),
1832 Operand::Constant(_) => None,
1837 ///////////////////////////////////////////////////////////////////////////
1840 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable, PartialEq)]
1841 pub enum Rvalue<'tcx> {
1842 /// x (either a move or copy, depending on type of x)
1846 Repeat(Operand<'tcx>, &'tcx ty::Const<'tcx>),
1849 Ref(Region<'tcx>, BorrowKind, Place<'tcx>),
1851 /// Accessing a thread local static. This is inherently a runtime operation, even if llvm
1852 /// treats it as an access to a static. This `Rvalue` yields a reference to the thread local
1854 ThreadLocalRef(DefId),
1856 /// Create a raw pointer to the given place
1857 /// Can be generated by raw address of expressions (`&raw const x`),
1858 /// or when casting a reference to a raw pointer.
1859 AddressOf(Mutability, Place<'tcx>),
1861 /// length of a `[X]` or `[X;n]` value
1864 Cast(CastKind, Operand<'tcx>, Ty<'tcx>),
1866 BinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
1867 CheckedBinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
1869 NullaryOp(NullOp, Ty<'tcx>),
1870 UnaryOp(UnOp, Operand<'tcx>),
1872 /// Read the discriminant of an ADT.
1874 /// Undefined (i.e., no effort is made to make it defined, but there’s no reason why it cannot
1875 /// be defined to return, say, a 0) if ADT is not an enum.
1876 Discriminant(Place<'tcx>),
1878 /// Creates an aggregate value, like a tuple or struct. This is
1879 /// only needed because we want to distinguish `dest = Foo { x:
1880 /// ..., y: ... }` from `dest.x = ...; dest.y = ...;` in the case
1881 /// that `Foo` has a destructor. These rvalues can be optimized
1882 /// away after type-checking and before lowering.
1883 Aggregate(Box<AggregateKind<'tcx>>, Vec<Operand<'tcx>>),
1886 #[derive(Clone, Copy, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
1889 Pointer(PointerCast),
1892 #[derive(Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
1893 pub enum AggregateKind<'tcx> {
1894 /// The type is of the element
1898 /// The second field is the variant index. It's equal to 0 for struct
1899 /// and union expressions. The fourth field is
1900 /// active field number and is present only for union expressions
1901 /// -- e.g., for a union expression `SomeUnion { c: .. }`, the
1902 /// active field index would identity the field `c`
1903 Adt(&'tcx AdtDef, VariantIdx, SubstsRef<'tcx>, Option<UserTypeAnnotationIndex>, Option<usize>),
1905 Closure(DefId, SubstsRef<'tcx>),
1906 Generator(DefId, SubstsRef<'tcx>, hir::Movability),
1909 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
1911 /// The `+` operator (addition)
1913 /// The `-` operator (subtraction)
1915 /// The `*` operator (multiplication)
1917 /// The `/` operator (division)
1919 /// The `%` operator (modulus)
1921 /// The `^` operator (bitwise xor)
1923 /// The `&` operator (bitwise and)
1925 /// The `|` operator (bitwise or)
1927 /// The `<<` operator (shift left)
1929 /// The `>>` operator (shift right)
1931 /// The `==` operator (equality)
1933 /// The `<` operator (less than)
1935 /// The `<=` operator (less than or equal to)
1937 /// The `!=` operator (not equal to)
1939 /// The `>=` operator (greater than or equal to)
1941 /// The `>` operator (greater than)
1943 /// The `ptr.offset` operator
1948 pub fn is_checkable(self) -> bool {
1951 Add | Sub | Mul | Shl | Shr => true,
1957 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
1959 /// Returns the size of a value of that type
1961 /// Creates a new uninitialized box for a value of that type
1965 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
1967 /// The `!` operator for logical inversion
1969 /// The `-` operator for negation
1973 impl<'tcx> Debug for Rvalue<'tcx> {
1974 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1975 use self::Rvalue::*;
1978 Use(ref place) => write!(fmt, "{:?}", place),
1979 Repeat(ref a, ref b) => {
1980 write!(fmt, "[{:?}; ", a)?;
1981 pretty_print_const(b, fmt, false)?;
1984 Len(ref a) => write!(fmt, "Len({:?})", a),
1985 Cast(ref kind, ref place, ref ty) => {
1986 write!(fmt, "{:?} as {:?} ({:?})", place, ty, kind)
1988 BinaryOp(ref op, ref a, ref b) => write!(fmt, "{:?}({:?}, {:?})", op, a, b),
1989 CheckedBinaryOp(ref op, ref a, ref b) => {
1990 write!(fmt, "Checked{:?}({:?}, {:?})", op, a, b)
1992 UnaryOp(ref op, ref a) => write!(fmt, "{:?}({:?})", op, a),
1993 Discriminant(ref place) => write!(fmt, "discriminant({:?})", place),
1994 NullaryOp(ref op, ref t) => write!(fmt, "{:?}({:?})", op, t),
1995 ThreadLocalRef(did) => ty::tls::with(|tcx| {
1996 let muta = tcx.static_mutability(did).unwrap().prefix_str();
1997 write!(fmt, "&/*tls*/ {}{}", muta, tcx.def_path_str(did))
1999 Ref(region, borrow_kind, ref place) => {
2000 let kind_str = match borrow_kind {
2001 BorrowKind::Shared => "",
2002 BorrowKind::Shallow => "shallow ",
2003 BorrowKind::Mut { .. } | BorrowKind::Unique => "mut ",
2006 // When printing regions, add trailing space if necessary.
2007 let print_region = ty::tls::with(|tcx| {
2008 tcx.sess.verbose() || tcx.sess.opts.debugging_opts.identify_regions
2010 let region = if print_region {
2011 let mut region = region.to_string();
2012 if !region.is_empty() {
2017 // Do not even print 'static
2020 write!(fmt, "&{}{}{:?}", region, kind_str, place)
2023 AddressOf(mutability, ref place) => {
2024 let kind_str = match mutability {
2025 Mutability::Mut => "mut",
2026 Mutability::Not => "const",
2029 write!(fmt, "&raw {} {:?}", kind_str, place)
2032 Aggregate(ref kind, ref places) => {
2033 let fmt_tuple = |fmt: &mut Formatter<'_>, name: &str| {
2034 let mut tuple_fmt = fmt.debug_tuple(name);
2035 for place in places {
2036 tuple_fmt.field(place);
2042 AggregateKind::Array(_) => write!(fmt, "{:?}", places),
2044 AggregateKind::Tuple => {
2045 if places.is_empty() {
2052 AggregateKind::Adt(adt_def, variant, substs, _user_ty, _) => {
2053 let variant_def = &adt_def.variants[variant];
2055 let name = ty::tls::with(|tcx| {
2056 let mut name = String::new();
2057 let substs = tcx.lift(&substs).expect("could not lift for printing");
2058 FmtPrinter::new(tcx, &mut name, Namespace::ValueNS)
2059 .print_def_path(variant_def.def_id, substs)?;
2063 match variant_def.ctor_kind {
2064 CtorKind::Const => fmt.write_str(&name),
2065 CtorKind::Fn => fmt_tuple(fmt, &name),
2066 CtorKind::Fictive => {
2067 let mut struct_fmt = fmt.debug_struct(&name);
2068 for (field, place) in variant_def.fields.iter().zip(places) {
2069 struct_fmt.field(&field.ident.as_str(), place);
2076 AggregateKind::Closure(def_id, substs) => ty::tls::with(|tcx| {
2077 if let Some(def_id) = def_id.as_local() {
2078 let hir_id = tcx.hir().as_local_hir_id(def_id);
2079 let name = if tcx.sess.opts.debugging_opts.span_free_formats {
2080 let substs = tcx.lift(&substs).unwrap();
2083 tcx.def_path_str_with_substs(def_id.to_def_id(), substs),
2086 let span = tcx.hir().span(hir_id);
2087 format!("[closure@{}]", tcx.sess.source_map().span_to_string(span))
2089 let mut struct_fmt = fmt.debug_struct(&name);
2091 if let Some(upvars) = tcx.upvars_mentioned(def_id) {
2092 for (&var_id, place) in upvars.keys().zip(places) {
2093 let var_name = tcx.hir().name(var_id);
2094 struct_fmt.field(&var_name.as_str(), place);
2100 write!(fmt, "[closure]")
2104 AggregateKind::Generator(def_id, _, _) => ty::tls::with(|tcx| {
2105 if let Some(def_id) = def_id.as_local() {
2106 let hir_id = tcx.hir().as_local_hir_id(def_id);
2107 let name = format!("[generator@{:?}]", tcx.hir().span(hir_id));
2108 let mut struct_fmt = fmt.debug_struct(&name);
2110 if let Some(upvars) = tcx.upvars_mentioned(def_id) {
2111 for (&var_id, place) in upvars.keys().zip(places) {
2112 let var_name = tcx.hir().name(var_id);
2113 struct_fmt.field(&var_name.as_str(), place);
2119 write!(fmt, "[generator]")
2128 ///////////////////////////////////////////////////////////////////////////
2131 /// Two constants are equal if they are the same constant. Note that
2132 /// this does not necessarily mean that they are "==" in Rust -- in
2133 /// particular one must be wary of `NaN`!
2135 #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, HashStable)]
2136 pub struct Constant<'tcx> {
2139 /// Optional user-given type: for something like
2140 /// `collect::<Vec<_>>`, this would be present and would
2141 /// indicate that `Vec<_>` was explicitly specified.
2143 /// Needed for NLL to impose user-given type constraints.
2144 pub user_ty: Option<UserTypeAnnotationIndex>,
2146 pub literal: &'tcx ty::Const<'tcx>,
2149 impl Constant<'tcx> {
2150 pub fn check_static_ptr(&self, tcx: TyCtxt<'_>) -> Option<DefId> {
2151 match self.literal.val.try_to_scalar() {
2152 Some(Scalar::Ptr(ptr)) => match tcx.global_alloc(ptr.alloc_id) {
2153 GlobalAlloc::Static(def_id) => {
2154 assert!(!tcx.is_thread_local_static(def_id));
2164 /// A collection of projections into user types.
2166 /// They are projections because a binding can occur a part of a
2167 /// parent pattern that has been ascribed a type.
2169 /// Its a collection because there can be multiple type ascriptions on
2170 /// the path from the root of the pattern down to the binding itself.
2175 /// struct S<'a>((i32, &'a str), String);
2176 /// let S((_, w): (i32, &'static str), _): S = ...;
2177 /// // ------ ^^^^^^^^^^^^^^^^^^^ (1)
2178 /// // --------------------------------- ^ (2)
2181 /// The highlights labelled `(1)` show the subpattern `(_, w)` being
2182 /// ascribed the type `(i32, &'static str)`.
2184 /// The highlights labelled `(2)` show the whole pattern being
2185 /// ascribed the type `S`.
2187 /// In this example, when we descend to `w`, we will have built up the
2188 /// following two projected types:
2190 /// * base: `S`, projection: `(base.0).1`
2191 /// * base: `(i32, &'static str)`, projection: `base.1`
2193 /// The first will lead to the constraint `w: &'1 str` (for some
2194 /// inferred region `'1`). The second will lead to the constraint `w:
2196 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
2197 pub struct UserTypeProjections {
2198 pub contents: Vec<(UserTypeProjection, Span)>,
2201 impl<'tcx> UserTypeProjections {
2202 pub fn none() -> Self {
2203 UserTypeProjections { contents: vec![] }
2206 pub fn is_empty(&self) -> bool {
2207 self.contents.is_empty()
2210 pub fn from_projections(projs: impl Iterator<Item = (UserTypeProjection, Span)>) -> Self {
2211 UserTypeProjections { contents: projs.collect() }
2214 pub fn projections_and_spans(
2216 ) -> impl Iterator<Item = &(UserTypeProjection, Span)> + ExactSizeIterator {
2217 self.contents.iter()
2220 pub fn projections(&self) -> impl Iterator<Item = &UserTypeProjection> + ExactSizeIterator {
2221 self.contents.iter().map(|&(ref user_type, _span)| user_type)
2224 pub fn push_projection(mut self, user_ty: &UserTypeProjection, span: Span) -> Self {
2225 self.contents.push((user_ty.clone(), span));
2231 mut f: impl FnMut(UserTypeProjection) -> UserTypeProjection,
2233 self.contents = self.contents.drain(..).map(|(proj, span)| (f(proj), span)).collect();
2237 pub fn index(self) -> Self {
2238 self.map_projections(|pat_ty_proj| pat_ty_proj.index())
2241 pub fn subslice(self, from: u32, to: u32) -> Self {
2242 self.map_projections(|pat_ty_proj| pat_ty_proj.subslice(from, to))
2245 pub fn deref(self) -> Self {
2246 self.map_projections(|pat_ty_proj| pat_ty_proj.deref())
2249 pub fn leaf(self, field: Field) -> Self {
2250 self.map_projections(|pat_ty_proj| pat_ty_proj.leaf(field))
2253 pub fn variant(self, adt_def: &'tcx AdtDef, variant_index: VariantIdx, field: Field) -> Self {
2254 self.map_projections(|pat_ty_proj| pat_ty_proj.variant(adt_def, variant_index, field))
2258 /// Encodes the effect of a user-supplied type annotation on the
2259 /// subcomponents of a pattern. The effect is determined by applying the
2260 /// given list of proejctions to some underlying base type. Often,
2261 /// the projection element list `projs` is empty, in which case this
2262 /// directly encodes a type in `base`. But in the case of complex patterns with
2263 /// subpatterns and bindings, we want to apply only a *part* of the type to a variable,
2264 /// in which case the `projs` vector is used.
2268 /// * `let x: T = ...` -- here, the `projs` vector is empty.
2270 /// * `let (x, _): T = ...` -- here, the `projs` vector would contain
2271 /// `field[0]` (aka `.0`), indicating that the type of `s` is
2272 /// determined by finding the type of the `.0` field from `T`.
2273 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable, PartialEq)]
2274 pub struct UserTypeProjection {
2275 pub base: UserTypeAnnotationIndex,
2276 pub projs: Vec<ProjectionKind>,
2279 impl Copy for ProjectionKind {}
2281 impl UserTypeProjection {
2282 pub(crate) fn index(mut self) -> Self {
2283 self.projs.push(ProjectionElem::Index(()));
2287 pub(crate) fn subslice(mut self, from: u32, to: u32) -> Self {
2288 self.projs.push(ProjectionElem::Subslice { from, to, from_end: true });
2292 pub(crate) fn deref(mut self) -> Self {
2293 self.projs.push(ProjectionElem::Deref);
2297 pub(crate) fn leaf(mut self, field: Field) -> Self {
2298 self.projs.push(ProjectionElem::Field(field, ()));
2302 pub(crate) fn variant(
2305 variant_index: VariantIdx,
2308 self.projs.push(ProjectionElem::Downcast(
2309 Some(adt_def.variants[variant_index].ident.name),
2312 self.projs.push(ProjectionElem::Field(field, ()));
2317 CloneTypeFoldableAndLiftImpls! { ProjectionKind, }
2319 impl<'tcx> TypeFoldable<'tcx> for UserTypeProjection {
2320 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
2321 use crate::mir::ProjectionElem::*;
2323 let base = self.base.fold_with(folder);
2324 let projs: Vec<_> = self
2327 .map(|&elem| match elem {
2329 Field(f, ()) => Field(f, ()),
2330 Index(()) => Index(()),
2331 Downcast(symbol, variantidx) => Downcast(symbol, variantidx),
2332 ConstantIndex { offset, min_length, from_end } => {
2333 ConstantIndex { offset, min_length, from_end }
2335 Subslice { from, to, from_end } => Subslice { from, to, from_end },
2339 UserTypeProjection { base, projs }
2342 fn super_visit_with<Vs: TypeVisitor<'tcx>>(&self, visitor: &mut Vs) -> bool {
2343 self.base.visit_with(visitor)
2344 // Note: there's nothing in `self.proj` to visit.
2348 rustc_index::newtype_index! {
2349 pub struct Promoted {
2351 DEBUG_FORMAT = "promoted[{}]"
2355 impl<'tcx> Debug for Constant<'tcx> {
2356 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2357 write!(fmt, "{}", self)
2361 impl<'tcx> Display for Constant<'tcx> {
2362 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2363 write!(fmt, "const ")?;
2364 pretty_print_const(self.literal, fmt, true)
2368 fn pretty_print_const(
2369 c: &ty::Const<'tcx>,
2370 fmt: &mut Formatter<'_>,
2373 use crate::ty::print::PrettyPrinter;
2374 ty::tls::with(|tcx| {
2375 let literal = tcx.lift(&c).unwrap();
2376 let mut cx = FmtPrinter::new(tcx, fmt, Namespace::ValueNS);
2377 cx.print_alloc_ids = true;
2378 cx.pretty_print_const(literal, print_types)?;
2383 impl<'tcx> graph::DirectedGraph for Body<'tcx> {
2384 type Node = BasicBlock;
2387 impl<'tcx> graph::WithNumNodes for Body<'tcx> {
2389 fn num_nodes(&self) -> usize {
2390 self.basic_blocks.len()
2394 impl<'tcx> graph::WithStartNode for Body<'tcx> {
2396 fn start_node(&self) -> Self::Node {
2401 impl<'tcx> graph::WithSuccessors for Body<'tcx> {
2403 fn successors(&self, node: Self::Node) -> <Self as GraphSuccessors<'_>>::Iter {
2404 self.basic_blocks[node].terminator().successors().cloned()
2408 impl<'a, 'b> graph::GraphSuccessors<'b> for Body<'a> {
2409 type Item = BasicBlock;
2410 type Iter = iter::Cloned<Successors<'b>>;
2413 impl graph::GraphPredecessors<'graph> for Body<'tcx> {
2414 type Item = BasicBlock;
2415 type Iter = smallvec::IntoIter<[BasicBlock; 4]>;
2418 impl graph::WithPredecessors for Body<'tcx> {
2420 fn predecessors(&self, node: Self::Node) -> <Self as graph::GraphPredecessors<'_>>::Iter {
2421 self.predecessors()[node].clone().into_iter()
2425 /// `Location` represents the position of the start of the statement; or, if
2426 /// `statement_index` equals the number of statements, then the start of the
2428 #[derive(Copy, Clone, PartialEq, Eq, Hash, Ord, PartialOrd, HashStable)]
2429 pub struct Location {
2430 /// The block that the location is within.
2431 pub block: BasicBlock,
2433 pub statement_index: usize,
2436 impl fmt::Debug for Location {
2437 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2438 write!(fmt, "{:?}[{}]", self.block, self.statement_index)
2443 pub const START: Location = Location { block: START_BLOCK, statement_index: 0 };
2445 /// Returns the location immediately after this one within the enclosing block.
2447 /// Note that if this location represents a terminator, then the
2448 /// resulting location would be out of bounds and invalid.
2449 pub fn successor_within_block(&self) -> Location {
2450 Location { block: self.block, statement_index: self.statement_index + 1 }
2453 /// Returns `true` if `other` is earlier in the control flow graph than `self`.
2454 pub fn is_predecessor_of<'tcx>(&self, other: Location, body: &Body<'tcx>) -> bool {
2455 // If we are in the same block as the other location and are an earlier statement
2456 // then we are a predecessor of `other`.
2457 if self.block == other.block && self.statement_index < other.statement_index {
2461 let predecessors = body.predecessors();
2463 // If we're in another block, then we want to check that block is a predecessor of `other`.
2464 let mut queue: Vec<BasicBlock> = predecessors[other.block].to_vec();
2465 let mut visited = FxHashSet::default();
2467 while let Some(block) = queue.pop() {
2468 // If we haven't visited this block before, then make sure we visit it's predecessors.
2469 if visited.insert(block) {
2470 queue.extend(predecessors[block].iter().cloned());
2475 // If we found the block that `self` is in, then we are a predecessor of `other` (since
2476 // we found that block by looking at the predecessors of `other`).
2477 if self.block == block {
2485 pub fn dominates(&self, other: Location, dominators: &Dominators<BasicBlock>) -> bool {
2486 if self.block == other.block {
2487 self.statement_index <= other.statement_index
2489 dominators.is_dominated_by(other.block, self.block)
2494 /// Coverage data associated with each function (MIR) instrumented with coverage counters, when
2495 /// compiled with `-Zinstrument_coverage`. The query `tcx.coverage_data(DefId)` computes these
2496 /// values on demand (during code generation). This query is only valid after executing the MIR pass
2497 /// `InstrumentCoverage`.
2498 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2499 pub struct CoverageData {
2500 /// A hash value that can be used by the consumer of the coverage profile data to detect
2501 /// changes to the instrumented source of the associated MIR body (typically, for an
2502 /// individual function).
2505 /// The total number of coverage region counters added to the MIR `Body`.
2506 pub num_counters: u32,