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::{Allocation, ConstValue, GlobalAlloc, Scalar};
6 use crate::mir::visit::MirVisitable;
7 use crate::ty::adjustment::PointerCast;
8 use crate::ty::codec::{TyDecoder, TyEncoder};
9 use crate::ty::fold::{TypeFoldable, TypeFolder, TypeVisitor};
10 use crate::ty::print::{FmtPrinter, Printer};
11 use crate::ty::subst::{Subst, SubstsRef};
13 self, AdtDef, CanonicalUserTypeAnnotations, List, Region, Ty, TyCtxt, UserTypeAnnotationIndex,
16 use rustc_hir::def::{CtorKind, Namespace};
17 use rustc_hir::def_id::DefId;
18 use rustc_hir::{self, GeneratorKind};
19 use rustc_target::abi::VariantIdx;
21 use polonius_engine::Atom;
22 pub use rustc_ast::ast::Mutability;
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_index::bit_set::BitMatrix;
27 use rustc_index::vec::{Idx, IndexVec};
28 use rustc_macros::HashStable;
29 use rustc_serialize::{Decodable, Encodable};
30 use rustc_span::symbol::Symbol;
31 use rustc_span::{Span, DUMMY_SP};
32 use rustc_target::abi;
33 use rustc_target::asm::InlineAsmRegOrRegClass;
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::*;
50 pub use terminator::*;
56 type LocalDecls<'tcx> = IndexVec<Local, LocalDecl<'tcx>>;
58 pub trait HasLocalDecls<'tcx> {
59 fn local_decls(&self) -> &LocalDecls<'tcx>;
62 impl<'tcx> HasLocalDecls<'tcx> for LocalDecls<'tcx> {
63 fn local_decls(&self) -> &LocalDecls<'tcx> {
68 impl<'tcx> HasLocalDecls<'tcx> for Body<'tcx> {
69 fn local_decls(&self) -> &LocalDecls<'tcx> {
74 /// The various "big phases" that MIR goes through.
76 /// Warning: ordering of variants is significant.
77 #[derive(Copy, Clone, TyEncodable, TyDecodable, Debug, PartialEq, Eq, PartialOrd, Ord)]
88 /// Gets the index of the current MirPhase within the set of all `MirPhase`s.
89 pub fn phase_index(&self) -> usize {
94 /// The lowered representation of a single function.
95 #[derive(Clone, TyEncodable, TyDecodable, Debug, HashStable, TypeFoldable)]
96 pub struct Body<'tcx> {
97 /// A list of basic blocks. References to basic block use a newtyped index type `BasicBlock`
98 /// that indexes into this vector.
99 basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
101 /// Records how far through the "desugaring and optimization" process this particular
102 /// MIR has traversed. This is particularly useful when inlining, since in that context
103 /// we instantiate the promoted constants and add them to our promoted vector -- but those
104 /// promoted items have already been optimized, whereas ours have not. This field allows
105 /// us to see the difference and forego optimization on the inlined promoted items.
108 /// A list of source scopes; these are referenced by statements
109 /// and used for debuginfo. Indexed by a `SourceScope`.
110 pub source_scopes: IndexVec<SourceScope, SourceScopeData>,
112 /// The yield type of the function, if it is a generator.
113 pub yield_ty: Option<Ty<'tcx>>,
115 /// Generator drop glue.
116 pub generator_drop: Option<Box<Body<'tcx>>>,
118 /// The layout of a generator. Produced by the state transformation.
119 pub generator_layout: Option<GeneratorLayout<'tcx>>,
121 /// If this is a generator then record the type of source expression that caused this generator
123 pub generator_kind: Option<GeneratorKind>,
125 /// Declarations of locals.
127 /// The first local is the return value pointer, followed by `arg_count`
128 /// locals for the function arguments, followed by any user-declared
129 /// variables and temporaries.
130 pub local_decls: LocalDecls<'tcx>,
132 /// User type annotations.
133 pub user_type_annotations: CanonicalUserTypeAnnotations<'tcx>,
135 /// The number of arguments this function takes.
137 /// Starting at local 1, `arg_count` locals will be provided by the caller
138 /// and can be assumed to be initialized.
140 /// If this MIR was built for a constant, this will be 0.
141 pub arg_count: usize,
143 /// Mark an argument local (which must be a tuple) as getting passed as
144 /// its individual components at the LLVM level.
146 /// This is used for the "rust-call" ABI.
147 pub spread_arg: Option<Local>,
149 /// Debug information pertaining to user variables, including captures.
150 pub var_debug_info: Vec<VarDebugInfo<'tcx>>,
152 /// A span representing this MIR, for error reporting.
155 /// Constants that are required to evaluate successfully for this MIR to be well-formed.
156 /// We hold in this field all the constants we are not able to evaluate yet.
157 pub required_consts: Vec<Constant<'tcx>>,
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
163 /// the 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 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 generator_kind: Option<GeneratorKind>,
183 // We need `arg_count` locals, and one for the return place.
185 local_decls.len() > arg_count,
186 "expected at least {} locals, got {}",
192 phase: MirPhase::Build,
196 generator_drop: None,
197 generator_layout: None,
200 user_type_annotations,
205 required_consts: Vec::new(),
206 ignore_interior_mut_in_const_validation: false,
207 predecessor_cache: PredecessorCache::new(),
211 /// Returns a partially initialized MIR body containing only a list of basic blocks.
213 /// The returned MIR contains no `LocalDecl`s (even for the return place) or source scopes. It
214 /// is only useful for testing but cannot be `#[cfg(test)]` because it is used in a different
216 pub fn new_cfg_only(basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>) -> Self {
218 phase: MirPhase::Build,
220 source_scopes: IndexVec::new(),
222 generator_drop: None,
223 generator_layout: None,
224 local_decls: IndexVec::new(),
225 user_type_annotations: IndexVec::new(),
229 required_consts: Vec::new(),
230 generator_kind: None,
231 var_debug_info: Vec::new(),
232 ignore_interior_mut_in_const_validation: false,
233 predecessor_cache: PredecessorCache::new(),
238 pub fn basic_blocks(&self) -> &IndexVec<BasicBlock, BasicBlockData<'tcx>> {
243 pub fn basic_blocks_mut(&mut self) -> &mut IndexVec<BasicBlock, BasicBlockData<'tcx>> {
244 // Because the user could mutate basic block terminators via this reference, we need to
245 // invalidate the predecessor cache.
247 // FIXME: Use a finer-grained API for this, so only transformations that alter terminators
248 // invalidate the predecessor cache.
249 self.predecessor_cache.invalidate();
250 &mut self.basic_blocks
254 pub fn basic_blocks_and_local_decls_mut(
256 ) -> (&mut IndexVec<BasicBlock, BasicBlockData<'tcx>>, &mut LocalDecls<'tcx>) {
257 self.predecessor_cache.invalidate();
258 (&mut self.basic_blocks, &mut self.local_decls)
262 pub fn basic_blocks_local_decls_mut_and_var_debug_info(
265 &mut IndexVec<BasicBlock, BasicBlockData<'tcx>>,
266 &mut LocalDecls<'tcx>,
267 &mut Vec<VarDebugInfo<'tcx>>,
269 self.predecessor_cache.invalidate();
270 (&mut self.basic_blocks, &mut self.local_decls, &mut self.var_debug_info)
273 /// Returns `true` if a cycle exists in the control-flow graph that is reachable from the
275 pub fn is_cfg_cyclic(&self) -> bool {
276 graph::is_cyclic(self)
280 pub fn local_kind(&self, local: Local) -> LocalKind {
281 let index = local.as_usize();
284 self.local_decls[local].mutability == Mutability::Mut,
285 "return place should be mutable"
288 LocalKind::ReturnPointer
289 } else if index < self.arg_count + 1 {
291 } else if self.local_decls[local].is_user_variable() {
298 /// Returns an iterator over all temporaries.
300 pub fn temps_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
301 (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
302 let local = Local::new(index);
303 if self.local_decls[local].is_user_variable() { None } else { Some(local) }
307 /// Returns an iterator over all user-declared locals.
309 pub fn vars_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
310 (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
311 let local = Local::new(index);
312 self.local_decls[local].is_user_variable().then_some(local)
316 /// Returns an iterator over all user-declared mutable locals.
318 pub fn mut_vars_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
319 (self.arg_count + 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() && decl.mutability == Mutability::Mut {
330 /// Returns an iterator over all user-declared mutable arguments and locals.
332 pub fn mut_vars_and_args_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
333 (1..self.local_decls.len()).filter_map(move |index| {
334 let local = Local::new(index);
335 let decl = &self.local_decls[local];
336 if (decl.is_user_variable() || index < self.arg_count + 1)
337 && decl.mutability == Mutability::Mut
346 /// Returns an iterator over all function arguments.
348 pub fn args_iter(&self) -> impl Iterator<Item = Local> + ExactSizeIterator {
349 let arg_count = self.arg_count;
350 (1..arg_count + 1).map(Local::new)
353 /// Returns an iterator over all user-defined variables and compiler-generated temporaries (all
354 /// locals that are neither arguments nor the return place).
356 pub fn vars_and_temps_iter(&self) -> impl Iterator<Item = Local> + ExactSizeIterator {
357 let arg_count = self.arg_count;
358 let local_count = self.local_decls.len();
359 (arg_count + 1..local_count).map(Local::new)
362 /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
363 /// invalidating statement indices in `Location`s.
364 pub fn make_statement_nop(&mut self, location: Location) {
365 let block = &mut self.basic_blocks[location.block];
366 debug_assert!(location.statement_index < block.statements.len());
367 block.statements[location.statement_index].make_nop()
370 /// Returns the source info associated with `location`.
371 pub fn source_info(&self, location: Location) -> &SourceInfo {
372 let block = &self[location.block];
373 let stmts = &block.statements;
374 let idx = location.statement_index;
375 if idx < stmts.len() {
376 &stmts[idx].source_info
378 assert_eq!(idx, stmts.len());
379 &block.terminator().source_info
383 /// Checks if `sub` is a sub scope of `sup`
384 pub fn is_sub_scope(&self, mut sub: SourceScope, sup: SourceScope) -> bool {
386 match self.source_scopes[sub].parent_scope {
387 None => return false,
394 /// Returns the return type; it always return first element from `local_decls` array.
396 pub fn return_ty(&self) -> Ty<'tcx> {
397 self.local_decls[RETURN_PLACE].ty
400 /// Gets the location of the terminator for the given block.
402 pub fn terminator_loc(&self, bb: BasicBlock) -> Location {
403 Location { block: bb, statement_index: self[bb].statements.len() }
407 pub fn predecessors(&self) -> impl std::ops::Deref<Target = Predecessors> + '_ {
408 self.predecessor_cache.compute(&self.basic_blocks)
412 pub fn dominators(&self) -> Dominators<BasicBlock> {
417 #[derive(Copy, Clone, PartialEq, Eq, Debug, TyEncodable, TyDecodable, HashStable)]
420 /// Unsafe because of a PushUnsafeBlock
422 /// Unsafe because of an unsafe fn
424 /// Unsafe because of an `unsafe` block
425 ExplicitUnsafe(hir::HirId),
428 impl<'tcx> Index<BasicBlock> for Body<'tcx> {
429 type Output = BasicBlockData<'tcx>;
432 fn index(&self, index: BasicBlock) -> &BasicBlockData<'tcx> {
433 &self.basic_blocks()[index]
437 impl<'tcx> IndexMut<BasicBlock> for Body<'tcx> {
439 fn index_mut(&mut self, index: BasicBlock) -> &mut BasicBlockData<'tcx> {
440 &mut self.basic_blocks_mut()[index]
444 #[derive(Copy, Clone, Debug, HashStable, TypeFoldable)]
445 pub enum ClearCrossCrate<T> {
450 impl<T> ClearCrossCrate<T> {
451 pub fn as_ref(&self) -> ClearCrossCrate<&T> {
453 ClearCrossCrate::Clear => ClearCrossCrate::Clear,
454 ClearCrossCrate::Set(v) => ClearCrossCrate::Set(v),
458 pub fn assert_crate_local(self) -> T {
460 ClearCrossCrate::Clear => bug!("unwrapping cross-crate data"),
461 ClearCrossCrate::Set(v) => v,
466 const TAG_CLEAR_CROSS_CRATE_CLEAR: u8 = 0;
467 const TAG_CLEAR_CROSS_CRATE_SET: u8 = 1;
469 impl<'tcx, E: TyEncoder<'tcx>, T: Encodable<E>> Encodable<E> for ClearCrossCrate<T> {
471 fn encode(&self, e: &mut E) -> Result<(), E::Error> {
472 if E::CLEAR_CROSS_CRATE {
477 ClearCrossCrate::Clear => TAG_CLEAR_CROSS_CRATE_CLEAR.encode(e),
478 ClearCrossCrate::Set(ref val) => {
479 TAG_CLEAR_CROSS_CRATE_SET.encode(e)?;
485 impl<'tcx, D: TyDecoder<'tcx>, T: Decodable<D>> Decodable<D> for ClearCrossCrate<T> {
487 fn decode(d: &mut D) -> Result<ClearCrossCrate<T>, D::Error> {
488 if D::CLEAR_CROSS_CRATE {
489 return Ok(ClearCrossCrate::Clear);
492 let discr = u8::decode(d)?;
495 TAG_CLEAR_CROSS_CRATE_CLEAR => Ok(ClearCrossCrate::Clear),
496 TAG_CLEAR_CROSS_CRATE_SET => {
497 let val = T::decode(d)?;
498 Ok(ClearCrossCrate::Set(val))
500 tag => Err(d.error(&format!("Invalid tag for ClearCrossCrate: {:?}", tag))),
505 /// Grouped information about the source code origin of a MIR entity.
506 /// Intended to be inspected by diagnostics and debuginfo.
507 /// Most passes can work with it as a whole, within a single function.
508 // The unofficial Cranelift backend, at least as of #65828, needs `SourceInfo` to implement `Eq` and
509 // `Hash`. Please ping @bjorn3 if removing them.
510 #[derive(Copy, Clone, Debug, Eq, PartialEq, TyEncodable, TyDecodable, Hash, HashStable)]
511 pub struct SourceInfo {
512 /// The source span for the AST pertaining to this MIR entity.
515 /// The source scope, keeping track of which bindings can be
516 /// seen by debuginfo, active lint levels, `unsafe {...}`, etc.
517 pub scope: SourceScope,
522 pub fn outermost(span: Span) -> Self {
523 SourceInfo { span, scope: OUTERMOST_SOURCE_SCOPE }
527 ///////////////////////////////////////////////////////////////////////////
530 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, TyEncodable, TyDecodable)]
531 #[derive(HashStable)]
532 pub enum BorrowKind {
533 /// Data must be immutable and is aliasable.
536 /// The immediately borrowed place must be immutable, but projections from
537 /// it don't need to be. For example, a shallow borrow of `a.b` doesn't
538 /// conflict with a mutable borrow of `a.b.c`.
540 /// This is used when lowering matches: when matching on a place we want to
541 /// ensure that place have the same value from the start of the match until
542 /// an arm is selected. This prevents this code from compiling:
544 /// let mut x = &Some(0);
547 /// Some(_) if { x = &None; false } => (),
551 /// This can't be a shared borrow because mutably borrowing (*x as Some).0
552 /// should not prevent `if let None = x { ... }`, for example, because the
553 /// mutating `(*x as Some).0` can't affect the discriminant of `x`.
554 /// We can also report errors with this kind of borrow differently.
557 /// Data must be immutable but not aliasable. This kind of borrow
558 /// cannot currently be expressed by the user and is used only in
559 /// implicit closure bindings. It is needed when the closure is
560 /// borrowing or mutating a mutable referent, e.g.:
562 /// let x: &mut isize = ...;
563 /// let y = || *x += 5;
565 /// If we were to try to translate this closure into a more explicit
566 /// form, we'd encounter an error with the code as written:
568 /// struct Env { x: & &mut isize }
569 /// let x: &mut isize = ...;
570 /// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn
571 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
573 /// This is then illegal because you cannot mutate an `&mut` found
574 /// in an aliasable location. To solve, you'd have to translate with
575 /// an `&mut` borrow:
577 /// struct Env { x: & &mut isize }
578 /// let x: &mut isize = ...;
579 /// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
580 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
582 /// Now the assignment to `**env.x` is legal, but creating a
583 /// mutable pointer to `x` is not because `x` is not mutable. We
584 /// could fix this by declaring `x` as `let mut x`. This is ok in
585 /// user code, if awkward, but extra weird for closures, since the
586 /// borrow is hidden.
588 /// So we introduce a "unique imm" borrow -- the referent is
589 /// immutable, but not aliasable. This solves the problem. For
590 /// simplicity, we don't give users the way to express this
591 /// borrow, it's just used when translating closures.
594 /// Data is mutable and not aliasable.
596 /// `true` if this borrow arose from method-call auto-ref
597 /// (i.e., `adjustment::Adjust::Borrow`).
598 allow_two_phase_borrow: bool,
603 pub fn allows_two_phase_borrow(&self) -> bool {
605 BorrowKind::Shared | BorrowKind::Shallow | BorrowKind::Unique => false,
606 BorrowKind::Mut { allow_two_phase_borrow } => allow_two_phase_borrow,
611 ///////////////////////////////////////////////////////////////////////////
612 // Variables and temps
614 rustc_index::newtype_index! {
617 DEBUG_FORMAT = "_{}",
618 const RETURN_PLACE = 0,
622 impl Atom for Local {
623 fn index(self) -> usize {
628 /// Classifies locals into categories. See `Body::local_kind`.
629 #[derive(PartialEq, Eq, Debug, HashStable)]
631 /// User-declared variable binding.
633 /// Compiler-introduced temporary.
635 /// Function argument.
637 /// Location of function's return value.
641 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable)]
642 pub struct VarBindingForm<'tcx> {
643 /// Is variable bound via `x`, `mut x`, `ref x`, or `ref mut x`?
644 pub binding_mode: ty::BindingMode,
645 /// If an explicit type was provided for this variable binding,
646 /// this holds the source Span of that type.
648 /// NOTE: if you want to change this to a `HirId`, be wary that
649 /// doing so breaks incremental compilation (as of this writing),
650 /// while a `Span` does not cause our tests to fail.
651 pub opt_ty_info: Option<Span>,
652 /// Place of the RHS of the =, or the subject of the `match` where this
653 /// variable is initialized. None in the case of `let PATTERN;`.
654 /// Some((None, ..)) in the case of and `let [mut] x = ...` because
655 /// (a) the right-hand side isn't evaluated as a place expression.
656 /// (b) it gives a way to separate this case from the remaining cases
658 pub opt_match_place: Option<(Option<Place<'tcx>>, Span)>,
659 /// The span of the pattern in which this variable was bound.
663 #[derive(Clone, Debug, TyEncodable, TyDecodable)]
664 pub enum BindingForm<'tcx> {
665 /// This is a binding for a non-`self` binding, or a `self` that has an explicit type.
666 Var(VarBindingForm<'tcx>),
667 /// Binding for a `self`/`&self`/`&mut self` binding where the type is implicit.
668 ImplicitSelf(ImplicitSelfKind),
669 /// Reference used in a guard expression to ensure immutability.
673 /// Represents what type of implicit self a function has, if any.
674 #[derive(Clone, Copy, PartialEq, Debug, TyEncodable, TyDecodable, HashStable)]
675 pub enum ImplicitSelfKind {
676 /// Represents a `fn x(self);`.
678 /// Represents a `fn x(mut self);`.
680 /// Represents a `fn x(&self);`.
682 /// Represents a `fn x(&mut self);`.
684 /// Represents when a function does not have a self argument or
685 /// when a function has a `self: X` argument.
689 CloneTypeFoldableAndLiftImpls! { BindingForm<'tcx>, }
691 mod binding_form_impl {
692 use crate::ich::StableHashingContext;
693 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
695 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for super::BindingForm<'tcx> {
696 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
697 use super::BindingForm::*;
698 ::std::mem::discriminant(self).hash_stable(hcx, hasher);
701 Var(binding) => binding.hash_stable(hcx, hasher),
702 ImplicitSelf(kind) => kind.hash_stable(hcx, hasher),
709 /// `BlockTailInfo` is attached to the `LocalDecl` for temporaries
710 /// created during evaluation of expressions in a block tail
711 /// expression; that is, a block like `{ STMT_1; STMT_2; EXPR }`.
713 /// It is used to improve diagnostics when such temporaries are
714 /// involved in borrow_check errors, e.g., explanations of where the
715 /// temporaries come from, when their destructors are run, and/or how
716 /// one might revise the code to satisfy the borrow checker's rules.
717 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable)]
718 pub struct BlockTailInfo {
719 /// If `true`, then the value resulting from evaluating this tail
720 /// expression is ignored by the block's expression context.
722 /// Examples include `{ ...; tail };` and `let _ = { ...; tail };`
723 /// but not e.g., `let _x = { ...; tail };`
724 pub tail_result_is_ignored: bool,
726 /// `Span` of the tail expression.
732 /// This can be a binding declared by the user, a temporary inserted by the compiler, a function
733 /// argument, or the return place.
734 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
735 pub struct LocalDecl<'tcx> {
736 /// Whether this is a mutable minding (i.e., `let x` or `let mut x`).
738 /// Temporaries and the return place are always mutable.
739 pub mutability: Mutability,
741 // FIXME(matthewjasper) Don't store in this in `Body`
742 pub local_info: Option<Box<LocalInfo<'tcx>>>,
744 /// `true` if this is an internal local.
746 /// These locals are not based on types in the source code and are only used
747 /// for a few desugarings at the moment.
749 /// The generator transformation will sanity check the locals which are live
750 /// across a suspension point against the type components of the generator
751 /// which type checking knows are live across a suspension point. We need to
752 /// flag drop flags to avoid triggering this check as they are introduced
755 /// Unsafety checking will also ignore dereferences of these locals,
756 /// so they can be used for raw pointers only used in a desugaring.
758 /// This should be sound because the drop flags are fully algebraic, and
759 /// therefore don't affect the OIBIT or outlives properties of the
763 /// If this local is a temporary and `is_block_tail` is `Some`,
764 /// then it is a temporary created for evaluation of some
765 /// subexpression of some block's tail expression (with no
766 /// intervening statement context).
767 // FIXME(matthewjasper) Don't store in this in `Body`
768 pub is_block_tail: Option<BlockTailInfo>,
770 /// The type of this local.
773 /// If the user manually ascribed a type to this variable,
774 /// e.g., via `let x: T`, then we carry that type here. The MIR
775 /// borrow checker needs this information since it can affect
776 /// region inference.
777 // FIXME(matthewjasper) Don't store in this in `Body`
778 pub user_ty: Option<Box<UserTypeProjections>>,
780 /// The *syntactic* (i.e., not visibility) source scope the local is defined
781 /// in. If the local was defined in a let-statement, this
782 /// is *within* the let-statement, rather than outside
785 /// This is needed because the visibility source scope of locals within
786 /// a let-statement is weird.
788 /// The reason is that we want the local to be *within* the let-statement
789 /// for lint purposes, but we want the local to be *after* the let-statement
790 /// for names-in-scope purposes.
792 /// That's it, if we have a let-statement like the one in this
796 /// fn foo(x: &str) {
797 /// #[allow(unused_mut)]
798 /// let mut x: u32 = { // <- one unused mut
799 /// let mut y: u32 = x.parse().unwrap();
806 /// Then, from a lint point of view, the declaration of `x: u32`
807 /// (and `y: u32`) are within the `#[allow(unused_mut)]` scope - the
808 /// lint scopes are the same as the AST/HIR nesting.
810 /// However, from a name lookup point of view, the scopes look more like
811 /// as if the let-statements were `match` expressions:
814 /// fn foo(x: &str) {
816 /// match x.parse().unwrap() {
825 /// We care about the name-lookup scopes for debuginfo - if the
826 /// debuginfo instruction pointer is at the call to `x.parse()`, we
827 /// want `x` to refer to `x: &str`, but if it is at the call to
828 /// `drop(x)`, we want it to refer to `x: u32`.
830 /// To allow both uses to work, we need to have more than a single scope
831 /// for a local. We have the `source_info.scope` represent the "syntactic"
832 /// lint scope (with a variable being under its let block) while the
833 /// `var_debug_info.source_info.scope` represents the "local variable"
834 /// scope (where the "rest" of a block is under all prior let-statements).
836 /// The end result looks like this:
840 /// │{ argument x: &str }
842 /// │ │{ #[allow(unused_mut)] } // This is actually split into 2 scopes
843 /// │ │ // in practice because I'm lazy.
845 /// │ │← x.source_info.scope
846 /// │ │← `x.parse().unwrap()`
848 /// │ │ │← y.source_info.scope
850 /// │ │ │{ let y: u32 }
852 /// │ │ │← y.var_debug_info.source_info.scope
855 /// │ │{ let x: u32 }
856 /// │ │← x.var_debug_info.source_info.scope
857 /// │ │← `drop(x)` // This accesses `x: u32`.
859 pub source_info: SourceInfo,
862 // `LocalDecl` is used a lot. Make sure it doesn't unintentionally get bigger.
863 #[cfg(target_arch = "x86_64")]
864 static_assert_size!(LocalDecl<'_>, 56);
866 /// Extra information about a some locals that's used for diagnostics and for
867 /// classifying variables into local variables, statics, etc, which is needed e.g.
868 /// for unsafety checking.
870 /// Not used for non-StaticRef temporaries, the return place, or anonymous
871 /// function parameters.
872 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
873 pub enum LocalInfo<'tcx> {
874 /// A user-defined local variable or function parameter
876 /// The `BindingForm` is solely used for local diagnostics when generating
877 /// warnings/errors when compiling the current crate, and therefore it need
878 /// not be visible across crates.
879 User(ClearCrossCrate<BindingForm<'tcx>>),
880 /// A temporary created that references the static with the given `DefId`.
881 StaticRef { def_id: DefId, is_thread_local: bool },
884 impl<'tcx> LocalDecl<'tcx> {
885 /// Returns `true` only if local is a binding that can itself be
886 /// made mutable via the addition of the `mut` keyword, namely
887 /// something like the occurrences of `x` in:
888 /// - `fn foo(x: Type) { ... }`,
890 /// - or `match ... { C(x) => ... }`
891 pub fn can_be_made_mutable(&self) -> bool {
892 match self.local_info {
893 Some(box LocalInfo::User(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
894 binding_mode: ty::BindingMode::BindByValue(_),
900 Some(box LocalInfo::User(ClearCrossCrate::Set(BindingForm::ImplicitSelf(
901 ImplicitSelfKind::Imm,
908 /// Returns `true` if local is definitely not a `ref ident` or
909 /// `ref mut ident` binding. (Such bindings cannot be made into
910 /// mutable bindings, but the inverse does not necessarily hold).
911 pub fn is_nonref_binding(&self) -> bool {
912 match self.local_info {
913 Some(box LocalInfo::User(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
914 binding_mode: ty::BindingMode::BindByValue(_),
920 Some(box LocalInfo::User(ClearCrossCrate::Set(BindingForm::ImplicitSelf(_)))) => true,
926 /// Returns `true` if this variable is a named variable or function
927 /// parameter declared by the user.
929 pub fn is_user_variable(&self) -> bool {
930 match self.local_info {
931 Some(box LocalInfo::User(_)) => true,
936 /// Returns `true` if this is a reference to a variable bound in a `match`
937 /// expression that is used to access said variable for the guard of the
939 pub fn is_ref_for_guard(&self) -> bool {
940 match self.local_info {
941 Some(box LocalInfo::User(ClearCrossCrate::Set(BindingForm::RefForGuard))) => true,
946 /// Returns `Some` if this is a reference to a static item that is used to
947 /// access that static
948 pub fn is_ref_to_static(&self) -> bool {
949 match self.local_info {
950 Some(box LocalInfo::StaticRef { .. }) => true,
955 /// Returns `Some` if this is a reference to a static item that is used to
956 /// access that static
957 pub fn is_ref_to_thread_local(&self) -> bool {
958 match self.local_info {
959 Some(box LocalInfo::StaticRef { is_thread_local, .. }) => is_thread_local,
964 /// Returns `true` is the local is from a compiler desugaring, e.g.,
965 /// `__next` from a `for` loop.
967 pub fn from_compiler_desugaring(&self) -> bool {
968 self.source_info.span.desugaring_kind().is_some()
971 /// Creates a new `LocalDecl` for a temporary: mutable, non-internal.
973 pub fn new(ty: Ty<'tcx>, span: Span) -> Self {
974 Self::with_source_info(ty, SourceInfo::outermost(span))
977 /// Like `LocalDecl::new`, but takes a `SourceInfo` instead of a `Span`.
979 pub fn with_source_info(ty: Ty<'tcx>, source_info: SourceInfo) -> Self {
981 mutability: Mutability::Mut,
991 /// Converts `self` into same `LocalDecl` except tagged as internal.
993 pub fn internal(mut self) -> Self {
994 self.internal = true;
998 /// Converts `self` into same `LocalDecl` except tagged as immutable.
1000 pub fn immutable(mut self) -> Self {
1001 self.mutability = Mutability::Not;
1005 /// Converts `self` into same `LocalDecl` except tagged as internal temporary.
1007 pub fn block_tail(mut self, info: BlockTailInfo) -> Self {
1008 assert!(self.is_block_tail.is_none());
1009 self.is_block_tail = Some(info);
1014 /// Debug information pertaining to a user variable.
1015 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
1016 pub struct VarDebugInfo<'tcx> {
1019 /// Source info of the user variable, including the scope
1020 /// within which the variable is visible (to debuginfo)
1021 /// (see `LocalDecl`'s `source_info` field for more details).
1022 pub source_info: SourceInfo,
1024 /// Where the data for this user variable is to be found.
1025 /// NOTE(eddyb) There's an unenforced invariant that this `Place` is
1026 /// based on a `Local`, not a `Static`, and contains no indexing.
1027 pub place: Place<'tcx>,
1030 ///////////////////////////////////////////////////////////////////////////
1033 rustc_index::newtype_index! {
1034 pub struct BasicBlock {
1036 DEBUG_FORMAT = "bb{}",
1037 const START_BLOCK = 0,
1042 pub fn start_location(self) -> Location {
1043 Location { block: self, statement_index: 0 }
1047 ///////////////////////////////////////////////////////////////////////////
1048 // BasicBlockData and Terminator
1050 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
1051 pub struct BasicBlockData<'tcx> {
1052 /// List of statements in this block.
1053 pub statements: Vec<Statement<'tcx>>,
1055 /// Terminator for this block.
1057 /// N.B., this should generally ONLY be `None` during construction.
1058 /// Therefore, you should generally access it via the
1059 /// `terminator()` or `terminator_mut()` methods. The only
1060 /// exception is that certain passes, such as `simplify_cfg`, swap
1061 /// out the terminator temporarily with `None` while they continue
1062 /// to recurse over the set of basic blocks.
1063 pub terminator: Option<Terminator<'tcx>>,
1065 /// If true, this block lies on an unwind path. This is used
1066 /// during codegen where distinct kinds of basic blocks may be
1067 /// generated (particularly for MSVC cleanup). Unwind blocks must
1068 /// only branch to other unwind blocks.
1069 pub is_cleanup: bool,
1072 /// Information about an assertion failure.
1073 #[derive(Clone, TyEncodable, TyDecodable, HashStable, PartialEq)]
1074 pub enum AssertKind<O> {
1075 BoundsCheck { len: O, index: O },
1076 Overflow(BinOp, O, O),
1080 ResumedAfterReturn(GeneratorKind),
1081 ResumedAfterPanic(GeneratorKind),
1084 #[derive(Clone, Debug, PartialEq, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
1085 pub enum InlineAsmOperand<'tcx> {
1087 reg: InlineAsmRegOrRegClass,
1088 value: Operand<'tcx>,
1091 reg: InlineAsmRegOrRegClass,
1093 place: Option<Place<'tcx>>,
1096 reg: InlineAsmRegOrRegClass,
1098 in_value: Operand<'tcx>,
1099 out_place: Option<Place<'tcx>>,
1102 value: Operand<'tcx>,
1105 value: Box<Constant<'tcx>>,
1112 /// Type for MIR `Assert` terminator error messages.
1113 pub type AssertMessage<'tcx> = AssertKind<Operand<'tcx>>;
1115 pub type Successors<'a> =
1116 iter::Chain<option::IntoIter<&'a BasicBlock>, slice::Iter<'a, BasicBlock>>;
1117 pub type SuccessorsMut<'a> =
1118 iter::Chain<option::IntoIter<&'a mut BasicBlock>, slice::IterMut<'a, BasicBlock>>;
1120 impl<'tcx> BasicBlockData<'tcx> {
1121 pub fn new(terminator: Option<Terminator<'tcx>>) -> BasicBlockData<'tcx> {
1122 BasicBlockData { statements: vec![], terminator, is_cleanup: false }
1125 /// Accessor for terminator.
1127 /// Terminator may not be None after construction of the basic block is complete. This accessor
1128 /// provides a convenience way to reach the terminator.
1129 pub fn terminator(&self) -> &Terminator<'tcx> {
1130 self.terminator.as_ref().expect("invalid terminator state")
1133 pub fn terminator_mut(&mut self) -> &mut Terminator<'tcx> {
1134 self.terminator.as_mut().expect("invalid terminator state")
1137 pub fn retain_statements<F>(&mut self, mut f: F)
1139 F: FnMut(&mut Statement<'_>) -> bool,
1141 for s in &mut self.statements {
1148 pub fn expand_statements<F, I>(&mut self, mut f: F)
1150 F: FnMut(&mut Statement<'tcx>) -> Option<I>,
1151 I: iter::TrustedLen<Item = Statement<'tcx>>,
1153 // Gather all the iterators we'll need to splice in, and their positions.
1154 let mut splices: Vec<(usize, I)> = vec![];
1155 let mut extra_stmts = 0;
1156 for (i, s) in self.statements.iter_mut().enumerate() {
1157 if let Some(mut new_stmts) = f(s) {
1158 if let Some(first) = new_stmts.next() {
1159 // We can already store the first new statement.
1162 // Save the other statements for optimized splicing.
1163 let remaining = new_stmts.size_hint().0;
1165 splices.push((i + 1 + extra_stmts, new_stmts));
1166 extra_stmts += remaining;
1174 // Splice in the new statements, from the end of the block.
1175 // FIXME(eddyb) This could be more efficient with a "gap buffer"
1176 // where a range of elements ("gap") is left uninitialized, with
1177 // splicing adding new elements to the end of that gap and moving
1178 // existing elements from before the gap to the end of the gap.
1179 // For now, this is safe code, emulating a gap but initializing it.
1180 let mut gap = self.statements.len()..self.statements.len() + extra_stmts;
1181 self.statements.resize(
1183 Statement { source_info: SourceInfo::outermost(DUMMY_SP), kind: StatementKind::Nop },
1185 for (splice_start, new_stmts) in splices.into_iter().rev() {
1186 let splice_end = splice_start + new_stmts.size_hint().0;
1187 while gap.end > splice_end {
1190 self.statements.swap(gap.start, gap.end);
1192 self.statements.splice(splice_start..splice_end, new_stmts);
1193 gap.end = splice_start;
1197 pub fn visitable(&self, index: usize) -> &dyn MirVisitable<'tcx> {
1198 if index < self.statements.len() { &self.statements[index] } else { &self.terminator }
1202 impl<O> AssertKind<O> {
1203 /// Getting a description does not require `O` to be printable, and does not
1204 /// require allocation.
1205 /// The caller is expected to handle `BoundsCheck` separately.
1206 pub fn description(&self) -> &'static str {
1209 Overflow(BinOp::Add, _, _) => "attempt to add with overflow",
1210 Overflow(BinOp::Sub, _, _) => "attempt to subtract with overflow",
1211 Overflow(BinOp::Mul, _, _) => "attempt to multiply with overflow",
1212 Overflow(BinOp::Div, _, _) => "attempt to divide with overflow",
1213 Overflow(BinOp::Rem, _, _) => "attempt to calculate the remainder with overflow",
1214 OverflowNeg(_) => "attempt to negate with overflow",
1215 Overflow(BinOp::Shr, _, _) => "attempt to shift right with overflow",
1216 Overflow(BinOp::Shl, _, _) => "attempt to shift left with overflow",
1217 Overflow(op, _, _) => bug!("{:?} cannot overflow", op),
1218 DivisionByZero(_) => "attempt to divide by zero",
1219 RemainderByZero(_) => "attempt to calculate the remainder with a divisor of zero",
1220 ResumedAfterReturn(GeneratorKind::Gen) => "generator resumed after completion",
1221 ResumedAfterReturn(GeneratorKind::Async(_)) => "`async fn` resumed after completion",
1222 ResumedAfterPanic(GeneratorKind::Gen) => "generator resumed after panicking",
1223 ResumedAfterPanic(GeneratorKind::Async(_)) => "`async fn` resumed after panicking",
1224 BoundsCheck { .. } => bug!("Unexpected AssertKind"),
1228 /// Format the message arguments for the `assert(cond, msg..)` terminator in MIR printing.
1229 fn fmt_assert_args<W: Write>(&self, f: &mut W) -> fmt::Result
1235 BoundsCheck { ref len, ref index } => write!(
1237 "\"index out of bounds: the len is {{}} but the index is {{}}\", {:?}, {:?}",
1241 OverflowNeg(op) => {
1242 write!(f, "\"attempt to negate {{}} which would overflow\", {:?}", op)
1244 DivisionByZero(op) => write!(f, "\"attempt to divide {{}} by zero\", {:?}", op),
1245 RemainderByZero(op) => write!(
1247 "\"attempt to calculate the remainder of {{}} with a divisor of zero\", {:?}",
1250 Overflow(BinOp::Add, l, r) => write!(
1252 "\"attempt to compute `{{}} + {{}}` which would overflow\", {:?}, {:?}",
1255 Overflow(BinOp::Sub, l, r) => write!(
1257 "\"attempt to compute `{{}} - {{}}` which would overflow\", {:?}, {:?}",
1260 Overflow(BinOp::Mul, l, r) => write!(
1262 "\"attempt to compute `{{}} * {{}}` which would overflow\", {:?}, {:?}",
1265 Overflow(BinOp::Div, l, r) => write!(
1267 "\"attempt to compute `{{}} / {{}}` which would overflow\", {:?}, {:?}",
1270 Overflow(BinOp::Rem, l, r) => write!(
1272 "\"attempt to compute the remainder of `{{}} % {{}}` which would overflow\", {:?}, {:?}",
1275 Overflow(BinOp::Shr, _, r) => {
1276 write!(f, "\"attempt to shift right by {{}} which would overflow\", {:?}", r)
1278 Overflow(BinOp::Shl, _, r) => {
1279 write!(f, "\"attempt to shift left by {{}} which would overflow\", {:?}", r)
1281 _ => write!(f, "\"{}\"", self.description()),
1286 impl<O: fmt::Debug> fmt::Debug for AssertKind<O> {
1287 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1290 BoundsCheck { ref len, ref index } => {
1291 write!(f, "index out of bounds: the len is {:?} but the index is {:?}", len, index)
1293 OverflowNeg(op) => write!(f, "attempt to negate {:#?} which would overflow", op),
1294 DivisionByZero(op) => write!(f, "attempt to divide {:#?} by zero", op),
1295 RemainderByZero(op) => {
1296 write!(f, "attempt to calculate the remainder of {:#?} with a divisor of zero", op)
1298 Overflow(BinOp::Add, l, r) => {
1299 write!(f, "attempt to compute `{:#?} + {:#?}` which would overflow", l, r)
1301 Overflow(BinOp::Sub, l, r) => {
1302 write!(f, "attempt to compute `{:#?} - {:#?}` which would overflow", l, r)
1304 Overflow(BinOp::Mul, l, r) => {
1305 write!(f, "attempt to compute `{:#?} * {:#?}` which would overflow", l, r)
1307 Overflow(BinOp::Div, l, r) => {
1308 write!(f, "attempt to compute `{:#?} / {:#?}` which would overflow", l, r)
1310 Overflow(BinOp::Rem, l, r) => write!(
1312 "attempt to compute the remainder of `{:#?} % {:#?}` which would overflow",
1315 Overflow(BinOp::Shr, _, r) => {
1316 write!(f, "attempt to shift right by {:#?} which would overflow", r)
1318 Overflow(BinOp::Shl, _, r) => {
1319 write!(f, "attempt to shift left by {:#?} which would overflow", r)
1321 _ => write!(f, "{}", self.description()),
1326 ///////////////////////////////////////////////////////////////////////////
1329 #[derive(Clone, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
1330 pub struct Statement<'tcx> {
1331 pub source_info: SourceInfo,
1332 pub kind: StatementKind<'tcx>,
1335 // `Statement` is used a lot. Make sure it doesn't unintentionally get bigger.
1336 #[cfg(target_arch = "x86_64")]
1337 static_assert_size!(Statement<'_>, 32);
1339 impl Statement<'_> {
1340 /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
1341 /// invalidating statement indices in `Location`s.
1342 pub fn make_nop(&mut self) {
1343 self.kind = StatementKind::Nop
1346 /// Changes a statement to a nop and returns the original statement.
1347 pub fn replace_nop(&mut self) -> Self {
1349 source_info: self.source_info,
1350 kind: mem::replace(&mut self.kind, StatementKind::Nop),
1355 #[derive(Clone, Debug, PartialEq, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
1356 pub enum StatementKind<'tcx> {
1357 /// Write the RHS Rvalue to the LHS Place.
1358 Assign(Box<(Place<'tcx>, Rvalue<'tcx>)>),
1360 /// This represents all the reading that a pattern match may do
1361 /// (e.g., inspecting constants and discriminant values), and the
1362 /// kind of pattern it comes from. This is in order to adapt potential
1363 /// error messages to these specific patterns.
1365 /// Note that this also is emitted for regular `let` bindings to ensure that locals that are
1366 /// never accessed still get some sanity checks for, e.g., `let x: ! = ..;`
1367 FakeRead(FakeReadCause, Box<Place<'tcx>>),
1369 /// Write the discriminant for a variant to the enum Place.
1370 SetDiscriminant { place: Box<Place<'tcx>>, variant_index: VariantIdx },
1372 /// Start a live range for the storage of the local.
1375 /// End the current live range for the storage of the local.
1378 /// Executes a piece of inline Assembly. Stored in a Box to keep the size
1379 /// of `StatementKind` low.
1380 LlvmInlineAsm(Box<LlvmInlineAsm<'tcx>>),
1382 /// Retag references in the given place, ensuring they got fresh tags. This is
1383 /// part of the Stacked Borrows model. These statements are currently only interpreted
1384 /// by miri and only generated when "-Z mir-emit-retag" is passed.
1385 /// See <https://internals.rust-lang.org/t/stacked-borrows-an-aliasing-model-for-rust/8153/>
1386 /// for more details.
1387 Retag(RetagKind, Box<Place<'tcx>>),
1389 /// Encodes a user's type ascription. These need to be preserved
1390 /// intact so that NLL can respect them. For example:
1394 /// The effect of this annotation is to relate the type `T_y` of the place `y`
1395 /// to the user-given type `T`. The effect depends on the specified variance:
1397 /// - `Covariant` -- requires that `T_y <: T`
1398 /// - `Contravariant` -- requires that `T_y :> T`
1399 /// - `Invariant` -- requires that `T_y == T`
1400 /// - `Bivariant` -- no effect
1401 AscribeUserType(Box<(Place<'tcx>, UserTypeProjection)>, ty::Variance),
1403 /// No-op. Useful for deleting instructions without affecting statement indices.
1407 /// Describes what kind of retag is to be performed.
1408 #[derive(Copy, Clone, TyEncodable, TyDecodable, Debug, PartialEq, Eq, HashStable)]
1409 pub enum RetagKind {
1410 /// The initial retag when entering a function.
1412 /// Retag preparing for a two-phase borrow.
1414 /// Retagging raw pointers.
1416 /// A "normal" retag.
1420 /// The `FakeReadCause` describes the type of pattern why a FakeRead statement exists.
1421 #[derive(Copy, Clone, TyEncodable, TyDecodable, Debug, HashStable, PartialEq)]
1422 pub enum FakeReadCause {
1423 /// Inject a fake read of the borrowed input at the end of each guards
1426 /// This should ensure that you cannot change the variant for an enum while
1427 /// you are in the midst of matching on it.
1430 /// `let x: !; match x {}` doesn't generate any read of x so we need to
1431 /// generate a read of x to check that it is initialized and safe.
1434 /// A fake read of the RefWithinGuard version of a bind-by-value variable
1435 /// in a match guard to ensure that it's value hasn't change by the time
1436 /// we create the OutsideGuard version.
1439 /// Officially, the semantics of
1441 /// `let pattern = <expr>;`
1443 /// is that `<expr>` is evaluated into a temporary and then this temporary is
1444 /// into the pattern.
1446 /// However, if we see the simple pattern `let var = <expr>`, we optimize this to
1447 /// evaluate `<expr>` directly into the variable `var`. This is mostly unobservable,
1448 /// but in some cases it can affect the borrow checker, as in #53695.
1449 /// Therefore, we insert a "fake read" here to ensure that we get
1450 /// appropriate errors.
1453 /// If we have an index expression like
1455 /// (*x)[1][{ x = y; 4}]
1457 /// then the first bounds check is invalidated when we evaluate the second
1458 /// index expression. Thus we create a fake borrow of `x` across the second
1459 /// indexer, which will cause a borrow check error.
1463 #[derive(Clone, Debug, PartialEq, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
1464 pub struct LlvmInlineAsm<'tcx> {
1465 pub asm: hir::LlvmInlineAsmInner,
1466 pub outputs: Box<[Place<'tcx>]>,
1467 pub inputs: Box<[(Span, Operand<'tcx>)]>,
1470 impl Debug for Statement<'_> {
1471 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1472 use self::StatementKind::*;
1474 Assign(box (ref place, ref rv)) => write!(fmt, "{:?} = {:?}", place, rv),
1475 FakeRead(ref cause, ref place) => write!(fmt, "FakeRead({:?}, {:?})", cause, place),
1476 Retag(ref kind, ref place) => write!(
1480 RetagKind::FnEntry => "[fn entry] ",
1481 RetagKind::TwoPhase => "[2phase] ",
1482 RetagKind::Raw => "[raw] ",
1483 RetagKind::Default => "",
1487 StorageLive(ref place) => write!(fmt, "StorageLive({:?})", place),
1488 StorageDead(ref place) => write!(fmt, "StorageDead({:?})", place),
1489 SetDiscriminant { ref place, variant_index } => {
1490 write!(fmt, "discriminant({:?}) = {:?}", place, variant_index)
1492 LlvmInlineAsm(ref asm) => {
1493 write!(fmt, "llvm_asm!({:?} : {:?} : {:?})", asm.asm, asm.outputs, asm.inputs)
1495 AscribeUserType(box (ref place, ref c_ty), ref variance) => {
1496 write!(fmt, "AscribeUserType({:?}, {:?}, {:?})", place, variance, c_ty)
1498 Nop => write!(fmt, "nop"),
1503 ///////////////////////////////////////////////////////////////////////////
1506 /// A path to a value; something that can be evaluated without
1507 /// changing or disturbing program state.
1508 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, HashStable)]
1509 pub struct Place<'tcx> {
1512 /// projection out of a place (access a field, deref a pointer, etc)
1513 pub projection: &'tcx List<PlaceElem<'tcx>>,
1516 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
1517 #[derive(TyEncodable, TyDecodable, HashStable)]
1518 pub enum ProjectionElem<V, T> {
1523 /// These indices are generated by slice patterns. Easiest to explain
1527 /// [X, _, .._, _, _] => { offset: 0, min_length: 4, from_end: false },
1528 /// [_, X, .._, _, _] => { offset: 1, min_length: 4, from_end: false },
1529 /// [_, _, .._, X, _] => { offset: 2, min_length: 4, from_end: true },
1530 /// [_, _, .._, _, X] => { offset: 1, min_length: 4, from_end: true },
1533 /// index or -index (in Python terms), depending on from_end
1535 /// The thing being indexed must be at least this long. For arrays this
1536 /// is always the exact length.
1538 /// Counting backwards from end? This is always false when indexing an
1543 /// These indices are generated by slice patterns.
1545 /// If `from_end` is true `slice[from..slice.len() - to]`.
1546 /// Otherwise `array[from..to]`.
1550 /// Whether `to` counts from the start or end of the array/slice.
1551 /// For `PlaceElem`s this is `true` if and only if the base is a slice.
1552 /// For `ProjectionKind`, this can also be `true` for arrays.
1556 /// "Downcast" to a variant of an ADT. Currently, we only introduce
1557 /// this for ADTs with more than one variant. It may be better to
1558 /// just introduce it always, or always for enums.
1560 /// The included Symbol is the name of the variant, used for printing MIR.
1561 Downcast(Option<Symbol>, VariantIdx),
1564 impl<V, T> ProjectionElem<V, T> {
1565 /// Returns `true` if the target of this projection may refer to a different region of memory
1567 fn is_indirect(&self) -> bool {
1569 Self::Deref => true,
1573 | Self::ConstantIndex { .. }
1574 | Self::Subslice { .. }
1575 | Self::Downcast(_, _) => false,
1580 /// Alias for projections as they appear in places, where the base is a place
1581 /// and the index is a local.
1582 pub type PlaceElem<'tcx> = ProjectionElem<Local, Ty<'tcx>>;
1584 // At least on 64 bit systems, `PlaceElem` should not be larger than two pointers.
1585 #[cfg(target_arch = "x86_64")]
1586 static_assert_size!(PlaceElem<'_>, 16);
1588 /// Alias for projections as they appear in `UserTypeProjection`, where we
1589 /// need neither the `V` parameter for `Index` nor the `T` for `Field`.
1590 pub type ProjectionKind = ProjectionElem<(), ()>;
1592 rustc_index::newtype_index! {
1595 DEBUG_FORMAT = "field[{}]"
1599 #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
1600 pub struct PlaceRef<'tcx> {
1602 pub projection: &'tcx [PlaceElem<'tcx>],
1605 impl<'tcx> Place<'tcx> {
1606 // FIXME change this to a const fn by also making List::empty a const fn.
1607 pub fn return_place() -> Place<'tcx> {
1608 Place { local: RETURN_PLACE, projection: List::empty() }
1611 /// Returns `true` if this `Place` contains a `Deref` projection.
1613 /// If `Place::is_indirect` returns false, the caller knows that the `Place` refers to the
1614 /// same region of memory as its base.
1615 pub fn is_indirect(&self) -> bool {
1616 self.projection.iter().any(|elem| elem.is_indirect())
1619 /// Finds the innermost `Local` from this `Place`, *if* it is either a local itself or
1620 /// a single deref of a local.
1622 // FIXME: can we safely swap the semantics of `fn base_local` below in here instead?
1623 pub fn local_or_deref_local(&self) -> Option<Local> {
1624 match self.as_ref() {
1625 PlaceRef { local, projection: [] }
1626 | PlaceRef { local, projection: [ProjectionElem::Deref] } => Some(local),
1631 /// If this place represents a local variable like `_X` with no
1632 /// projections, return `Some(_X)`.
1633 pub fn as_local(&self) -> Option<Local> {
1634 self.as_ref().as_local()
1637 pub fn as_ref(&self) -> PlaceRef<'tcx> {
1638 PlaceRef { local: self.local, projection: &self.projection }
1642 impl From<Local> for Place<'_> {
1643 fn from(local: Local) -> Self {
1644 Place { local, projection: List::empty() }
1648 impl<'tcx> PlaceRef<'tcx> {
1649 /// Finds the innermost `Local` from this `Place`, *if* it is either a local itself or
1650 /// a single deref of a local.
1652 // FIXME: can we safely swap the semantics of `fn base_local` below in here instead?
1653 pub fn local_or_deref_local(&self) -> Option<Local> {
1655 PlaceRef { local, projection: [] }
1656 | PlaceRef { local, projection: [ProjectionElem::Deref] } => Some(local),
1661 /// If this place represents a local variable like `_X` with no
1662 /// projections, return `Some(_X)`.
1663 pub fn as_local(&self) -> Option<Local> {
1665 PlaceRef { local, projection: [] } => Some(local),
1671 impl Debug for Place<'_> {
1672 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1673 for elem in self.projection.iter().rev() {
1675 ProjectionElem::Downcast(_, _) | ProjectionElem::Field(_, _) => {
1676 write!(fmt, "(").unwrap();
1678 ProjectionElem::Deref => {
1679 write!(fmt, "(*").unwrap();
1681 ProjectionElem::Index(_)
1682 | ProjectionElem::ConstantIndex { .. }
1683 | ProjectionElem::Subslice { .. } => {}
1687 write!(fmt, "{:?}", self.local)?;
1689 for elem in self.projection.iter() {
1691 ProjectionElem::Downcast(Some(name), _index) => {
1692 write!(fmt, " as {})", name)?;
1694 ProjectionElem::Downcast(None, index) => {
1695 write!(fmt, " as variant#{:?})", index)?;
1697 ProjectionElem::Deref => {
1700 ProjectionElem::Field(field, ty) => {
1701 write!(fmt, ".{:?}: {:?})", field.index(), ty)?;
1703 ProjectionElem::Index(ref index) => {
1704 write!(fmt, "[{:?}]", index)?;
1706 ProjectionElem::ConstantIndex { offset, min_length, from_end: false } => {
1707 write!(fmt, "[{:?} of {:?}]", offset, min_length)?;
1709 ProjectionElem::ConstantIndex { offset, min_length, from_end: true } => {
1710 write!(fmt, "[-{:?} of {:?}]", offset, min_length)?;
1712 ProjectionElem::Subslice { from, to, from_end: true } if to == 0 => {
1713 write!(fmt, "[{:?}:]", from)?;
1715 ProjectionElem::Subslice { from, to, from_end: true } if from == 0 => {
1716 write!(fmt, "[:-{:?}]", to)?;
1718 ProjectionElem::Subslice { from, to, from_end: true } => {
1719 write!(fmt, "[{:?}:-{:?}]", from, to)?;
1721 ProjectionElem::Subslice { from, to, from_end: false } => {
1722 write!(fmt, "[{:?}..{:?}]", from, to)?;
1731 ///////////////////////////////////////////////////////////////////////////
1734 rustc_index::newtype_index! {
1735 pub struct SourceScope {
1737 DEBUG_FORMAT = "scope[{}]",
1738 const OUTERMOST_SOURCE_SCOPE = 0,
1742 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable)]
1743 pub struct SourceScopeData {
1745 pub parent_scope: Option<SourceScope>,
1747 /// Crate-local information for this source scope, that can't (and
1748 /// needn't) be tracked across crates.
1749 pub local_data: ClearCrossCrate<SourceScopeLocalData>,
1752 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable)]
1753 pub struct SourceScopeLocalData {
1754 /// An `HirId` with lint levels equivalent to this scope's lint levels.
1755 pub lint_root: hir::HirId,
1756 /// The unsafe block that contains this node.
1760 ///////////////////////////////////////////////////////////////////////////
1763 /// These are values that can appear inside an rvalue. They are intentionally
1764 /// limited to prevent rvalues from being nested in one another.
1765 #[derive(Clone, PartialEq, TyEncodable, TyDecodable, HashStable)]
1766 pub enum Operand<'tcx> {
1767 /// Copy: The value must be available for use afterwards.
1769 /// This implies that the type of the place must be `Copy`; this is true
1770 /// by construction during build, but also checked by the MIR type checker.
1773 /// Move: The value (including old borrows of it) will not be used again.
1775 /// Safe for values of all types (modulo future developments towards `?Move`).
1776 /// Correct usage patterns are enforced by the borrow checker for safe code.
1777 /// `Copy` may be converted to `Move` to enable "last-use" optimizations.
1780 /// Synthesizes a constant value.
1781 Constant(Box<Constant<'tcx>>),
1784 impl<'tcx> Debug for Operand<'tcx> {
1785 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1786 use self::Operand::*;
1788 Constant(ref a) => write!(fmt, "{:?}", a),
1789 Copy(ref place) => write!(fmt, "{:?}", place),
1790 Move(ref place) => write!(fmt, "move {:?}", place),
1795 impl<'tcx> Operand<'tcx> {
1796 /// Convenience helper to make a constant that refers to the fn
1797 /// with given `DefId` and substs. Since this is used to synthesize
1798 /// MIR, assumes `user_ty` is None.
1799 pub fn function_handle(
1802 substs: SubstsRef<'tcx>,
1805 let ty = tcx.type_of(def_id).subst(tcx, substs);
1806 Operand::Constant(box Constant {
1809 literal: ty::Const::zero_sized(tcx, ty),
1813 /// Convenience helper to make a literal-like constant from a given scalar value.
1814 /// Since this is used to synthesize MIR, assumes `user_ty` is None.
1815 pub fn const_from_scalar(
1820 ) -> Operand<'tcx> {
1822 let param_env_and_ty = ty::ParamEnv::empty().and(ty);
1824 .layout_of(param_env_and_ty)
1825 .unwrap_or_else(|e| panic!("could not compute layout for {:?}: {:?}", ty, e))
1827 let scalar_size = abi::Size::from_bytes(match val {
1828 Scalar::Raw { size, .. } => size,
1829 _ => panic!("Invalid scalar type {:?}", val),
1831 scalar_size == type_size
1833 Operand::Constant(box Constant {
1836 literal: ty::Const::from_scalar(tcx, val, ty),
1840 /// Convenience helper to make a `Scalar` from the given `Operand`, assuming that `Operand`
1841 /// wraps a constant literal value. Panics if this is not the case.
1842 pub fn scalar_from_const(operand: &Operand<'tcx>) -> Scalar {
1844 Operand::Constant(constant) => match constant.literal.val.try_to_scalar() {
1845 Some(scalar) => scalar,
1846 _ => panic!("{:?}: Scalar value expected", constant.literal.val),
1848 _ => panic!("{:?}: Constant expected", operand),
1852 /// Convenience helper to make a literal-like constant from a given `&str` slice.
1853 /// Since this is used to synthesize MIR, assumes `user_ty` is None.
1854 pub fn const_from_str(tcx: TyCtxt<'tcx>, val: &str, span: Span) -> Operand<'tcx> {
1856 let allocation = Allocation::from_byte_aligned_bytes(val.as_bytes());
1857 let allocation = tcx.intern_const_alloc(allocation);
1858 let const_val = ConstValue::Slice { data: allocation, start: 0, end: val.len() };
1859 let ty = tcx.mk_imm_ref(tcx.lifetimes.re_erased, tcx.types.str_);
1860 Operand::Constant(box Constant {
1863 literal: ty::Const::from_value(tcx, const_val, ty),
1867 /// Convenience helper to make a `ConstValue` from the given `Operand`, assuming that `Operand`
1868 /// wraps a constant value (such as a `&str` slice). Panics if this is not the case.
1869 pub fn value_from_const(operand: &Operand<'tcx>) -> ConstValue<'tcx> {
1871 Operand::Constant(constant) => match constant.literal.val.try_to_value() {
1872 Some(const_value) => const_value,
1873 _ => panic!("{:?}: ConstValue expected", constant.literal.val),
1875 _ => panic!("{:?}: Constant expected", operand),
1879 pub fn to_copy(&self) -> Self {
1881 Operand::Copy(_) | Operand::Constant(_) => self.clone(),
1882 Operand::Move(place) => Operand::Copy(place),
1886 /// Returns the `Place` that is the target of this `Operand`, or `None` if this `Operand` is a
1888 pub fn place(&self) -> Option<Place<'tcx>> {
1890 Operand::Copy(place) | Operand::Move(place) => Some(*place),
1891 Operand::Constant(_) => None,
1896 ///////////////////////////////////////////////////////////////////////////
1899 #[derive(Clone, TyEncodable, TyDecodable, HashStable, PartialEq)]
1900 pub enum Rvalue<'tcx> {
1901 /// x (either a move or copy, depending on type of x)
1905 Repeat(Operand<'tcx>, &'tcx ty::Const<'tcx>),
1908 Ref(Region<'tcx>, BorrowKind, Place<'tcx>),
1910 /// Accessing a thread local static. This is inherently a runtime operation, even if llvm
1911 /// treats it as an access to a static. This `Rvalue` yields a reference to the thread local
1913 ThreadLocalRef(DefId),
1915 /// Create a raw pointer to the given place
1916 /// Can be generated by raw address of expressions (`&raw const x`),
1917 /// or when casting a reference to a raw pointer.
1918 AddressOf(Mutability, Place<'tcx>),
1920 /// length of a `[X]` or `[X;n]` value
1923 Cast(CastKind, Operand<'tcx>, Ty<'tcx>),
1925 BinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
1926 CheckedBinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
1928 NullaryOp(NullOp, Ty<'tcx>),
1929 UnaryOp(UnOp, Operand<'tcx>),
1931 /// Read the discriminant of an ADT.
1933 /// Undefined (i.e., no effort is made to make it defined, but there’s no reason why it cannot
1934 /// be defined to return, say, a 0) if ADT is not an enum.
1935 Discriminant(Place<'tcx>),
1937 /// Creates an aggregate value, like a tuple or struct. This is
1938 /// only needed because we want to distinguish `dest = Foo { x:
1939 /// ..., y: ... }` from `dest.x = ...; dest.y = ...;` in the case
1940 /// that `Foo` has a destructor. These rvalues can be optimized
1941 /// away after type-checking and before lowering.
1942 Aggregate(Box<AggregateKind<'tcx>>, Vec<Operand<'tcx>>),
1945 #[derive(Clone, Copy, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
1948 Pointer(PointerCast),
1951 #[derive(Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
1952 pub enum AggregateKind<'tcx> {
1953 /// The type is of the element
1957 /// The second field is the variant index. It's equal to 0 for struct
1958 /// and union expressions. The fourth field is
1959 /// active field number and is present only for union expressions
1960 /// -- e.g., for a union expression `SomeUnion { c: .. }`, the
1961 /// active field index would identity the field `c`
1962 Adt(&'tcx AdtDef, VariantIdx, SubstsRef<'tcx>, Option<UserTypeAnnotationIndex>, Option<usize>),
1964 Closure(DefId, SubstsRef<'tcx>),
1965 Generator(DefId, SubstsRef<'tcx>, hir::Movability),
1968 #[derive(Copy, Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
1970 /// The `+` operator (addition)
1972 /// The `-` operator (subtraction)
1974 /// The `*` operator (multiplication)
1976 /// The `/` operator (division)
1978 /// The `%` operator (modulus)
1980 /// The `^` operator (bitwise xor)
1982 /// The `&` operator (bitwise and)
1984 /// The `|` operator (bitwise or)
1986 /// The `<<` operator (shift left)
1988 /// The `>>` operator (shift right)
1990 /// The `==` operator (equality)
1992 /// The `<` operator (less than)
1994 /// The `<=` operator (less than or equal to)
1996 /// The `!=` operator (not equal to)
1998 /// The `>=` operator (greater than or equal to)
2000 /// The `>` operator (greater than)
2002 /// The `ptr.offset` operator
2007 pub fn is_checkable(self) -> bool {
2010 Add | Sub | Mul | Shl | Shr => true,
2016 #[derive(Copy, Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
2018 /// Returns the size of a value of that type
2020 /// Creates a new uninitialized box for a value of that type
2024 #[derive(Copy, Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
2026 /// The `!` operator for logical inversion
2028 /// The `-` operator for negation
2032 impl<'tcx> Debug for Rvalue<'tcx> {
2033 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2034 use self::Rvalue::*;
2037 Use(ref place) => write!(fmt, "{:?}", place),
2038 Repeat(ref a, ref b) => {
2039 write!(fmt, "[{:?}; ", a)?;
2040 pretty_print_const(b, fmt, false)?;
2043 Len(ref a) => write!(fmt, "Len({:?})", a),
2044 Cast(ref kind, ref place, ref ty) => {
2045 write!(fmt, "{:?} as {:?} ({:?})", place, ty, kind)
2047 BinaryOp(ref op, ref a, ref b) => write!(fmt, "{:?}({:?}, {:?})", op, a, b),
2048 CheckedBinaryOp(ref op, ref a, ref b) => {
2049 write!(fmt, "Checked{:?}({:?}, {:?})", op, a, b)
2051 UnaryOp(ref op, ref a) => write!(fmt, "{:?}({:?})", op, a),
2052 Discriminant(ref place) => write!(fmt, "discriminant({:?})", place),
2053 NullaryOp(ref op, ref t) => write!(fmt, "{:?}({:?})", op, t),
2054 ThreadLocalRef(did) => ty::tls::with(|tcx| {
2055 let muta = tcx.static_mutability(did).unwrap().prefix_str();
2056 write!(fmt, "&/*tls*/ {}{}", muta, tcx.def_path_str(did))
2058 Ref(region, borrow_kind, ref place) => {
2059 let kind_str = match borrow_kind {
2060 BorrowKind::Shared => "",
2061 BorrowKind::Shallow => "shallow ",
2062 BorrowKind::Mut { .. } | BorrowKind::Unique => "mut ",
2065 // When printing regions, add trailing space if necessary.
2066 let print_region = ty::tls::with(|tcx| {
2067 tcx.sess.verbose() || tcx.sess.opts.debugging_opts.identify_regions
2069 let region = if print_region {
2070 let mut region = region.to_string();
2071 if !region.is_empty() {
2076 // Do not even print 'static
2079 write!(fmt, "&{}{}{:?}", region, kind_str, place)
2082 AddressOf(mutability, ref place) => {
2083 let kind_str = match mutability {
2084 Mutability::Mut => "mut",
2085 Mutability::Not => "const",
2088 write!(fmt, "&raw {} {:?}", kind_str, place)
2091 Aggregate(ref kind, ref places) => {
2092 let fmt_tuple = |fmt: &mut Formatter<'_>, name: &str| {
2093 let mut tuple_fmt = fmt.debug_tuple(name);
2094 for place in places {
2095 tuple_fmt.field(place);
2101 AggregateKind::Array(_) => write!(fmt, "{:?}", places),
2103 AggregateKind::Tuple => {
2104 if places.is_empty() {
2111 AggregateKind::Adt(adt_def, variant, substs, _user_ty, _) => {
2112 let variant_def = &adt_def.variants[variant];
2114 let name = ty::tls::with(|tcx| {
2115 let mut name = String::new();
2116 let substs = tcx.lift(&substs).expect("could not lift for printing");
2117 FmtPrinter::new(tcx, &mut name, Namespace::ValueNS)
2118 .print_def_path(variant_def.def_id, substs)?;
2122 match variant_def.ctor_kind {
2123 CtorKind::Const => fmt.write_str(&name),
2124 CtorKind::Fn => fmt_tuple(fmt, &name),
2125 CtorKind::Fictive => {
2126 let mut struct_fmt = fmt.debug_struct(&name);
2127 for (field, place) in variant_def.fields.iter().zip(places) {
2128 struct_fmt.field(&field.ident.as_str(), place);
2135 AggregateKind::Closure(def_id, substs) => ty::tls::with(|tcx| {
2136 if let Some(def_id) = def_id.as_local() {
2137 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
2138 let name = if tcx.sess.opts.debugging_opts.span_free_formats {
2139 let substs = tcx.lift(&substs).unwrap();
2142 tcx.def_path_str_with_substs(def_id.to_def_id(), substs),
2145 let span = tcx.hir().span(hir_id);
2146 format!("[closure@{}]", tcx.sess.source_map().span_to_string(span))
2148 let mut struct_fmt = fmt.debug_struct(&name);
2150 if let Some(upvars) = tcx.upvars_mentioned(def_id) {
2151 for (&var_id, place) in upvars.keys().zip(places) {
2152 let var_name = tcx.hir().name(var_id);
2153 struct_fmt.field(&var_name.as_str(), place);
2159 write!(fmt, "[closure]")
2163 AggregateKind::Generator(def_id, _, _) => ty::tls::with(|tcx| {
2164 if let Some(def_id) = def_id.as_local() {
2165 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
2166 let name = format!("[generator@{:?}]", tcx.hir().span(hir_id));
2167 let mut struct_fmt = fmt.debug_struct(&name);
2169 if let Some(upvars) = tcx.upvars_mentioned(def_id) {
2170 for (&var_id, place) in upvars.keys().zip(places) {
2171 let var_name = tcx.hir().name(var_id);
2172 struct_fmt.field(&var_name.as_str(), place);
2178 write!(fmt, "[generator]")
2187 ///////////////////////////////////////////////////////////////////////////
2190 /// Two constants are equal if they are the same constant. Note that
2191 /// this does not necessarily mean that they are "==" in Rust -- in
2192 /// particular one must be wary of `NaN`!
2194 #[derive(Clone, Copy, PartialEq, TyEncodable, TyDecodable, HashStable)]
2195 pub struct Constant<'tcx> {
2198 /// Optional user-given type: for something like
2199 /// `collect::<Vec<_>>`, this would be present and would
2200 /// indicate that `Vec<_>` was explicitly specified.
2202 /// Needed for NLL to impose user-given type constraints.
2203 pub user_ty: Option<UserTypeAnnotationIndex>,
2205 pub literal: &'tcx ty::Const<'tcx>,
2208 impl Constant<'tcx> {
2209 pub fn check_static_ptr(&self, tcx: TyCtxt<'_>) -> Option<DefId> {
2210 match self.literal.val.try_to_scalar() {
2211 Some(Scalar::Ptr(ptr)) => match tcx.global_alloc(ptr.alloc_id) {
2212 GlobalAlloc::Static(def_id) => {
2213 assert!(!tcx.is_thread_local_static(def_id));
2223 /// A collection of projections into user types.
2225 /// They are projections because a binding can occur a part of a
2226 /// parent pattern that has been ascribed a type.
2228 /// Its a collection because there can be multiple type ascriptions on
2229 /// the path from the root of the pattern down to the binding itself.
2234 /// struct S<'a>((i32, &'a str), String);
2235 /// let S((_, w): (i32, &'static str), _): S = ...;
2236 /// // ------ ^^^^^^^^^^^^^^^^^^^ (1)
2237 /// // --------------------------------- ^ (2)
2240 /// The highlights labelled `(1)` show the subpattern `(_, w)` being
2241 /// ascribed the type `(i32, &'static str)`.
2243 /// The highlights labelled `(2)` show the whole pattern being
2244 /// ascribed the type `S`.
2246 /// In this example, when we descend to `w`, we will have built up the
2247 /// following two projected types:
2249 /// * base: `S`, projection: `(base.0).1`
2250 /// * base: `(i32, &'static str)`, projection: `base.1`
2252 /// The first will lead to the constraint `w: &'1 str` (for some
2253 /// inferred region `'1`). The second will lead to the constraint `w:
2255 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
2256 pub struct UserTypeProjections {
2257 pub contents: Vec<(UserTypeProjection, Span)>,
2260 impl<'tcx> UserTypeProjections {
2261 pub fn none() -> Self {
2262 UserTypeProjections { contents: vec![] }
2265 pub fn is_empty(&self) -> bool {
2266 self.contents.is_empty()
2269 pub fn from_projections(projs: impl Iterator<Item = (UserTypeProjection, Span)>) -> Self {
2270 UserTypeProjections { contents: projs.collect() }
2273 pub fn projections_and_spans(
2275 ) -> impl Iterator<Item = &(UserTypeProjection, Span)> + ExactSizeIterator {
2276 self.contents.iter()
2279 pub fn projections(&self) -> impl Iterator<Item = &UserTypeProjection> + ExactSizeIterator {
2280 self.contents.iter().map(|&(ref user_type, _span)| user_type)
2283 pub fn push_projection(mut self, user_ty: &UserTypeProjection, span: Span) -> Self {
2284 self.contents.push((user_ty.clone(), span));
2290 mut f: impl FnMut(UserTypeProjection) -> UserTypeProjection,
2292 self.contents = self.contents.drain(..).map(|(proj, span)| (f(proj), span)).collect();
2296 pub fn index(self) -> Self {
2297 self.map_projections(|pat_ty_proj| pat_ty_proj.index())
2300 pub fn subslice(self, from: u32, to: u32) -> Self {
2301 self.map_projections(|pat_ty_proj| pat_ty_proj.subslice(from, to))
2304 pub fn deref(self) -> Self {
2305 self.map_projections(|pat_ty_proj| pat_ty_proj.deref())
2308 pub fn leaf(self, field: Field) -> Self {
2309 self.map_projections(|pat_ty_proj| pat_ty_proj.leaf(field))
2312 pub fn variant(self, adt_def: &'tcx AdtDef, variant_index: VariantIdx, field: Field) -> Self {
2313 self.map_projections(|pat_ty_proj| pat_ty_proj.variant(adt_def, variant_index, field))
2317 /// Encodes the effect of a user-supplied type annotation on the
2318 /// subcomponents of a pattern. The effect is determined by applying the
2319 /// given list of proejctions to some underlying base type. Often,
2320 /// the projection element list `projs` is empty, in which case this
2321 /// directly encodes a type in `base`. But in the case of complex patterns with
2322 /// subpatterns and bindings, we want to apply only a *part* of the type to a variable,
2323 /// in which case the `projs` vector is used.
2327 /// * `let x: T = ...` -- here, the `projs` vector is empty.
2329 /// * `let (x, _): T = ...` -- here, the `projs` vector would contain
2330 /// `field[0]` (aka `.0`), indicating that the type of `s` is
2331 /// determined by finding the type of the `.0` field from `T`.
2332 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, PartialEq)]
2333 pub struct UserTypeProjection {
2334 pub base: UserTypeAnnotationIndex,
2335 pub projs: Vec<ProjectionKind>,
2338 impl Copy for ProjectionKind {}
2340 impl UserTypeProjection {
2341 pub(crate) fn index(mut self) -> Self {
2342 self.projs.push(ProjectionElem::Index(()));
2346 pub(crate) fn subslice(mut self, from: u32, to: u32) -> Self {
2347 self.projs.push(ProjectionElem::Subslice { from, to, from_end: true });
2351 pub(crate) fn deref(mut self) -> Self {
2352 self.projs.push(ProjectionElem::Deref);
2356 pub(crate) fn leaf(mut self, field: Field) -> Self {
2357 self.projs.push(ProjectionElem::Field(field, ()));
2361 pub(crate) fn variant(
2364 variant_index: VariantIdx,
2367 self.projs.push(ProjectionElem::Downcast(
2368 Some(adt_def.variants[variant_index].ident.name),
2371 self.projs.push(ProjectionElem::Field(field, ()));
2376 CloneTypeFoldableAndLiftImpls! { ProjectionKind, }
2378 impl<'tcx> TypeFoldable<'tcx> for UserTypeProjection {
2379 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
2380 use crate::mir::ProjectionElem::*;
2382 let base = self.base.fold_with(folder);
2383 let projs: Vec<_> = self
2386 .map(|&elem| match elem {
2388 Field(f, ()) => Field(f, ()),
2389 Index(()) => Index(()),
2390 Downcast(symbol, variantidx) => Downcast(symbol, variantidx),
2391 ConstantIndex { offset, min_length, from_end } => {
2392 ConstantIndex { offset, min_length, from_end }
2394 Subslice { from, to, from_end } => Subslice { from, to, from_end },
2398 UserTypeProjection { base, projs }
2401 fn super_visit_with<Vs: TypeVisitor<'tcx>>(&self, visitor: &mut Vs) -> bool {
2402 self.base.visit_with(visitor)
2403 // Note: there's nothing in `self.proj` to visit.
2407 rustc_index::newtype_index! {
2408 pub struct Promoted {
2410 DEBUG_FORMAT = "promoted[{}]"
2414 impl<'tcx> Debug for Constant<'tcx> {
2415 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2416 write!(fmt, "{}", self)
2420 impl<'tcx> Display for Constant<'tcx> {
2421 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2422 write!(fmt, "const ")?;
2423 pretty_print_const(self.literal, fmt, true)
2427 fn pretty_print_const(
2428 c: &ty::Const<'tcx>,
2429 fmt: &mut Formatter<'_>,
2432 use crate::ty::print::PrettyPrinter;
2433 ty::tls::with(|tcx| {
2434 let literal = tcx.lift(&c).unwrap();
2435 let mut cx = FmtPrinter::new(tcx, fmt, Namespace::ValueNS);
2436 cx.print_alloc_ids = true;
2437 cx.pretty_print_const(literal, print_types)?;
2442 impl<'tcx> graph::DirectedGraph for Body<'tcx> {
2443 type Node = BasicBlock;
2446 impl<'tcx> graph::WithNumNodes for Body<'tcx> {
2448 fn num_nodes(&self) -> usize {
2449 self.basic_blocks.len()
2453 impl<'tcx> graph::WithStartNode for Body<'tcx> {
2455 fn start_node(&self) -> Self::Node {
2460 impl<'tcx> graph::WithSuccessors for Body<'tcx> {
2462 fn successors(&self, node: Self::Node) -> <Self as GraphSuccessors<'_>>::Iter {
2463 self.basic_blocks[node].terminator().successors().cloned()
2467 impl<'a, 'b> graph::GraphSuccessors<'b> for Body<'a> {
2468 type Item = BasicBlock;
2469 type Iter = iter::Cloned<Successors<'b>>;
2472 impl graph::GraphPredecessors<'graph> for Body<'tcx> {
2473 type Item = BasicBlock;
2474 type Iter = smallvec::IntoIter<[BasicBlock; 4]>;
2477 impl graph::WithPredecessors for Body<'tcx> {
2479 fn predecessors(&self, node: Self::Node) -> <Self as graph::GraphPredecessors<'_>>::Iter {
2480 self.predecessors()[node].clone().into_iter()
2484 /// `Location` represents the position of the start of the statement; or, if
2485 /// `statement_index` equals the number of statements, then the start of the
2487 #[derive(Copy, Clone, PartialEq, Eq, Hash, Ord, PartialOrd, HashStable)]
2488 pub struct Location {
2489 /// The block that the location is within.
2490 pub block: BasicBlock,
2492 pub statement_index: usize,
2495 impl fmt::Debug for Location {
2496 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2497 write!(fmt, "{:?}[{}]", self.block, self.statement_index)
2502 pub const START: Location = Location { block: START_BLOCK, statement_index: 0 };
2504 /// Returns the location immediately after this one within the enclosing block.
2506 /// Note that if this location represents a terminator, then the
2507 /// resulting location would be out of bounds and invalid.
2508 pub fn successor_within_block(&self) -> Location {
2509 Location { block: self.block, statement_index: self.statement_index + 1 }
2512 /// Returns `true` if `other` is earlier in the control flow graph than `self`.
2513 pub fn is_predecessor_of<'tcx>(&self, other: Location, body: &Body<'tcx>) -> bool {
2514 // If we are in the same block as the other location and are an earlier statement
2515 // then we are a predecessor of `other`.
2516 if self.block == other.block && self.statement_index < other.statement_index {
2520 let predecessors = body.predecessors();
2522 // If we're in another block, then we want to check that block is a predecessor of `other`.
2523 let mut queue: Vec<BasicBlock> = predecessors[other.block].to_vec();
2524 let mut visited = FxHashSet::default();
2526 while let Some(block) = queue.pop() {
2527 // If we haven't visited this block before, then make sure we visit it's predecessors.
2528 if visited.insert(block) {
2529 queue.extend(predecessors[block].iter().cloned());
2534 // If we found the block that `self` is in, then we are a predecessor of `other` (since
2535 // we found that block by looking at the predecessors of `other`).
2536 if self.block == block {
2544 pub fn dominates(&self, other: Location, dominators: &Dominators<BasicBlock>) -> bool {
2545 if self.block == other.block {
2546 self.statement_index <= other.statement_index
2548 dominators.is_dominated_by(other.block, self.block)