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::coverage::{CodeRegion, CoverageKind};
6 use crate::mir::interpret::{Allocation, GlobalAlloc, Scalar};
7 use crate::mir::visit::MirVisitable;
8 use crate::ty::adjustment::PointerCast;
9 use crate::ty::codec::{TyDecoder, TyEncoder};
10 use crate::ty::fold::{TypeFoldable, TypeFolder, TypeVisitor};
11 use crate::ty::print::{FmtPrinter, Printer};
12 use crate::ty::subst::{Subst, SubstsRef};
13 use crate::ty::{self, List, Ty, TyCtxt};
14 use crate::ty::{AdtDef, InstanceDef, Region, ScalarInt, UserTypeAnnotationIndex};
16 use rustc_hir::def::{CtorKind, Namespace};
17 use rustc_hir::def_id::{DefId, CRATE_DEF_INDEX};
18 use rustc_hir::{self, GeneratorKind};
19 use rustc_target::abi::{Size, VariantIdx};
21 use polonius_engine::Atom;
22 pub use rustc_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_serialize::{Decodable, Encodable};
29 use rustc_span::symbol::Symbol;
30 use rustc_span::{Span, DUMMY_SP};
31 use rustc_target::asm::InlineAsmRegOrRegClass;
33 use std::convert::TryInto;
34 use std::fmt::{self, Debug, Display, Formatter, Write};
35 use std::ops::{ControlFlow, Index, IndexMut};
37 use std::{iter, mem, option};
39 use self::graph_cyclic_cache::GraphIsCyclicCache;
40 use self::predecessors::{PredecessorCache, Predecessors};
41 pub use self::query::*;
43 pub mod abstract_const;
45 mod graph_cyclic_cache;
52 pub use terminator::*;
58 pub type LocalDecls<'tcx> = IndexVec<Local, LocalDecl<'tcx>>;
60 pub trait HasLocalDecls<'tcx> {
61 fn local_decls(&self) -> &LocalDecls<'tcx>;
64 impl<'tcx> HasLocalDecls<'tcx> for LocalDecls<'tcx> {
66 fn local_decls(&self) -> &LocalDecls<'tcx> {
71 impl<'tcx> HasLocalDecls<'tcx> for Body<'tcx> {
73 fn local_decls(&self) -> &LocalDecls<'tcx> {
78 /// The various "big phases" that MIR goes through.
80 /// These phases all describe dialects of MIR. Since all MIR uses the same datastructures, the
81 /// dialects forbid certain variants or values in certain phases.
83 /// Note: Each phase's validation checks all invariants of the *previous* phases' dialects. A phase
84 /// that changes the dialect documents what invariants must be upheld *after* that phase finishes.
86 /// Warning: ordering of variants is significant.
87 #[derive(Copy, Clone, TyEncodable, TyDecodable, Debug, PartialEq, Eq, PartialOrd, Ord)]
91 // FIXME(oli-obk): it's unclear whether we still need this phase (and its corresponding query).
92 // We used to have this for pre-miri MIR based const eval.
94 /// This phase checks the MIR for promotable elements and takes them out of the main MIR body
95 /// by creating a new MIR body per promoted element. After this phase (and thus the termination
96 /// of the `mir_promoted` query), these promoted elements are available in the `promoted_mir`
100 /// * the only `AggregateKind`s allowed are `Array` and `Generator`,
101 /// * `DropAndReplace` is gone for good
102 /// * `Drop` now uses explicit drop flags visible in the MIR and reaching a `Drop` terminator
103 /// means that the auto-generated drop glue will be invoked.
105 /// After this phase, generators are explicit state machines (no more `Yield`).
106 /// `AggregateKind::Generator` is gone for good.
107 GeneratorLowering = 4,
112 /// Gets the index of the current MirPhase within the set of all `MirPhase`s.
113 pub fn phase_index(&self) -> usize {
118 /// Where a specific `mir::Body` comes from.
119 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
120 #[derive(HashStable, TyEncodable, TyDecodable, TypeFoldable)]
121 pub struct MirSource<'tcx> {
122 pub instance: InstanceDef<'tcx>,
124 /// If `Some`, this is a promoted rvalue within the parent function.
125 pub promoted: Option<Promoted>,
128 impl<'tcx> MirSource<'tcx> {
129 pub fn item(def_id: DefId) -> Self {
131 instance: InstanceDef::Item(ty::WithOptConstParam::unknown(def_id)),
136 pub fn from_instance(instance: InstanceDef<'tcx>) -> Self {
137 MirSource { instance, promoted: None }
140 pub fn with_opt_param(self) -> ty::WithOptConstParam<DefId> {
141 self.instance.with_opt_param()
145 pub fn def_id(&self) -> DefId {
146 self.instance.def_id()
150 #[derive(Clone, TyEncodable, TyDecodable, Debug, HashStable, TypeFoldable)]
151 pub struct GeneratorInfo<'tcx> {
152 /// The yield type of the function, if it is a generator.
153 pub yield_ty: Option<Ty<'tcx>>,
155 /// Generator drop glue.
156 pub generator_drop: Option<Body<'tcx>>,
158 /// The layout of a generator. Produced by the state transformation.
159 pub generator_layout: Option<GeneratorLayout<'tcx>>,
161 /// If this is a generator then record the type of source expression that caused this generator
163 pub generator_kind: GeneratorKind,
166 /// The lowered representation of a single function.
167 #[derive(Clone, TyEncodable, TyDecodable, Debug, HashStable, TypeFoldable)]
168 pub struct Body<'tcx> {
169 /// A list of basic blocks. References to basic block use a newtyped index type [`BasicBlock`]
170 /// that indexes into this vector.
171 basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
173 /// Records how far through the "desugaring and optimization" process this particular
174 /// MIR has traversed. This is particularly useful when inlining, since in that context
175 /// we instantiate the promoted constants and add them to our promoted vector -- but those
176 /// promoted items have already been optimized, whereas ours have not. This field allows
177 /// us to see the difference and forego optimization on the inlined promoted items.
180 pub source: MirSource<'tcx>,
182 /// A list of source scopes; these are referenced by statements
183 /// and used for debuginfo. Indexed by a `SourceScope`.
184 pub source_scopes: IndexVec<SourceScope, SourceScopeData<'tcx>>,
186 pub generator: Option<Box<GeneratorInfo<'tcx>>>,
188 /// Declarations of locals.
190 /// The first local is the return value pointer, followed by `arg_count`
191 /// locals for the function arguments, followed by any user-declared
192 /// variables and temporaries.
193 pub local_decls: LocalDecls<'tcx>,
195 /// User type annotations.
196 pub user_type_annotations: ty::CanonicalUserTypeAnnotations<'tcx>,
198 /// The number of arguments this function takes.
200 /// Starting at local 1, `arg_count` locals will be provided by the caller
201 /// and can be assumed to be initialized.
203 /// If this MIR was built for a constant, this will be 0.
204 pub arg_count: usize,
206 /// Mark an argument local (which must be a tuple) as getting passed as
207 /// its individual components at the LLVM level.
209 /// This is used for the "rust-call" ABI.
210 pub spread_arg: Option<Local>,
212 /// Debug information pertaining to user variables, including captures.
213 pub var_debug_info: Vec<VarDebugInfo<'tcx>>,
215 /// A span representing this MIR, for error reporting.
218 /// Constants that are required to evaluate successfully for this MIR to be well-formed.
219 /// We hold in this field all the constants we are not able to evaluate yet.
220 pub required_consts: Vec<Constant<'tcx>>,
222 /// Does this body use generic parameters. This is used for the `ConstEvaluatable` check.
224 /// Note that this does not actually mean that this body is not computable right now.
225 /// The repeat count in the following example is polymorphic, but can still be evaluated
226 /// without knowing anything about the type parameter `T`.
230 /// let _ = [0; std::mem::size_of::<*mut T>()];
234 /// **WARNING**: Do not change this flags after the MIR was originally created, even if an optimization
235 /// removed the last mention of all generic params. We do not want to rely on optimizations and
236 /// potentially allow things like `[u8; std::mem::size_of::<T>() * 0]` due to this.
237 pub is_polymorphic: bool,
239 predecessor_cache: PredecessorCache,
240 is_cyclic: GraphIsCyclicCache,
243 impl<'tcx> Body<'tcx> {
245 source: MirSource<'tcx>,
246 basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
247 source_scopes: IndexVec<SourceScope, SourceScopeData<'tcx>>,
248 local_decls: LocalDecls<'tcx>,
249 user_type_annotations: ty::CanonicalUserTypeAnnotations<'tcx>,
251 var_debug_info: Vec<VarDebugInfo<'tcx>>,
253 generator_kind: Option<GeneratorKind>,
255 // We need `arg_count` locals, and one for the return place.
257 local_decls.len() > arg_count,
258 "expected at least {} locals, got {}",
263 let mut body = Body {
264 phase: MirPhase::Build,
268 generator: generator_kind.map(|generator_kind| {
269 Box::new(GeneratorInfo {
271 generator_drop: None,
272 generator_layout: None,
277 user_type_annotations,
282 required_consts: Vec::new(),
283 is_polymorphic: false,
284 predecessor_cache: PredecessorCache::new(),
285 is_cyclic: GraphIsCyclicCache::new(),
287 body.is_polymorphic = body.has_param_types_or_consts();
291 /// Returns a partially initialized MIR body containing only a list of basic blocks.
293 /// The returned MIR contains no `LocalDecl`s (even for the return place) or source scopes. It
294 /// is only useful for testing but cannot be `#[cfg(test)]` because it is used in a different
296 pub fn new_cfg_only(basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>) -> Self {
297 let mut body = Body {
298 phase: MirPhase::Build,
299 source: MirSource::item(DefId::local(CRATE_DEF_INDEX)),
301 source_scopes: IndexVec::new(),
303 local_decls: IndexVec::new(),
304 user_type_annotations: IndexVec::new(),
308 required_consts: Vec::new(),
309 var_debug_info: Vec::new(),
310 is_polymorphic: false,
311 predecessor_cache: PredecessorCache::new(),
312 is_cyclic: GraphIsCyclicCache::new(),
314 body.is_polymorphic = body.has_param_types_or_consts();
319 pub fn basic_blocks(&self) -> &IndexVec<BasicBlock, BasicBlockData<'tcx>> {
324 pub fn basic_blocks_mut(&mut self) -> &mut IndexVec<BasicBlock, BasicBlockData<'tcx>> {
325 // Because the user could mutate basic block terminators via this reference, we need to
326 // invalidate the caches.
328 // FIXME: Use a finer-grained API for this, so only transformations that alter terminators
329 // invalidate the caches.
330 self.predecessor_cache.invalidate();
331 self.is_cyclic.invalidate();
332 &mut self.basic_blocks
336 pub fn basic_blocks_and_local_decls_mut(
338 ) -> (&mut IndexVec<BasicBlock, BasicBlockData<'tcx>>, &mut LocalDecls<'tcx>) {
339 self.predecessor_cache.invalidate();
340 self.is_cyclic.invalidate();
341 (&mut self.basic_blocks, &mut self.local_decls)
345 pub fn basic_blocks_local_decls_mut_and_var_debug_info(
348 &mut IndexVec<BasicBlock, BasicBlockData<'tcx>>,
349 &mut LocalDecls<'tcx>,
350 &mut Vec<VarDebugInfo<'tcx>>,
352 self.predecessor_cache.invalidate();
353 self.is_cyclic.invalidate();
354 (&mut self.basic_blocks, &mut self.local_decls, &mut self.var_debug_info)
357 /// Returns `true` if a cycle exists in the control-flow graph that is reachable from the
359 pub fn is_cfg_cyclic(&self) -> bool {
360 self.is_cyclic.is_cyclic(self)
364 pub fn local_kind(&self, local: Local) -> LocalKind {
365 let index = local.as_usize();
368 self.local_decls[local].mutability == Mutability::Mut,
369 "return place should be mutable"
372 LocalKind::ReturnPointer
373 } else if index < self.arg_count + 1 {
375 } else if self.local_decls[local].is_user_variable() {
382 /// Returns an iterator over all temporaries.
384 pub fn temps_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
385 (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
386 let local = Local::new(index);
387 if self.local_decls[local].is_user_variable() { None } else { Some(local) }
391 /// Returns an iterator over all user-declared locals.
393 pub fn vars_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
394 (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
395 let local = Local::new(index);
396 self.local_decls[local].is_user_variable().then_some(local)
400 /// Returns an iterator over all user-declared mutable locals.
402 pub fn mut_vars_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
403 (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
404 let local = Local::new(index);
405 let decl = &self.local_decls[local];
406 if decl.is_user_variable() && decl.mutability == Mutability::Mut {
414 /// Returns an iterator over all user-declared mutable arguments and locals.
416 pub fn mut_vars_and_args_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
417 (1..self.local_decls.len()).filter_map(move |index| {
418 let local = Local::new(index);
419 let decl = &self.local_decls[local];
420 if (decl.is_user_variable() || index < self.arg_count + 1)
421 && decl.mutability == Mutability::Mut
430 /// Returns an iterator over all function arguments.
432 pub fn args_iter(&self) -> impl Iterator<Item = Local> + ExactSizeIterator {
433 let arg_count = self.arg_count;
434 (1..arg_count + 1).map(Local::new)
437 /// Returns an iterator over all user-defined variables and compiler-generated temporaries (all
438 /// locals that are neither arguments nor the return place).
440 pub fn vars_and_temps_iter(
442 ) -> impl DoubleEndedIterator<Item = Local> + ExactSizeIterator {
443 let arg_count = self.arg_count;
444 let local_count = self.local_decls.len();
445 (arg_count + 1..local_count).map(Local::new)
448 /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
449 /// invalidating statement indices in `Location`s.
450 pub fn make_statement_nop(&mut self, location: Location) {
451 let block = &mut self.basic_blocks[location.block];
452 debug_assert!(location.statement_index < block.statements.len());
453 block.statements[location.statement_index].make_nop()
456 /// Returns the source info associated with `location`.
457 pub fn source_info(&self, location: Location) -> &SourceInfo {
458 let block = &self[location.block];
459 let stmts = &block.statements;
460 let idx = location.statement_index;
461 if idx < stmts.len() {
462 &stmts[idx].source_info
464 assert_eq!(idx, stmts.len());
465 &block.terminator().source_info
469 /// Returns the return type; it always return first element from `local_decls` array.
471 pub fn return_ty(&self) -> Ty<'tcx> {
472 self.local_decls[RETURN_PLACE].ty
475 /// Gets the location of the terminator for the given block.
477 pub fn terminator_loc(&self, bb: BasicBlock) -> Location {
478 Location { block: bb, statement_index: self[bb].statements.len() }
482 pub fn predecessors(&self) -> impl std::ops::Deref<Target = Predecessors> + '_ {
483 self.predecessor_cache.compute(&self.basic_blocks)
487 pub fn dominators(&self) -> Dominators<BasicBlock> {
492 pub fn yield_ty(&self) -> Option<Ty<'tcx>> {
493 self.generator.as_ref().and_then(|generator| generator.yield_ty)
497 pub fn generator_layout(&self) -> Option<&GeneratorLayout<'tcx>> {
498 self.generator.as_ref().and_then(|generator| generator.generator_layout.as_ref())
502 pub fn generator_drop(&self) -> Option<&Body<'tcx>> {
503 self.generator.as_ref().and_then(|generator| generator.generator_drop.as_ref())
507 pub fn generator_kind(&self) -> Option<GeneratorKind> {
508 self.generator.as_ref().map(|generator| generator.generator_kind)
512 #[derive(Copy, Clone, PartialEq, Eq, Debug, TyEncodable, TyDecodable, HashStable)]
515 /// Unsafe because of a PushUnsafeBlock
517 /// Unsafe because of an unsafe fn
519 /// Unsafe because of an `unsafe` block
520 ExplicitUnsafe(hir::HirId),
523 impl<'tcx> Index<BasicBlock> for Body<'tcx> {
524 type Output = BasicBlockData<'tcx>;
527 fn index(&self, index: BasicBlock) -> &BasicBlockData<'tcx> {
528 &self.basic_blocks()[index]
532 impl<'tcx> IndexMut<BasicBlock> for Body<'tcx> {
534 fn index_mut(&mut self, index: BasicBlock) -> &mut BasicBlockData<'tcx> {
535 &mut self.basic_blocks_mut()[index]
539 #[derive(Copy, Clone, Debug, HashStable, TypeFoldable)]
540 pub enum ClearCrossCrate<T> {
545 impl<T> ClearCrossCrate<T> {
546 pub fn as_ref(&self) -> ClearCrossCrate<&T> {
548 ClearCrossCrate::Clear => ClearCrossCrate::Clear,
549 ClearCrossCrate::Set(v) => ClearCrossCrate::Set(v),
553 pub fn assert_crate_local(self) -> T {
555 ClearCrossCrate::Clear => bug!("unwrapping cross-crate data"),
556 ClearCrossCrate::Set(v) => v,
561 const TAG_CLEAR_CROSS_CRATE_CLEAR: u8 = 0;
562 const TAG_CLEAR_CROSS_CRATE_SET: u8 = 1;
564 impl<'tcx, E: TyEncoder<'tcx>, T: Encodable<E>> Encodable<E> for ClearCrossCrate<T> {
566 fn encode(&self, e: &mut E) -> Result<(), E::Error> {
567 if E::CLEAR_CROSS_CRATE {
572 ClearCrossCrate::Clear => TAG_CLEAR_CROSS_CRATE_CLEAR.encode(e),
573 ClearCrossCrate::Set(ref val) => {
574 TAG_CLEAR_CROSS_CRATE_SET.encode(e)?;
580 impl<'tcx, D: TyDecoder<'tcx>, T: Decodable<D>> Decodable<D> for ClearCrossCrate<T> {
582 fn decode(d: &mut D) -> Result<ClearCrossCrate<T>, D::Error> {
583 if D::CLEAR_CROSS_CRATE {
584 return Ok(ClearCrossCrate::Clear);
587 let discr = u8::decode(d)?;
590 TAG_CLEAR_CROSS_CRATE_CLEAR => Ok(ClearCrossCrate::Clear),
591 TAG_CLEAR_CROSS_CRATE_SET => {
592 let val = T::decode(d)?;
593 Ok(ClearCrossCrate::Set(val))
595 tag => Err(d.error(&format!("Invalid tag for ClearCrossCrate: {:?}", tag))),
600 /// Grouped information about the source code origin of a MIR entity.
601 /// Intended to be inspected by diagnostics and debuginfo.
602 /// Most passes can work with it as a whole, within a single function.
603 // The unofficial Cranelift backend, at least as of #65828, needs `SourceInfo` to implement `Eq` and
604 // `Hash`. Please ping @bjorn3 if removing them.
605 #[derive(Copy, Clone, Debug, Eq, PartialEq, TyEncodable, TyDecodable, Hash, HashStable)]
606 pub struct SourceInfo {
607 /// The source span for the AST pertaining to this MIR entity.
610 /// The source scope, keeping track of which bindings can be
611 /// seen by debuginfo, active lint levels, `unsafe {...}`, etc.
612 pub scope: SourceScope,
617 pub fn outermost(span: Span) -> Self {
618 SourceInfo { span, scope: OUTERMOST_SOURCE_SCOPE }
622 ///////////////////////////////////////////////////////////////////////////
625 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, TyEncodable, TyDecodable)]
626 #[derive(Hash, HashStable)]
627 pub enum BorrowKind {
628 /// Data must be immutable and is aliasable.
631 /// The immediately borrowed place must be immutable, but projections from
632 /// it don't need to be. For example, a shallow borrow of `a.b` doesn't
633 /// conflict with a mutable borrow of `a.b.c`.
635 /// This is used when lowering matches: when matching on a place we want to
636 /// ensure that place have the same value from the start of the match until
637 /// an arm is selected. This prevents this code from compiling:
639 /// let mut x = &Some(0);
642 /// Some(_) if { x = &None; false } => (),
646 /// This can't be a shared borrow because mutably borrowing (*x as Some).0
647 /// should not prevent `if let None = x { ... }`, for example, because the
648 /// mutating `(*x as Some).0` can't affect the discriminant of `x`.
649 /// We can also report errors with this kind of borrow differently.
652 /// Data must be immutable but not aliasable. This kind of borrow
653 /// cannot currently be expressed by the user and is used only in
654 /// implicit closure bindings. It is needed when the closure is
655 /// borrowing or mutating a mutable referent, e.g.:
657 /// let x: &mut isize = ...;
658 /// let y = || *x += 5;
660 /// If we were to try to translate this closure into a more explicit
661 /// form, we'd encounter an error with the code as written:
663 /// struct Env { x: & &mut isize }
664 /// let x: &mut isize = ...;
665 /// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn
666 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
668 /// This is then illegal because you cannot mutate an `&mut` found
669 /// in an aliasable location. To solve, you'd have to translate with
670 /// an `&mut` borrow:
672 /// struct Env { x: & &mut isize }
673 /// let x: &mut isize = ...;
674 /// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
675 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
677 /// Now the assignment to `**env.x` is legal, but creating a
678 /// mutable pointer to `x` is not because `x` is not mutable. We
679 /// could fix this by declaring `x` as `let mut x`. This is ok in
680 /// user code, if awkward, but extra weird for closures, since the
681 /// borrow is hidden.
683 /// So we introduce a "unique imm" borrow -- the referent is
684 /// immutable, but not aliasable. This solves the problem. For
685 /// simplicity, we don't give users the way to express this
686 /// borrow, it's just used when translating closures.
689 /// Data is mutable and not aliasable.
691 /// `true` if this borrow arose from method-call auto-ref
692 /// (i.e., `adjustment::Adjust::Borrow`).
693 allow_two_phase_borrow: bool,
698 pub fn allows_two_phase_borrow(&self) -> bool {
700 BorrowKind::Shared | BorrowKind::Shallow | BorrowKind::Unique => false,
701 BorrowKind::Mut { allow_two_phase_borrow } => allow_two_phase_borrow,
706 ///////////////////////////////////////////////////////////////////////////
707 // Variables and temps
709 rustc_index::newtype_index! {
712 DEBUG_FORMAT = "_{}",
713 const RETURN_PLACE = 0,
717 impl Atom for Local {
718 fn index(self) -> usize {
723 /// Classifies locals into categories. See `Body::local_kind`.
724 #[derive(Clone, Copy, PartialEq, Eq, Debug, HashStable)]
726 /// User-declared variable binding.
728 /// Compiler-introduced temporary.
730 /// Function argument.
732 /// Location of function's return value.
736 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable)]
737 pub struct VarBindingForm<'tcx> {
738 /// Is variable bound via `x`, `mut x`, `ref x`, or `ref mut x`?
739 pub binding_mode: ty::BindingMode,
740 /// If an explicit type was provided for this variable binding,
741 /// this holds the source Span of that type.
743 /// NOTE: if you want to change this to a `HirId`, be wary that
744 /// doing so breaks incremental compilation (as of this writing),
745 /// while a `Span` does not cause our tests to fail.
746 pub opt_ty_info: Option<Span>,
747 /// Place of the RHS of the =, or the subject of the `match` where this
748 /// variable is initialized. None in the case of `let PATTERN;`.
749 /// Some((None, ..)) in the case of and `let [mut] x = ...` because
750 /// (a) the right-hand side isn't evaluated as a place expression.
751 /// (b) it gives a way to separate this case from the remaining cases
753 pub opt_match_place: Option<(Option<Place<'tcx>>, Span)>,
754 /// The span of the pattern in which this variable was bound.
758 #[derive(Clone, Debug, TyEncodable, TyDecodable)]
759 pub enum BindingForm<'tcx> {
760 /// This is a binding for a non-`self` binding, or a `self` that has an explicit type.
761 Var(VarBindingForm<'tcx>),
762 /// Binding for a `self`/`&self`/`&mut self` binding where the type is implicit.
763 ImplicitSelf(ImplicitSelfKind),
764 /// Reference used in a guard expression to ensure immutability.
768 /// Represents what type of implicit self a function has, if any.
769 #[derive(Clone, Copy, PartialEq, Debug, TyEncodable, TyDecodable, HashStable)]
770 pub enum ImplicitSelfKind {
771 /// Represents a `fn x(self);`.
773 /// Represents a `fn x(mut self);`.
775 /// Represents a `fn x(&self);`.
777 /// Represents a `fn x(&mut self);`.
779 /// Represents when a function does not have a self argument or
780 /// when a function has a `self: X` argument.
784 TrivialTypeFoldableAndLiftImpls! { BindingForm<'tcx>, }
786 mod binding_form_impl {
787 use crate::ich::StableHashingContext;
788 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
790 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for super::BindingForm<'tcx> {
791 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
792 use super::BindingForm::*;
793 std::mem::discriminant(self).hash_stable(hcx, hasher);
796 Var(binding) => binding.hash_stable(hcx, hasher),
797 ImplicitSelf(kind) => kind.hash_stable(hcx, hasher),
804 /// `BlockTailInfo` is attached to the `LocalDecl` for temporaries
805 /// created during evaluation of expressions in a block tail
806 /// expression; that is, a block like `{ STMT_1; STMT_2; EXPR }`.
808 /// It is used to improve diagnostics when such temporaries are
809 /// involved in borrow_check errors, e.g., explanations of where the
810 /// temporaries come from, when their destructors are run, and/or how
811 /// one might revise the code to satisfy the borrow checker's rules.
812 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable)]
813 pub struct BlockTailInfo {
814 /// If `true`, then the value resulting from evaluating this tail
815 /// expression is ignored by the block's expression context.
817 /// Examples include `{ ...; tail };` and `let _ = { ...; tail };`
818 /// but not e.g., `let _x = { ...; tail };`
819 pub tail_result_is_ignored: bool,
821 /// `Span` of the tail expression.
827 /// This can be a binding declared by the user, a temporary inserted by the compiler, a function
828 /// argument, or the return place.
829 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
830 pub struct LocalDecl<'tcx> {
831 /// Whether this is a mutable binding (i.e., `let x` or `let mut x`).
833 /// Temporaries and the return place are always mutable.
834 pub mutability: Mutability,
836 // FIXME(matthewjasper) Don't store in this in `Body`
837 pub local_info: Option<Box<LocalInfo<'tcx>>>,
839 /// `true` if this is an internal local.
841 /// These locals are not based on types in the source code and are only used
842 /// for a few desugarings at the moment.
844 /// The generator transformation will sanity check the locals which are live
845 /// across a suspension point against the type components of the generator
846 /// which type checking knows are live across a suspension point. We need to
847 /// flag drop flags to avoid triggering this check as they are introduced
850 /// This should be sound because the drop flags are fully algebraic, and
851 /// therefore don't affect the auto-trait or outlives properties of the
855 /// If this local is a temporary and `is_block_tail` is `Some`,
856 /// then it is a temporary created for evaluation of some
857 /// subexpression of some block's tail expression (with no
858 /// intervening statement context).
859 // FIXME(matthewjasper) Don't store in this in `Body`
860 pub is_block_tail: Option<BlockTailInfo>,
862 /// The type of this local.
865 /// If the user manually ascribed a type to this variable,
866 /// e.g., via `let x: T`, then we carry that type here. The MIR
867 /// borrow checker needs this information since it can affect
868 /// region inference.
869 // FIXME(matthewjasper) Don't store in this in `Body`
870 pub user_ty: Option<Box<UserTypeProjections>>,
872 /// The *syntactic* (i.e., not visibility) source scope the local is defined
873 /// in. If the local was defined in a let-statement, this
874 /// is *within* the let-statement, rather than outside
877 /// This is needed because the visibility source scope of locals within
878 /// a let-statement is weird.
880 /// The reason is that we want the local to be *within* the let-statement
881 /// for lint purposes, but we want the local to be *after* the let-statement
882 /// for names-in-scope purposes.
884 /// That's it, if we have a let-statement like the one in this
888 /// fn foo(x: &str) {
889 /// #[allow(unused_mut)]
890 /// let mut x: u32 = { // <- one unused mut
891 /// let mut y: u32 = x.parse().unwrap();
898 /// Then, from a lint point of view, the declaration of `x: u32`
899 /// (and `y: u32`) are within the `#[allow(unused_mut)]` scope - the
900 /// lint scopes are the same as the AST/HIR nesting.
902 /// However, from a name lookup point of view, the scopes look more like
903 /// as if the let-statements were `match` expressions:
906 /// fn foo(x: &str) {
908 /// match x.parse().unwrap() {
917 /// We care about the name-lookup scopes for debuginfo - if the
918 /// debuginfo instruction pointer is at the call to `x.parse()`, we
919 /// want `x` to refer to `x: &str`, but if it is at the call to
920 /// `drop(x)`, we want it to refer to `x: u32`.
922 /// To allow both uses to work, we need to have more than a single scope
923 /// for a local. We have the `source_info.scope` represent the "syntactic"
924 /// lint scope (with a variable being under its let block) while the
925 /// `var_debug_info.source_info.scope` represents the "local variable"
926 /// scope (where the "rest" of a block is under all prior let-statements).
928 /// The end result looks like this:
932 /// │{ argument x: &str }
934 /// │ │{ #[allow(unused_mut)] } // This is actually split into 2 scopes
935 /// │ │ // in practice because I'm lazy.
937 /// │ │← x.source_info.scope
938 /// │ │← `x.parse().unwrap()`
940 /// │ │ │← y.source_info.scope
942 /// │ │ │{ let y: u32 }
944 /// │ │ │← y.var_debug_info.source_info.scope
947 /// │ │{ let x: u32 }
948 /// │ │← x.var_debug_info.source_info.scope
949 /// │ │← `drop(x)` // This accesses `x: u32`.
951 pub source_info: SourceInfo,
954 // `LocalDecl` is used a lot. Make sure it doesn't unintentionally get bigger.
955 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
956 static_assert_size!(LocalDecl<'_>, 56);
958 /// Extra information about a some locals that's used for diagnostics and for
959 /// classifying variables into local variables, statics, etc, which is needed e.g.
960 /// for unsafety checking.
962 /// Not used for non-StaticRef temporaries, the return place, or anonymous
963 /// function parameters.
964 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
965 pub enum LocalInfo<'tcx> {
966 /// A user-defined local variable or function parameter
968 /// The `BindingForm` is solely used for local diagnostics when generating
969 /// warnings/errors when compiling the current crate, and therefore it need
970 /// not be visible across crates.
971 User(ClearCrossCrate<BindingForm<'tcx>>),
972 /// A temporary created that references the static with the given `DefId`.
973 StaticRef { def_id: DefId, is_thread_local: bool },
974 /// A temporary created that references the const with the given `DefId`
975 ConstRef { def_id: DefId },
978 impl<'tcx> LocalDecl<'tcx> {
979 /// Returns `true` only if local is a binding that can itself be
980 /// made mutable via the addition of the `mut` keyword, namely
981 /// something like the occurrences of `x` in:
982 /// - `fn foo(x: Type) { ... }`,
984 /// - or `match ... { C(x) => ... }`
985 pub fn can_be_made_mutable(&self) -> bool {
988 Some(box LocalInfo::User(ClearCrossCrate::Set(
989 BindingForm::Var(VarBindingForm {
990 binding_mode: ty::BindingMode::BindByValue(_),
994 }) | BindingForm::ImplicitSelf(ImplicitSelfKind::Imm),
999 /// Returns `true` if local is definitely not a `ref ident` or
1000 /// `ref mut ident` binding. (Such bindings cannot be made into
1001 /// mutable bindings, but the inverse does not necessarily hold).
1002 pub fn is_nonref_binding(&self) -> bool {
1005 Some(box LocalInfo::User(ClearCrossCrate::Set(
1006 BindingForm::Var(VarBindingForm {
1007 binding_mode: ty::BindingMode::BindByValue(_),
1011 }) | BindingForm::ImplicitSelf(_),
1016 /// Returns `true` if this variable is a named variable or function
1017 /// parameter declared by the user.
1019 pub fn is_user_variable(&self) -> bool {
1020 matches!(self.local_info, Some(box LocalInfo::User(_)))
1023 /// Returns `true` if this is a reference to a variable bound in a `match`
1024 /// expression that is used to access said variable for the guard of the
1026 pub fn is_ref_for_guard(&self) -> bool {
1029 Some(box LocalInfo::User(ClearCrossCrate::Set(BindingForm::RefForGuard)))
1033 /// Returns `Some` if this is a reference to a static item that is used to
1034 /// access that static.
1035 pub fn is_ref_to_static(&self) -> bool {
1036 matches!(self.local_info, Some(box LocalInfo::StaticRef { .. }))
1039 /// Returns `Some` if this is a reference to a thread-local static item that is used to
1040 /// access that static.
1041 pub fn is_ref_to_thread_local(&self) -> bool {
1042 match self.local_info {
1043 Some(box LocalInfo::StaticRef { is_thread_local, .. }) => is_thread_local,
1048 /// Returns `true` is the local is from a compiler desugaring, e.g.,
1049 /// `__next` from a `for` loop.
1051 pub fn from_compiler_desugaring(&self) -> bool {
1052 self.source_info.span.desugaring_kind().is_some()
1055 /// Creates a new `LocalDecl` for a temporary: mutable, non-internal.
1057 pub fn new(ty: Ty<'tcx>, span: Span) -> Self {
1058 Self::with_source_info(ty, SourceInfo::outermost(span))
1061 /// Like `LocalDecl::new`, but takes a `SourceInfo` instead of a `Span`.
1063 pub fn with_source_info(ty: Ty<'tcx>, source_info: SourceInfo) -> Self {
1065 mutability: Mutability::Mut,
1068 is_block_tail: None,
1075 /// Converts `self` into same `LocalDecl` except tagged as internal.
1077 pub fn internal(mut self) -> Self {
1078 self.internal = true;
1082 /// Converts `self` into same `LocalDecl` except tagged as immutable.
1084 pub fn immutable(mut self) -> Self {
1085 self.mutability = Mutability::Not;
1089 /// Converts `self` into same `LocalDecl` except tagged as internal temporary.
1091 pub fn block_tail(mut self, info: BlockTailInfo) -> Self {
1092 assert!(self.is_block_tail.is_none());
1093 self.is_block_tail = Some(info);
1098 #[derive(Clone, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
1099 pub enum VarDebugInfoContents<'tcx> {
1100 /// NOTE(eddyb) There's an unenforced invariant that this `Place` is
1101 /// based on a `Local`, not a `Static`, and contains no indexing.
1103 Const(Constant<'tcx>),
1106 impl<'tcx> Debug for VarDebugInfoContents<'tcx> {
1107 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1109 VarDebugInfoContents::Const(c) => write!(fmt, "{}", c),
1110 VarDebugInfoContents::Place(p) => write!(fmt, "{:?}", p),
1115 /// Debug information pertaining to a user variable.
1116 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
1117 pub struct VarDebugInfo<'tcx> {
1120 /// Source info of the user variable, including the scope
1121 /// within which the variable is visible (to debuginfo)
1122 /// (see `LocalDecl`'s `source_info` field for more details).
1123 pub source_info: SourceInfo,
1125 /// Where the data for this user variable is to be found.
1126 pub value: VarDebugInfoContents<'tcx>,
1129 ///////////////////////////////////////////////////////////////////////////
1132 rustc_index::newtype_index! {
1133 /// A node in the MIR [control-flow graph][CFG].
1135 /// There are no branches (e.g., `if`s, function calls, etc.) within a basic block, which makes
1136 /// it easier to do [data-flow analyses] and optimizations. Instead, branches are represented
1137 /// as an edge in a graph between basic blocks.
1139 /// Basic blocks consist of a series of [statements][Statement], ending with a
1140 /// [terminator][Terminator]. Basic blocks can have multiple predecessors and successors,
1141 /// however there is a MIR pass ([`CriticalCallEdges`]) that removes *critical edges*, which
1142 /// are edges that go from a multi-successor node to a multi-predecessor node. This pass is
1143 /// needed because some analyses require that there are no critical edges in the CFG.
1145 /// Note that this type is just an index into [`Body.basic_blocks`](Body::basic_blocks);
1146 /// the actual data that a basic block holds is in [`BasicBlockData`].
1148 /// Read more about basic blocks in the [rustc-dev-guide][guide-mir].
1150 /// [CFG]: https://rustc-dev-guide.rust-lang.org/appendix/background.html#cfg
1151 /// [data-flow analyses]:
1152 /// https://rustc-dev-guide.rust-lang.org/appendix/background.html#what-is-a-dataflow-analysis
1153 /// [`CriticalCallEdges`]: ../../rustc_mir/transform/add_call_guards/enum.AddCallGuards.html#variant.CriticalCallEdges
1154 /// [guide-mir]: https://rustc-dev-guide.rust-lang.org/mir/
1155 pub struct BasicBlock {
1157 DEBUG_FORMAT = "bb{}",
1158 const START_BLOCK = 0,
1163 pub fn start_location(self) -> Location {
1164 Location { block: self, statement_index: 0 }
1168 ///////////////////////////////////////////////////////////////////////////
1169 // BasicBlockData and Terminator
1171 /// See [`BasicBlock`] for documentation on what basic blocks are at a high level.
1172 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
1173 pub struct BasicBlockData<'tcx> {
1174 /// List of statements in this block.
1175 pub statements: Vec<Statement<'tcx>>,
1177 /// Terminator for this block.
1179 /// N.B., this should generally ONLY be `None` during construction.
1180 /// Therefore, you should generally access it via the
1181 /// `terminator()` or `terminator_mut()` methods. The only
1182 /// exception is that certain passes, such as `simplify_cfg`, swap
1183 /// out the terminator temporarily with `None` while they continue
1184 /// to recurse over the set of basic blocks.
1185 pub terminator: Option<Terminator<'tcx>>,
1187 /// If true, this block lies on an unwind path. This is used
1188 /// during codegen where distinct kinds of basic blocks may be
1189 /// generated (particularly for MSVC cleanup). Unwind blocks must
1190 /// only branch to other unwind blocks.
1191 pub is_cleanup: bool,
1194 /// Information about an assertion failure.
1195 #[derive(Clone, TyEncodable, TyDecodable, Hash, HashStable, PartialEq, PartialOrd)]
1196 pub enum AssertKind<O> {
1197 BoundsCheck { len: O, index: O },
1198 Overflow(BinOp, O, O),
1202 ResumedAfterReturn(GeneratorKind),
1203 ResumedAfterPanic(GeneratorKind),
1217 pub enum InlineAsmOperand<'tcx> {
1219 reg: InlineAsmRegOrRegClass,
1220 value: Operand<'tcx>,
1223 reg: InlineAsmRegOrRegClass,
1225 place: Option<Place<'tcx>>,
1228 reg: InlineAsmRegOrRegClass,
1230 in_value: Operand<'tcx>,
1231 out_place: Option<Place<'tcx>>,
1234 value: Operand<'tcx>,
1237 value: Box<Constant<'tcx>>,
1244 /// Type for MIR `Assert` terminator error messages.
1245 pub type AssertMessage<'tcx> = AssertKind<Operand<'tcx>>;
1247 pub type Successors<'a> =
1248 iter::Chain<option::IntoIter<&'a BasicBlock>, slice::Iter<'a, BasicBlock>>;
1249 pub type SuccessorsMut<'a> =
1250 iter::Chain<option::IntoIter<&'a mut BasicBlock>, slice::IterMut<'a, BasicBlock>>;
1252 impl<'tcx> BasicBlockData<'tcx> {
1253 pub fn new(terminator: Option<Terminator<'tcx>>) -> BasicBlockData<'tcx> {
1254 BasicBlockData { statements: vec![], terminator, is_cleanup: false }
1257 /// Accessor for terminator.
1259 /// Terminator may not be None after construction of the basic block is complete. This accessor
1260 /// provides a convenience way to reach the terminator.
1261 pub fn terminator(&self) -> &Terminator<'tcx> {
1262 self.terminator.as_ref().expect("invalid terminator state")
1265 pub fn terminator_mut(&mut self) -> &mut Terminator<'tcx> {
1266 self.terminator.as_mut().expect("invalid terminator state")
1269 pub fn retain_statements<F>(&mut self, mut f: F)
1271 F: FnMut(&mut Statement<'_>) -> bool,
1273 for s in &mut self.statements {
1280 pub fn expand_statements<F, I>(&mut self, mut f: F)
1282 F: FnMut(&mut Statement<'tcx>) -> Option<I>,
1283 I: iter::TrustedLen<Item = Statement<'tcx>>,
1285 // Gather all the iterators we'll need to splice in, and their positions.
1286 let mut splices: Vec<(usize, I)> = vec![];
1287 let mut extra_stmts = 0;
1288 for (i, s) in self.statements.iter_mut().enumerate() {
1289 if let Some(mut new_stmts) = f(s) {
1290 if let Some(first) = new_stmts.next() {
1291 // We can already store the first new statement.
1294 // Save the other statements for optimized splicing.
1295 let remaining = new_stmts.size_hint().0;
1297 splices.push((i + 1 + extra_stmts, new_stmts));
1298 extra_stmts += remaining;
1306 // Splice in the new statements, from the end of the block.
1307 // FIXME(eddyb) This could be more efficient with a "gap buffer"
1308 // where a range of elements ("gap") is left uninitialized, with
1309 // splicing adding new elements to the end of that gap and moving
1310 // existing elements from before the gap to the end of the gap.
1311 // For now, this is safe code, emulating a gap but initializing it.
1312 let mut gap = self.statements.len()..self.statements.len() + extra_stmts;
1313 self.statements.resize(
1315 Statement { source_info: SourceInfo::outermost(DUMMY_SP), kind: StatementKind::Nop },
1317 for (splice_start, new_stmts) in splices.into_iter().rev() {
1318 let splice_end = splice_start + new_stmts.size_hint().0;
1319 while gap.end > splice_end {
1322 self.statements.swap(gap.start, gap.end);
1324 self.statements.splice(splice_start..splice_end, new_stmts);
1325 gap.end = splice_start;
1329 pub fn visitable(&self, index: usize) -> &dyn MirVisitable<'tcx> {
1330 if index < self.statements.len() { &self.statements[index] } else { &self.terminator }
1334 impl<O> AssertKind<O> {
1335 /// Getting a description does not require `O` to be printable, and does not
1336 /// require allocation.
1337 /// The caller is expected to handle `BoundsCheck` separately.
1338 pub fn description(&self) -> &'static str {
1341 Overflow(BinOp::Add, _, _) => "attempt to add with overflow",
1342 Overflow(BinOp::Sub, _, _) => "attempt to subtract with overflow",
1343 Overflow(BinOp::Mul, _, _) => "attempt to multiply with overflow",
1344 Overflow(BinOp::Div, _, _) => "attempt to divide with overflow",
1345 Overflow(BinOp::Rem, _, _) => "attempt to calculate the remainder with overflow",
1346 OverflowNeg(_) => "attempt to negate with overflow",
1347 Overflow(BinOp::Shr, _, _) => "attempt to shift right with overflow",
1348 Overflow(BinOp::Shl, _, _) => "attempt to shift left with overflow",
1349 Overflow(op, _, _) => bug!("{:?} cannot overflow", op),
1350 DivisionByZero(_) => "attempt to divide by zero",
1351 RemainderByZero(_) => "attempt to calculate the remainder with a divisor of zero",
1352 ResumedAfterReturn(GeneratorKind::Gen) => "generator resumed after completion",
1353 ResumedAfterReturn(GeneratorKind::Async(_)) => "`async fn` resumed after completion",
1354 ResumedAfterPanic(GeneratorKind::Gen) => "generator resumed after panicking",
1355 ResumedAfterPanic(GeneratorKind::Async(_)) => "`async fn` resumed after panicking",
1356 BoundsCheck { .. } => bug!("Unexpected AssertKind"),
1360 /// Format the message arguments for the `assert(cond, msg..)` terminator in MIR printing.
1361 fn fmt_assert_args<W: Write>(&self, f: &mut W) -> fmt::Result
1367 BoundsCheck { ref len, ref index } => write!(
1369 "\"index out of bounds: the length is {{}} but the index is {{}}\", {:?}, {:?}",
1373 OverflowNeg(op) => {
1374 write!(f, "\"attempt to negate `{{}}`, which would overflow\", {:?}", op)
1376 DivisionByZero(op) => write!(f, "\"attempt to divide `{{}}` by zero\", {:?}", op),
1377 RemainderByZero(op) => write!(
1379 "\"attempt to calculate the remainder of `{{}}` with a divisor of zero\", {:?}",
1382 Overflow(BinOp::Add, l, r) => write!(
1384 "\"attempt to compute `{{}} + {{}}`, which would overflow\", {:?}, {:?}",
1387 Overflow(BinOp::Sub, l, r) => write!(
1389 "\"attempt to compute `{{}} - {{}}`, which would overflow\", {:?}, {:?}",
1392 Overflow(BinOp::Mul, l, r) => write!(
1394 "\"attempt to compute `{{}} * {{}}`, which would overflow\", {:?}, {:?}",
1397 Overflow(BinOp::Div, l, r) => write!(
1399 "\"attempt to compute `{{}} / {{}}`, which would overflow\", {:?}, {:?}",
1402 Overflow(BinOp::Rem, l, r) => write!(
1404 "\"attempt to compute the remainder of `{{}} % {{}}`, which would overflow\", {:?}, {:?}",
1407 Overflow(BinOp::Shr, _, r) => {
1408 write!(f, "\"attempt to shift right by `{{}}`, which would overflow\", {:?}", r)
1410 Overflow(BinOp::Shl, _, r) => {
1411 write!(f, "\"attempt to shift left by `{{}}`, which would overflow\", {:?}", r)
1413 _ => write!(f, "\"{}\"", self.description()),
1418 impl<O: fmt::Debug> fmt::Debug for AssertKind<O> {
1419 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1422 BoundsCheck { ref len, ref index } => write!(
1424 "index out of bounds: the length is {:?} but the index is {:?}",
1427 OverflowNeg(op) => write!(f, "attempt to negate `{:#?}`, which would overflow", op),
1428 DivisionByZero(op) => write!(f, "attempt to divide `{:#?}` by zero", op),
1429 RemainderByZero(op) => write!(
1431 "attempt to calculate the remainder of `{:#?}` with a divisor of zero",
1434 Overflow(BinOp::Add, l, r) => {
1435 write!(f, "attempt to compute `{:#?} + {:#?}`, which would overflow", l, r)
1437 Overflow(BinOp::Sub, l, r) => {
1438 write!(f, "attempt to compute `{:#?} - {:#?}`, which would overflow", l, r)
1440 Overflow(BinOp::Mul, l, r) => {
1441 write!(f, "attempt to compute `{:#?} * {:#?}`, which would overflow", l, r)
1443 Overflow(BinOp::Div, l, r) => {
1444 write!(f, "attempt to compute `{:#?} / {:#?}`, which would overflow", l, r)
1446 Overflow(BinOp::Rem, l, r) => write!(
1448 "attempt to compute the remainder of `{:#?} % {:#?}`, which would overflow",
1451 Overflow(BinOp::Shr, _, r) => {
1452 write!(f, "attempt to shift right by `{:#?}`, which would overflow", r)
1454 Overflow(BinOp::Shl, _, r) => {
1455 write!(f, "attempt to shift left by `{:#?}`, which would overflow", r)
1457 _ => write!(f, "{}", self.description()),
1462 ///////////////////////////////////////////////////////////////////////////
1465 #[derive(Clone, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
1466 pub struct Statement<'tcx> {
1467 pub source_info: SourceInfo,
1468 pub kind: StatementKind<'tcx>,
1471 // `Statement` is used a lot. Make sure it doesn't unintentionally get bigger.
1472 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
1473 static_assert_size!(Statement<'_>, 32);
1475 impl Statement<'_> {
1476 /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
1477 /// invalidating statement indices in `Location`s.
1478 pub fn make_nop(&mut self) {
1479 self.kind = StatementKind::Nop
1482 /// Changes a statement to a nop and returns the original statement.
1483 pub fn replace_nop(&mut self) -> Self {
1485 source_info: self.source_info,
1486 kind: mem::replace(&mut self.kind, StatementKind::Nop),
1491 #[derive(Clone, Debug, PartialEq, TyEncodable, TyDecodable, Hash, HashStable, TypeFoldable)]
1492 pub enum StatementKind<'tcx> {
1493 /// Write the RHS Rvalue to the LHS Place.
1494 Assign(Box<(Place<'tcx>, Rvalue<'tcx>)>),
1496 /// This represents all the reading that a pattern match may do
1497 /// (e.g., inspecting constants and discriminant values), and the
1498 /// kind of pattern it comes from. This is in order to adapt potential
1499 /// error messages to these specific patterns.
1501 /// Note that this also is emitted for regular `let` bindings to ensure that locals that are
1502 /// never accessed still get some sanity checks for, e.g., `let x: ! = ..;`
1503 FakeRead(FakeReadCause, Box<Place<'tcx>>),
1505 /// Write the discriminant for a variant to the enum Place.
1506 SetDiscriminant { place: Box<Place<'tcx>>, variant_index: VariantIdx },
1508 /// Start a live range for the storage of the local.
1511 /// End the current live range for the storage of the local.
1514 /// Executes a piece of inline Assembly. Stored in a Box to keep the size
1515 /// of `StatementKind` low.
1516 LlvmInlineAsm(Box<LlvmInlineAsm<'tcx>>),
1518 /// Retag references in the given place, ensuring they got fresh tags. This is
1519 /// part of the Stacked Borrows model. These statements are currently only interpreted
1520 /// by miri and only generated when "-Z mir-emit-retag" is passed.
1521 /// See <https://internals.rust-lang.org/t/stacked-borrows-an-aliasing-model-for-rust/8153/>
1522 /// for more details.
1523 Retag(RetagKind, Box<Place<'tcx>>),
1525 /// Encodes a user's type ascription. These need to be preserved
1526 /// intact so that NLL can respect them. For example:
1530 /// The effect of this annotation is to relate the type `T_y` of the place `y`
1531 /// to the user-given type `T`. The effect depends on the specified variance:
1533 /// - `Covariant` -- requires that `T_y <: T`
1534 /// - `Contravariant` -- requires that `T_y :> T`
1535 /// - `Invariant` -- requires that `T_y == T`
1536 /// - `Bivariant` -- no effect
1537 AscribeUserType(Box<(Place<'tcx>, UserTypeProjection)>, ty::Variance),
1539 /// Marks the start of a "coverage region", injected with '-Zinstrument-coverage'. A
1540 /// `Coverage` statement carries metadata about the coverage region, used to inject a coverage
1541 /// map into the binary. If `Coverage::kind` is a `Counter`, the statement also generates
1542 /// executable code, to increment a counter varible at runtime, each time the code region is
1544 Coverage(Box<Coverage>),
1546 /// Denotes a call to the intrinsic function copy_overlapping, where `src_dst` denotes the
1547 /// memory being read from and written to(one field to save memory), and size
1548 /// indicates how many bytes are being copied over.
1549 CopyNonOverlapping(Box<CopyNonOverlapping<'tcx>>),
1551 /// No-op. Useful for deleting instructions without affecting statement indices.
1555 impl<'tcx> StatementKind<'tcx> {
1556 pub fn as_assign_mut(&mut self) -> Option<&mut (Place<'tcx>, Rvalue<'tcx>)> {
1558 StatementKind::Assign(x) => Some(x),
1563 pub fn as_assign(&self) -> Option<&(Place<'tcx>, Rvalue<'tcx>)> {
1565 StatementKind::Assign(x) => Some(x),
1571 /// Describes what kind of retag is to be performed.
1572 #[derive(Copy, Clone, TyEncodable, TyDecodable, Debug, PartialEq, Eq, Hash, HashStable)]
1573 pub enum RetagKind {
1574 /// The initial retag when entering a function.
1576 /// Retag preparing for a two-phase borrow.
1578 /// Retagging raw pointers.
1580 /// A "normal" retag.
1584 /// The `FakeReadCause` describes the type of pattern why a FakeRead statement exists.
1585 #[derive(Copy, Clone, TyEncodable, TyDecodable, Debug, Hash, HashStable, PartialEq)]
1586 pub enum FakeReadCause {
1587 /// Inject a fake read of the borrowed input at the end of each guards
1590 /// This should ensure that you cannot change the variant for an enum while
1591 /// you are in the midst of matching on it.
1594 /// `let x: !; match x {}` doesn't generate any read of x so we need to
1595 /// generate a read of x to check that it is initialized and safe.
1598 /// A fake read of the RefWithinGuard version of a bind-by-value variable
1599 /// in a match guard to ensure that it's value hasn't change by the time
1600 /// we create the OutsideGuard version.
1603 /// Officially, the semantics of
1605 /// `let pattern = <expr>;`
1607 /// is that `<expr>` is evaluated into a temporary and then this temporary is
1608 /// into the pattern.
1610 /// However, if we see the simple pattern `let var = <expr>`, we optimize this to
1611 /// evaluate `<expr>` directly into the variable `var`. This is mostly unobservable,
1612 /// but in some cases it can affect the borrow checker, as in #53695.
1613 /// Therefore, we insert a "fake read" here to ensure that we get
1614 /// appropriate errors.
1617 /// If we have an index expression like
1619 /// (*x)[1][{ x = y; 4}]
1621 /// then the first bounds check is invalidated when we evaluate the second
1622 /// index expression. Thus we create a fake borrow of `x` across the second
1623 /// indexer, which will cause a borrow check error.
1627 #[derive(Clone, Debug, PartialEq, TyEncodable, TyDecodable, Hash, HashStable, TypeFoldable)]
1628 pub struct LlvmInlineAsm<'tcx> {
1629 pub asm: hir::LlvmInlineAsmInner,
1630 pub outputs: Box<[Place<'tcx>]>,
1631 pub inputs: Box<[(Span, Operand<'tcx>)]>,
1634 impl Debug for Statement<'_> {
1635 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1636 use self::StatementKind::*;
1638 Assign(box (ref place, ref rv)) => write!(fmt, "{:?} = {:?}", place, rv),
1639 FakeRead(ref cause, ref place) => write!(fmt, "FakeRead({:?}, {:?})", cause, place),
1640 Retag(ref kind, ref place) => write!(
1644 RetagKind::FnEntry => "[fn entry] ",
1645 RetagKind::TwoPhase => "[2phase] ",
1646 RetagKind::Raw => "[raw] ",
1647 RetagKind::Default => "",
1651 StorageLive(ref place) => write!(fmt, "StorageLive({:?})", place),
1652 StorageDead(ref place) => write!(fmt, "StorageDead({:?})", place),
1653 SetDiscriminant { ref place, variant_index } => {
1654 write!(fmt, "discriminant({:?}) = {:?}", place, variant_index)
1656 LlvmInlineAsm(ref asm) => {
1657 write!(fmt, "llvm_asm!({:?} : {:?} : {:?})", asm.asm, asm.outputs, asm.inputs)
1659 AscribeUserType(box (ref place, ref c_ty), ref variance) => {
1660 write!(fmt, "AscribeUserType({:?}, {:?}, {:?})", place, variance, c_ty)
1662 Coverage(box ref coverage) => {
1663 if let Some(rgn) = &coverage.code_region {
1664 write!(fmt, "Coverage::{:?} for {:?}", coverage.kind, rgn)
1666 write!(fmt, "Coverage::{:?}", coverage.kind)
1669 CopyNonOverlapping(box crate::mir::CopyNonOverlapping {
1674 write!(fmt, "copy_nonoverlapping(src={:?}, dst={:?}, count={:?})", src, dst, count)
1676 Nop => write!(fmt, "nop"),
1681 #[derive(Clone, Debug, PartialEq, TyEncodable, TyDecodable, Hash, HashStable, TypeFoldable)]
1682 pub struct Coverage {
1683 pub kind: CoverageKind,
1684 pub code_region: Option<CodeRegion>,
1687 #[derive(Clone, Debug, PartialEq, TyEncodable, TyDecodable, Hash, HashStable, TypeFoldable)]
1688 pub struct CopyNonOverlapping<'tcx> {
1689 pub src: Operand<'tcx>,
1690 pub dst: Operand<'tcx>,
1691 /// Number of elements to copy from src to dest, not bytes.
1692 pub count: Operand<'tcx>,
1695 ///////////////////////////////////////////////////////////////////////////
1698 /// A path to a value; something that can be evaluated without
1699 /// changing or disturbing program state.
1700 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, HashStable)]
1701 pub struct Place<'tcx> {
1704 /// projection out of a place (access a field, deref a pointer, etc)
1705 pub projection: &'tcx List<PlaceElem<'tcx>>,
1708 #[cfg(target_arch = "x86_64")]
1709 static_assert_size!(Place<'_>, 16);
1711 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
1712 #[derive(TyEncodable, TyDecodable, HashStable)]
1713 pub enum ProjectionElem<V, T> {
1718 /// These indices are generated by slice patterns. Easiest to explain
1722 /// [X, _, .._, _, _] => { offset: 0, min_length: 4, from_end: false },
1723 /// [_, X, .._, _, _] => { offset: 1, min_length: 4, from_end: false },
1724 /// [_, _, .._, X, _] => { offset: 2, min_length: 4, from_end: true },
1725 /// [_, _, .._, _, X] => { offset: 1, min_length: 4, from_end: true },
1728 /// index or -index (in Python terms), depending on from_end
1730 /// The thing being indexed must be at least this long. For arrays this
1731 /// is always the exact length.
1733 /// Counting backwards from end? This is always false when indexing an
1738 /// These indices are generated by slice patterns.
1740 /// If `from_end` is true `slice[from..slice.len() - to]`.
1741 /// Otherwise `array[from..to]`.
1745 /// Whether `to` counts from the start or end of the array/slice.
1746 /// For `PlaceElem`s this is `true` if and only if the base is a slice.
1747 /// For `ProjectionKind`, this can also be `true` for arrays.
1751 /// "Downcast" to a variant of an ADT. Currently, we only introduce
1752 /// this for ADTs with more than one variant. It may be better to
1753 /// just introduce it always, or always for enums.
1755 /// The included Symbol is the name of the variant, used for printing MIR.
1756 Downcast(Option<Symbol>, VariantIdx),
1759 impl<V, T> ProjectionElem<V, T> {
1760 /// Returns `true` if the target of this projection may refer to a different region of memory
1762 fn is_indirect(&self) -> bool {
1764 Self::Deref => true,
1768 | Self::ConstantIndex { .. }
1769 | Self::Subslice { .. }
1770 | Self::Downcast(_, _) => false,
1775 /// Alias for projections as they appear in places, where the base is a place
1776 /// and the index is a local.
1777 pub type PlaceElem<'tcx> = ProjectionElem<Local, Ty<'tcx>>;
1779 // At least on 64 bit systems, `PlaceElem` should not be larger than two pointers.
1780 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
1781 static_assert_size!(PlaceElem<'_>, 24);
1783 /// Alias for projections as they appear in `UserTypeProjection`, where we
1784 /// need neither the `V` parameter for `Index` nor the `T` for `Field`.
1785 pub type ProjectionKind = ProjectionElem<(), ()>;
1787 rustc_index::newtype_index! {
1790 DEBUG_FORMAT = "field[{}]"
1794 #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
1795 pub struct PlaceRef<'tcx> {
1797 pub projection: &'tcx [PlaceElem<'tcx>],
1800 impl<'tcx> Place<'tcx> {
1801 // FIXME change this to a const fn by also making List::empty a const fn.
1802 pub fn return_place() -> Place<'tcx> {
1803 Place { local: RETURN_PLACE, projection: List::empty() }
1806 /// Returns `true` if this `Place` contains a `Deref` projection.
1808 /// If `Place::is_indirect` returns false, the caller knows that the `Place` refers to the
1809 /// same region of memory as its base.
1810 pub fn is_indirect(&self) -> bool {
1811 self.projection.iter().any(|elem| elem.is_indirect())
1814 /// Finds the innermost `Local` from this `Place`, *if* it is either a local itself or
1815 /// a single deref of a local.
1817 pub fn local_or_deref_local(&self) -> Option<Local> {
1818 self.as_ref().local_or_deref_local()
1821 /// If this place represents a local variable like `_X` with no
1822 /// projections, return `Some(_X)`.
1824 pub fn as_local(&self) -> Option<Local> {
1825 self.as_ref().as_local()
1829 pub fn as_ref(&self) -> PlaceRef<'tcx> {
1830 PlaceRef { local: self.local, projection: &self.projection }
1833 /// Iterate over the projections in evaluation order, i.e., the first element is the base with
1834 /// its projection and then subsequently more projections are added.
1835 /// As a concrete example, given the place a.b.c, this would yield:
1839 /// Given a place without projections, the iterator is empty.
1841 pub fn iter_projections(
1843 ) -> impl Iterator<Item = (PlaceRef<'tcx>, PlaceElem<'tcx>)> + DoubleEndedIterator {
1844 self.projection.iter().enumerate().map(move |(i, proj)| {
1845 let base = PlaceRef { local: self.local, projection: &self.projection[..i] };
1851 impl From<Local> for Place<'_> {
1852 fn from(local: Local) -> Self {
1853 Place { local, projection: List::empty() }
1857 impl<'tcx> PlaceRef<'tcx> {
1858 /// Finds the innermost `Local` from this `Place`, *if* it is either a local itself or
1859 /// a single deref of a local.
1860 pub fn local_or_deref_local(&self) -> Option<Local> {
1862 PlaceRef { local, projection: [] }
1863 | PlaceRef { local, projection: [ProjectionElem::Deref] } => Some(local),
1868 /// If this place represents a local variable like `_X` with no
1869 /// projections, return `Some(_X)`.
1870 pub fn as_local(&self) -> Option<Local> {
1872 PlaceRef { local, projection: [] } => Some(local),
1877 pub fn last_projection(&self) -> Option<(PlaceRef<'tcx>, PlaceElem<'tcx>)> {
1878 if let &[ref proj_base @ .., elem] = self.projection {
1879 Some((PlaceRef { local: self.local, projection: proj_base }, elem))
1886 impl Debug for Place<'_> {
1887 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1888 for elem in self.projection.iter().rev() {
1890 ProjectionElem::Downcast(_, _) | ProjectionElem::Field(_, _) => {
1891 write!(fmt, "(").unwrap();
1893 ProjectionElem::Deref => {
1894 write!(fmt, "(*").unwrap();
1896 ProjectionElem::Index(_)
1897 | ProjectionElem::ConstantIndex { .. }
1898 | ProjectionElem::Subslice { .. } => {}
1902 write!(fmt, "{:?}", self.local)?;
1904 for elem in self.projection.iter() {
1906 ProjectionElem::Downcast(Some(name), _index) => {
1907 write!(fmt, " as {})", name)?;
1909 ProjectionElem::Downcast(None, index) => {
1910 write!(fmt, " as variant#{:?})", index)?;
1912 ProjectionElem::Deref => {
1915 ProjectionElem::Field(field, ty) => {
1916 write!(fmt, ".{:?}: {:?})", field.index(), ty)?;
1918 ProjectionElem::Index(ref index) => {
1919 write!(fmt, "[{:?}]", index)?;
1921 ProjectionElem::ConstantIndex { offset, min_length, from_end: false } => {
1922 write!(fmt, "[{:?} of {:?}]", offset, min_length)?;
1924 ProjectionElem::ConstantIndex { offset, min_length, from_end: true } => {
1925 write!(fmt, "[-{:?} of {:?}]", offset, min_length)?;
1927 ProjectionElem::Subslice { from, to, from_end: true } if to == 0 => {
1928 write!(fmt, "[{:?}:]", from)?;
1930 ProjectionElem::Subslice { from, to, from_end: true } if from == 0 => {
1931 write!(fmt, "[:-{:?}]", to)?;
1933 ProjectionElem::Subslice { from, to, from_end: true } => {
1934 write!(fmt, "[{:?}:-{:?}]", from, to)?;
1936 ProjectionElem::Subslice { from, to, from_end: false } => {
1937 write!(fmt, "[{:?}..{:?}]", from, to)?;
1946 ///////////////////////////////////////////////////////////////////////////
1949 rustc_index::newtype_index! {
1950 pub struct SourceScope {
1952 DEBUG_FORMAT = "scope[{}]",
1953 const OUTERMOST_SOURCE_SCOPE = 0,
1957 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
1958 pub struct SourceScopeData<'tcx> {
1960 pub parent_scope: Option<SourceScope>,
1962 /// Whether this scope is the root of a scope tree of another body,
1963 /// inlined into this body by the MIR inliner.
1964 /// `ty::Instance` is the callee, and the `Span` is the call site.
1965 pub inlined: Option<(ty::Instance<'tcx>, Span)>,
1967 /// Nearest (transitive) parent scope (if any) which is inlined.
1968 /// This is an optimization over walking up `parent_scope`
1969 /// until a scope with `inlined: Some(...)` is found.
1970 pub inlined_parent_scope: Option<SourceScope>,
1972 /// Crate-local information for this source scope, that can't (and
1973 /// needn't) be tracked across crates.
1974 pub local_data: ClearCrossCrate<SourceScopeLocalData>,
1977 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable)]
1978 pub struct SourceScopeLocalData {
1979 /// An `HirId` with lint levels equivalent to this scope's lint levels.
1980 pub lint_root: hir::HirId,
1981 /// The unsafe block that contains this node.
1985 ///////////////////////////////////////////////////////////////////////////
1988 /// These are values that can appear inside an rvalue. They are intentionally
1989 /// limited to prevent rvalues from being nested in one another.
1990 #[derive(Clone, PartialEq, PartialOrd, TyEncodable, TyDecodable, Hash, HashStable)]
1991 pub enum Operand<'tcx> {
1992 /// Copy: The value must be available for use afterwards.
1994 /// This implies that the type of the place must be `Copy`; this is true
1995 /// by construction during build, but also checked by the MIR type checker.
1998 /// Move: The value (including old borrows of it) will not be used again.
2000 /// Safe for values of all types (modulo future developments towards `?Move`).
2001 /// Correct usage patterns are enforced by the borrow checker for safe code.
2002 /// `Copy` may be converted to `Move` to enable "last-use" optimizations.
2005 /// Synthesizes a constant value.
2006 Constant(Box<Constant<'tcx>>),
2009 #[cfg(target_arch = "x86_64")]
2010 static_assert_size!(Operand<'_>, 24);
2012 impl<'tcx> Debug for Operand<'tcx> {
2013 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2014 use self::Operand::*;
2016 Constant(ref a) => write!(fmt, "{:?}", a),
2017 Copy(ref place) => write!(fmt, "{:?}", place),
2018 Move(ref place) => write!(fmt, "move {:?}", place),
2023 impl<'tcx> Operand<'tcx> {
2024 /// Convenience helper to make a constant that refers to the fn
2025 /// with given `DefId` and substs. Since this is used to synthesize
2026 /// MIR, assumes `user_ty` is None.
2027 pub fn function_handle(
2030 substs: SubstsRef<'tcx>,
2033 let ty = tcx.type_of(def_id).subst(tcx, substs);
2034 Operand::Constant(box Constant {
2037 literal: ConstantKind::Ty(ty::Const::zero_sized(tcx, ty)),
2041 pub fn is_move(&self) -> bool {
2042 matches!(self, Operand::Move(..))
2045 /// Convenience helper to make a literal-like constant from a given scalar value.
2046 /// Since this is used to synthesize MIR, assumes `user_ty` is None.
2047 pub fn const_from_scalar(
2052 ) -> Operand<'tcx> {
2054 let param_env_and_ty = ty::ParamEnv::empty().and(ty);
2056 .layout_of(param_env_and_ty)
2057 .unwrap_or_else(|e| panic!("could not compute layout for {:?}: {:?}", ty, e))
2059 let scalar_size = match val {
2060 Scalar::Int(int) => int.size(),
2061 _ => panic!("Invalid scalar type {:?}", val),
2063 scalar_size == type_size
2065 Operand::Constant(box Constant {
2068 literal: ConstantKind::Val(val.into(), ty),
2072 pub fn to_copy(&self) -> Self {
2074 Operand::Copy(_) | Operand::Constant(_) => self.clone(),
2075 Operand::Move(place) => Operand::Copy(place),
2079 /// Returns the `Place` that is the target of this `Operand`, or `None` if this `Operand` is a
2081 pub fn place(&self) -> Option<Place<'tcx>> {
2083 Operand::Copy(place) | Operand::Move(place) => Some(*place),
2084 Operand::Constant(_) => None,
2088 /// Returns the `Constant` that is the target of this `Operand`, or `None` if this `Operand` is a
2090 pub fn constant(&self) -> Option<&Constant<'tcx>> {
2092 Operand::Constant(x) => Some(&**x),
2093 Operand::Copy(_) | Operand::Move(_) => None,
2098 ///////////////////////////////////////////////////////////////////////////
2101 #[derive(Clone, TyEncodable, TyDecodable, Hash, HashStable, PartialEq)]
2102 pub enum Rvalue<'tcx> {
2103 /// x (either a move or copy, depending on type of x)
2107 Repeat(Operand<'tcx>, &'tcx ty::Const<'tcx>),
2110 Ref(Region<'tcx>, BorrowKind, Place<'tcx>),
2112 /// Accessing a thread local static. This is inherently a runtime operation, even if llvm
2113 /// treats it as an access to a static. This `Rvalue` yields a reference to the thread local
2115 ThreadLocalRef(DefId),
2117 /// Create a raw pointer to the given place
2118 /// Can be generated by raw address of expressions (`&raw const x`),
2119 /// or when casting a reference to a raw pointer.
2120 AddressOf(Mutability, Place<'tcx>),
2122 /// length of a `[X]` or `[X;n]` value
2125 Cast(CastKind, Operand<'tcx>, Ty<'tcx>),
2127 BinaryOp(BinOp, Box<(Operand<'tcx>, Operand<'tcx>)>),
2128 CheckedBinaryOp(BinOp, Box<(Operand<'tcx>, Operand<'tcx>)>),
2130 NullaryOp(NullOp, Ty<'tcx>),
2131 UnaryOp(UnOp, Operand<'tcx>),
2133 /// Read the discriminant of an ADT.
2135 /// Undefined (i.e., no effort is made to make it defined, but there’s no reason why it cannot
2136 /// be defined to return, say, a 0) if ADT is not an enum.
2137 Discriminant(Place<'tcx>),
2139 /// Creates an aggregate value, like a tuple or struct. This is
2140 /// only needed because we want to distinguish `dest = Foo { x:
2141 /// ..., y: ... }` from `dest.x = ...; dest.y = ...;` in the case
2142 /// that `Foo` has a destructor. These rvalues can be optimized
2143 /// away after type-checking and before lowering.
2144 Aggregate(Box<AggregateKind<'tcx>>, Vec<Operand<'tcx>>),
2147 #[cfg(target_arch = "x86_64")]
2148 static_assert_size!(Rvalue<'_>, 40);
2150 #[derive(Clone, Copy, Debug, PartialEq, Eq, TyEncodable, TyDecodable, Hash, HashStable)]
2153 Pointer(PointerCast),
2156 #[derive(Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, Hash, HashStable)]
2157 pub enum AggregateKind<'tcx> {
2158 /// The type is of the element
2162 /// The second field is the variant index. It's equal to 0 for struct
2163 /// and union expressions. The fourth field is
2164 /// active field number and is present only for union expressions
2165 /// -- e.g., for a union expression `SomeUnion { c: .. }`, the
2166 /// active field index would identity the field `c`
2167 Adt(&'tcx AdtDef, VariantIdx, SubstsRef<'tcx>, Option<UserTypeAnnotationIndex>, Option<usize>),
2169 Closure(DefId, SubstsRef<'tcx>),
2170 Generator(DefId, SubstsRef<'tcx>, hir::Movability),
2173 #[cfg(target_arch = "x86_64")]
2174 static_assert_size!(AggregateKind<'_>, 48);
2176 #[derive(Copy, Clone, Debug, PartialEq, PartialOrd, Eq, TyEncodable, TyDecodable, Hash, HashStable)]
2178 /// The `+` operator (addition)
2180 /// The `-` operator (subtraction)
2182 /// The `*` operator (multiplication)
2184 /// The `/` operator (division)
2186 /// The `%` operator (modulus)
2188 /// The `^` operator (bitwise xor)
2190 /// The `&` operator (bitwise and)
2192 /// The `|` operator (bitwise or)
2194 /// The `<<` operator (shift left)
2196 /// The `>>` operator (shift right)
2198 /// The `==` operator (equality)
2200 /// The `<` operator (less than)
2202 /// The `<=` operator (less than or equal to)
2204 /// The `!=` operator (not equal to)
2206 /// The `>=` operator (greater than or equal to)
2208 /// The `>` operator (greater than)
2210 /// The `ptr.offset` operator
2215 pub fn is_checkable(self) -> bool {
2217 matches!(self, Add | Sub | Mul | Shl | Shr)
2221 #[derive(Copy, Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, Hash, HashStable)]
2223 /// Returns the size of a value of that type
2225 /// Creates a new uninitialized box for a value of that type
2229 #[derive(Copy, Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, Hash, HashStable)]
2231 /// The `!` operator for logical inversion
2233 /// The `-` operator for negation
2237 impl<'tcx> Debug for Rvalue<'tcx> {
2238 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2239 use self::Rvalue::*;
2242 Use(ref place) => write!(fmt, "{:?}", place),
2243 Repeat(ref a, ref b) => {
2244 write!(fmt, "[{:?}; ", a)?;
2245 pretty_print_const(b, fmt, false)?;
2248 Len(ref a) => write!(fmt, "Len({:?})", a),
2249 Cast(ref kind, ref place, ref ty) => {
2250 write!(fmt, "{:?} as {:?} ({:?})", place, ty, kind)
2252 BinaryOp(ref op, box (ref a, ref b)) => write!(fmt, "{:?}({:?}, {:?})", op, a, b),
2253 CheckedBinaryOp(ref op, box (ref a, ref b)) => {
2254 write!(fmt, "Checked{:?}({:?}, {:?})", op, a, b)
2256 UnaryOp(ref op, ref a) => write!(fmt, "{:?}({:?})", op, a),
2257 Discriminant(ref place) => write!(fmt, "discriminant({:?})", place),
2258 NullaryOp(ref op, ref t) => write!(fmt, "{:?}({:?})", op, t),
2259 ThreadLocalRef(did) => ty::tls::with(|tcx| {
2260 let muta = tcx.static_mutability(did).unwrap().prefix_str();
2261 write!(fmt, "&/*tls*/ {}{}", muta, tcx.def_path_str(did))
2263 Ref(region, borrow_kind, ref place) => {
2264 let kind_str = match borrow_kind {
2265 BorrowKind::Shared => "",
2266 BorrowKind::Shallow => "shallow ",
2267 BorrowKind::Mut { .. } | BorrowKind::Unique => "mut ",
2270 // When printing regions, add trailing space if necessary.
2271 let print_region = ty::tls::with(|tcx| {
2272 tcx.sess.verbose() || tcx.sess.opts.debugging_opts.identify_regions
2274 let region = if print_region {
2275 let mut region = region.to_string();
2276 if !region.is_empty() {
2281 // Do not even print 'static
2284 write!(fmt, "&{}{}{:?}", region, kind_str, place)
2287 AddressOf(mutability, ref place) => {
2288 let kind_str = match mutability {
2289 Mutability::Mut => "mut",
2290 Mutability::Not => "const",
2293 write!(fmt, "&raw {} {:?}", kind_str, place)
2296 Aggregate(ref kind, ref places) => {
2297 let fmt_tuple = |fmt: &mut Formatter<'_>, name: &str| {
2298 let mut tuple_fmt = fmt.debug_tuple(name);
2299 for place in places {
2300 tuple_fmt.field(place);
2306 AggregateKind::Array(_) => write!(fmt, "{:?}", places),
2308 AggregateKind::Tuple => {
2309 if places.is_empty() {
2316 AggregateKind::Adt(adt_def, variant, substs, _user_ty, _) => {
2317 let variant_def = &adt_def.variants[variant];
2319 let name = ty::tls::with(|tcx| {
2320 let mut name = String::new();
2321 let substs = tcx.lift(substs).expect("could not lift for printing");
2322 FmtPrinter::new(tcx, &mut name, Namespace::ValueNS)
2323 .print_def_path(variant_def.def_id, substs)?;
2327 match variant_def.ctor_kind {
2328 CtorKind::Const => fmt.write_str(&name),
2329 CtorKind::Fn => fmt_tuple(fmt, &name),
2330 CtorKind::Fictive => {
2331 let mut struct_fmt = fmt.debug_struct(&name);
2332 for (field, place) in variant_def.fields.iter().zip(places) {
2333 struct_fmt.field(&field.ident.as_str(), place);
2340 AggregateKind::Closure(def_id, substs) => ty::tls::with(|tcx| {
2341 if let Some(def_id) = def_id.as_local() {
2342 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
2343 let name = if tcx.sess.opts.debugging_opts.span_free_formats {
2344 let substs = tcx.lift(substs).unwrap();
2347 tcx.def_path_str_with_substs(def_id.to_def_id(), substs),
2350 let span = tcx.hir().span(hir_id);
2351 format!("[closure@{}]", tcx.sess.source_map().span_to_string(span))
2353 let mut struct_fmt = fmt.debug_struct(&name);
2355 if let Some(upvars) = tcx.upvars_mentioned(def_id) {
2356 for (&var_id, place) in upvars.keys().zip(places) {
2357 let var_name = tcx.hir().name(var_id);
2358 struct_fmt.field(&var_name.as_str(), place);
2364 write!(fmt, "[closure]")
2368 AggregateKind::Generator(def_id, _, _) => ty::tls::with(|tcx| {
2369 if let Some(def_id) = def_id.as_local() {
2370 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
2371 let name = format!("[generator@{:?}]", tcx.hir().span(hir_id));
2372 let mut struct_fmt = fmt.debug_struct(&name);
2374 if let Some(upvars) = tcx.upvars_mentioned(def_id) {
2375 for (&var_id, place) in upvars.keys().zip(places) {
2376 let var_name = tcx.hir().name(var_id);
2377 struct_fmt.field(&var_name.as_str(), place);
2383 write!(fmt, "[generator]")
2392 ///////////////////////////////////////////////////////////////////////////
2395 /// Two constants are equal if they are the same constant. Note that
2396 /// this does not necessarily mean that they are `==` in Rust. In
2397 /// particular, one must be wary of `NaN`!
2399 #[derive(Clone, Copy, PartialEq, PartialOrd, TyEncodable, TyDecodable, Hash, HashStable)]
2400 pub struct Constant<'tcx> {
2403 /// Optional user-given type: for something like
2404 /// `collect::<Vec<_>>`, this would be present and would
2405 /// indicate that `Vec<_>` was explicitly specified.
2407 /// Needed for NLL to impose user-given type constraints.
2408 pub user_ty: Option<UserTypeAnnotationIndex>,
2410 pub literal: ConstantKind<'tcx>,
2413 #[derive(Clone, Copy, PartialEq, PartialOrd, TyEncodable, TyDecodable, Hash, HashStable, Debug)]
2414 pub enum ConstantKind<'tcx> {
2415 /// This constant came from the type system
2416 Ty(&'tcx ty::Const<'tcx>),
2417 /// This constant cannot go back into the type system, as it represents
2418 /// something the type system cannot handle (e.g. pointers).
2419 Val(interpret::ConstValue<'tcx>, Ty<'tcx>),
2422 impl Constant<'tcx> {
2423 pub fn check_static_ptr(&self, tcx: TyCtxt<'_>) -> Option<DefId> {
2424 match self.literal.const_for_ty()?.val.try_to_scalar() {
2425 Some(Scalar::Ptr(ptr)) => match tcx.global_alloc(ptr.alloc_id) {
2426 GlobalAlloc::Static(def_id) => {
2427 assert!(!tcx.is_thread_local_static(def_id));
2435 pub fn ty(&self) -> Ty<'tcx> {
2440 impl From<&'tcx ty::Const<'tcx>> for ConstantKind<'tcx> {
2441 fn from(ct: &'tcx ty::Const<'tcx>) -> Self {
2446 impl ConstantKind<'tcx> {
2447 /// Returns `None` if the constant is not trivially safe for use in the type system.
2448 pub fn const_for_ty(&self) -> Option<&'tcx ty::Const<'tcx>> {
2450 ConstantKind::Ty(c) => Some(c),
2451 ConstantKind::Val(..) => None,
2455 pub fn ty(&self) -> Ty<'tcx> {
2457 ConstantKind::Ty(c) => c.ty,
2458 ConstantKind::Val(_, ty) => ty,
2463 pub fn try_to_value(self) -> Option<interpret::ConstValue<'tcx>> {
2465 ConstantKind::Ty(c) => c.val.try_to_value(),
2466 ConstantKind::Val(val, _) => Some(val),
2471 pub fn try_to_scalar(self) -> Option<Scalar> {
2472 self.try_to_value()?.try_to_scalar()
2476 pub fn try_to_scalar_int(self) -> Option<ScalarInt> {
2477 Some(self.try_to_value()?.try_to_scalar()?.assert_int())
2481 pub fn try_to_bits(self, size: Size) -> Option<u128> {
2482 self.try_to_scalar_int()?.to_bits(size).ok()
2486 pub fn try_to_bool(self) -> Option<bool> {
2487 self.try_to_scalar_int()?.try_into().ok()
2491 pub fn try_eval_bits(
2494 param_env: ty::ParamEnv<'tcx>,
2498 Self::Ty(ct) => ct.try_eval_bits(tcx, param_env, ty),
2499 Self::Val(val, t) => {
2502 tcx.layout_of(param_env.with_reveal_all_normalized(tcx).and(ty)).ok()?.size;
2503 val.try_to_bits(size)
2509 pub fn try_eval_bool(&self, tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>) -> Option<bool> {
2511 Self::Ty(ct) => ct.try_eval_bool(tcx, param_env),
2512 Self::Val(val, _) => val.try_to_bool(),
2517 pub fn try_eval_usize(&self, tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>) -> Option<u64> {
2519 Self::Ty(ct) => ct.try_eval_usize(tcx, param_env),
2520 Self::Val(val, _) => val.try_to_machine_usize(tcx),
2525 /// A collection of projections into user types.
2527 /// They are projections because a binding can occur a part of a
2528 /// parent pattern that has been ascribed a type.
2530 /// Its a collection because there can be multiple type ascriptions on
2531 /// the path from the root of the pattern down to the binding itself.
2536 /// struct S<'a>((i32, &'a str), String);
2537 /// let S((_, w): (i32, &'static str), _): S = ...;
2538 /// // ------ ^^^^^^^^^^^^^^^^^^^ (1)
2539 /// // --------------------------------- ^ (2)
2542 /// The highlights labelled `(1)` show the subpattern `(_, w)` being
2543 /// ascribed the type `(i32, &'static str)`.
2545 /// The highlights labelled `(2)` show the whole pattern being
2546 /// ascribed the type `S`.
2548 /// In this example, when we descend to `w`, we will have built up the
2549 /// following two projected types:
2551 /// * base: `S`, projection: `(base.0).1`
2552 /// * base: `(i32, &'static str)`, projection: `base.1`
2554 /// The first will lead to the constraint `w: &'1 str` (for some
2555 /// inferred region `'1`). The second will lead to the constraint `w:
2557 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
2558 pub struct UserTypeProjections {
2559 pub contents: Vec<(UserTypeProjection, Span)>,
2562 impl<'tcx> UserTypeProjections {
2563 pub fn none() -> Self {
2564 UserTypeProjections { contents: vec![] }
2567 pub fn is_empty(&self) -> bool {
2568 self.contents.is_empty()
2571 pub fn projections_and_spans(
2573 ) -> impl Iterator<Item = &(UserTypeProjection, Span)> + ExactSizeIterator {
2574 self.contents.iter()
2577 pub fn projections(&self) -> impl Iterator<Item = &UserTypeProjection> + ExactSizeIterator {
2578 self.contents.iter().map(|&(ref user_type, _span)| user_type)
2581 pub fn push_projection(mut self, user_ty: &UserTypeProjection, span: Span) -> Self {
2582 self.contents.push((user_ty.clone(), span));
2588 mut f: impl FnMut(UserTypeProjection) -> UserTypeProjection,
2590 self.contents = self.contents.drain(..).map(|(proj, span)| (f(proj), span)).collect();
2594 pub fn index(self) -> Self {
2595 self.map_projections(|pat_ty_proj| pat_ty_proj.index())
2598 pub fn subslice(self, from: u64, to: u64) -> Self {
2599 self.map_projections(|pat_ty_proj| pat_ty_proj.subslice(from, to))
2602 pub fn deref(self) -> Self {
2603 self.map_projections(|pat_ty_proj| pat_ty_proj.deref())
2606 pub fn leaf(self, field: Field) -> Self {
2607 self.map_projections(|pat_ty_proj| pat_ty_proj.leaf(field))
2610 pub fn variant(self, adt_def: &'tcx AdtDef, variant_index: VariantIdx, field: Field) -> Self {
2611 self.map_projections(|pat_ty_proj| pat_ty_proj.variant(adt_def, variant_index, field))
2615 /// Encodes the effect of a user-supplied type annotation on the
2616 /// subcomponents of a pattern. The effect is determined by applying the
2617 /// given list of proejctions to some underlying base type. Often,
2618 /// the projection element list `projs` is empty, in which case this
2619 /// directly encodes a type in `base`. But in the case of complex patterns with
2620 /// subpatterns and bindings, we want to apply only a *part* of the type to a variable,
2621 /// in which case the `projs` vector is used.
2625 /// * `let x: T = ...` -- here, the `projs` vector is empty.
2627 /// * `let (x, _): T = ...` -- here, the `projs` vector would contain
2628 /// `field[0]` (aka `.0`), indicating that the type of `s` is
2629 /// determined by finding the type of the `.0` field from `T`.
2630 #[derive(Clone, Debug, TyEncodable, TyDecodable, Hash, HashStable, PartialEq)]
2631 pub struct UserTypeProjection {
2632 pub base: UserTypeAnnotationIndex,
2633 pub projs: Vec<ProjectionKind>,
2636 impl Copy for ProjectionKind {}
2638 impl UserTypeProjection {
2639 pub(crate) fn index(mut self) -> Self {
2640 self.projs.push(ProjectionElem::Index(()));
2644 pub(crate) fn subslice(mut self, from: u64, to: u64) -> Self {
2645 self.projs.push(ProjectionElem::Subslice { from, to, from_end: true });
2649 pub(crate) fn deref(mut self) -> Self {
2650 self.projs.push(ProjectionElem::Deref);
2654 pub(crate) fn leaf(mut self, field: Field) -> Self {
2655 self.projs.push(ProjectionElem::Field(field, ()));
2659 pub(crate) fn variant(
2662 variant_index: VariantIdx,
2665 self.projs.push(ProjectionElem::Downcast(
2666 Some(adt_def.variants[variant_index].ident.name),
2669 self.projs.push(ProjectionElem::Field(field, ()));
2674 TrivialTypeFoldableAndLiftImpls! { ProjectionKind, }
2676 impl<'tcx> TypeFoldable<'tcx> for UserTypeProjection {
2677 fn super_fold_with<F: TypeFolder<'tcx>>(self, folder: &mut F) -> Self {
2678 UserTypeProjection {
2679 base: self.base.fold_with(folder),
2680 projs: self.projs.fold_with(folder),
2684 fn super_visit_with<Vs: TypeVisitor<'tcx>>(
2687 ) -> ControlFlow<Vs::BreakTy> {
2688 self.base.visit_with(visitor)
2689 // Note: there's nothing in `self.proj` to visit.
2693 rustc_index::newtype_index! {
2694 pub struct Promoted {
2696 DEBUG_FORMAT = "promoted[{}]"
2700 impl<'tcx> Debug for Constant<'tcx> {
2701 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2702 write!(fmt, "{}", self)
2706 impl<'tcx> Display for Constant<'tcx> {
2707 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2708 match self.ty().kind() {
2710 _ => write!(fmt, "const ")?,
2712 match self.literal {
2713 ConstantKind::Ty(c) => pretty_print_const(c, fmt, true),
2714 ConstantKind::Val(val, ty) => pretty_print_const_value(val, ty, fmt, true),
2719 fn pretty_print_const(
2720 c: &ty::Const<'tcx>,
2721 fmt: &mut Formatter<'_>,
2724 use crate::ty::print::PrettyPrinter;
2725 ty::tls::with(|tcx| {
2726 let literal = tcx.lift(c).unwrap();
2727 let mut cx = FmtPrinter::new(tcx, fmt, Namespace::ValueNS);
2728 cx.print_alloc_ids = true;
2729 cx.pretty_print_const(literal, print_types)?;
2734 fn pretty_print_const_value(
2735 val: interpret::ConstValue<'tcx>,
2737 fmt: &mut Formatter<'_>,
2740 use crate::ty::print::PrettyPrinter;
2741 ty::tls::with(|tcx| {
2742 let val = tcx.lift(val).unwrap();
2743 let ty = tcx.lift(ty).unwrap();
2744 let mut cx = FmtPrinter::new(tcx, fmt, Namespace::ValueNS);
2745 cx.print_alloc_ids = true;
2746 cx.pretty_print_const_value(val, ty, print_types)?;
2751 impl<'tcx> graph::DirectedGraph for Body<'tcx> {
2752 type Node = BasicBlock;
2755 impl<'tcx> graph::WithNumNodes for Body<'tcx> {
2757 fn num_nodes(&self) -> usize {
2758 self.basic_blocks.len()
2762 impl<'tcx> graph::WithStartNode for Body<'tcx> {
2764 fn start_node(&self) -> Self::Node {
2769 impl<'tcx> graph::WithSuccessors for Body<'tcx> {
2771 fn successors(&self, node: Self::Node) -> <Self as GraphSuccessors<'_>>::Iter {
2772 self.basic_blocks[node].terminator().successors().cloned()
2776 impl<'a, 'b> graph::GraphSuccessors<'b> for Body<'a> {
2777 type Item = BasicBlock;
2778 type Iter = iter::Cloned<Successors<'b>>;
2781 impl graph::GraphPredecessors<'graph> for Body<'tcx> {
2782 type Item = BasicBlock;
2783 type Iter = smallvec::IntoIter<[BasicBlock; 4]>;
2786 impl graph::WithPredecessors for Body<'tcx> {
2788 fn predecessors(&self, node: Self::Node) -> <Self as graph::GraphPredecessors<'_>>::Iter {
2789 self.predecessors()[node].clone().into_iter()
2793 /// `Location` represents the position of the start of the statement; or, if
2794 /// `statement_index` equals the number of statements, then the start of the
2796 #[derive(Copy, Clone, PartialEq, Eq, Hash, Ord, PartialOrd, HashStable)]
2797 pub struct Location {
2798 /// The block that the location is within.
2799 pub block: BasicBlock,
2801 pub statement_index: usize,
2804 impl fmt::Debug for Location {
2805 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2806 write!(fmt, "{:?}[{}]", self.block, self.statement_index)
2811 pub const START: Location = Location { block: START_BLOCK, statement_index: 0 };
2813 /// Returns the location immediately after this one within the enclosing block.
2815 /// Note that if this location represents a terminator, then the
2816 /// resulting location would be out of bounds and invalid.
2817 pub fn successor_within_block(&self) -> Location {
2818 Location { block: self.block, statement_index: self.statement_index + 1 }
2821 /// Returns `true` if `other` is earlier in the control flow graph than `self`.
2822 pub fn is_predecessor_of<'tcx>(&self, other: Location, body: &Body<'tcx>) -> bool {
2823 // If we are in the same block as the other location and are an earlier statement
2824 // then we are a predecessor of `other`.
2825 if self.block == other.block && self.statement_index < other.statement_index {
2829 let predecessors = body.predecessors();
2831 // If we're in another block, then we want to check that block is a predecessor of `other`.
2832 let mut queue: Vec<BasicBlock> = predecessors[other.block].to_vec();
2833 let mut visited = FxHashSet::default();
2835 while let Some(block) = queue.pop() {
2836 // If we haven't visited this block before, then make sure we visit it's predecessors.
2837 if visited.insert(block) {
2838 queue.extend(predecessors[block].iter().cloned());
2843 // If we found the block that `self` is in, then we are a predecessor of `other` (since
2844 // we found that block by looking at the predecessors of `other`).
2845 if self.block == block {
2853 pub fn dominates(&self, other: Location, dominators: &Dominators<BasicBlock>) -> bool {
2854 if self.block == other.block {
2855 self.statement_index <= other.statement_index
2857 dominators.is_dominated_by(other.block, self.block)