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, ConstValue, 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::{FallibleTypeFolder, TypeFoldable, 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_hir::{self as hir, HirId};
20 use rustc_session::Session;
21 use rustc_target::abi::{Size, VariantIdx};
23 use polonius_engine::Atom;
24 pub use rustc_ast::Mutability;
25 use rustc_data_structures::fx::FxHashSet;
26 use rustc_data_structures::graph::dominators::{dominators, Dominators};
27 use rustc_data_structures::graph::{self, GraphSuccessors};
28 use rustc_index::bit_set::BitMatrix;
29 use rustc_index::vec::{Idx, IndexVec};
30 use rustc_serialize::{Decodable, Encodable};
31 use rustc_span::symbol::Symbol;
32 use rustc_span::{Span, DUMMY_SP};
33 use rustc_target::asm::InlineAsmRegOrRegClass;
38 use std::convert::TryInto;
39 use std::fmt::{self, Debug, Display, Formatter, Write};
40 use std::ops::{ControlFlow, Index, IndexMut};
42 use std::{iter, mem, option};
44 use self::graph_cyclic_cache::GraphIsCyclicCache;
45 use self::predecessors::{PredecessorCache, Predecessors};
46 pub use self::query::*;
50 pub mod generic_graphviz;
51 mod graph_cyclic_cache;
62 pub use terminator::*;
67 pub use self::generic_graph::graphviz_safe_def_name;
68 pub use self::graphviz::write_mir_graphviz;
69 pub use self::pretty::{
70 create_dump_file, display_allocation, dump_enabled, dump_mir, write_mir_pretty, PassWhere,
74 pub type LocalDecls<'tcx> = IndexVec<Local, LocalDecl<'tcx>>;
76 pub trait HasLocalDecls<'tcx> {
77 fn local_decls(&self) -> &LocalDecls<'tcx>;
80 impl<'tcx> HasLocalDecls<'tcx> for LocalDecls<'tcx> {
82 fn local_decls(&self) -> &LocalDecls<'tcx> {
87 impl<'tcx> HasLocalDecls<'tcx> for Body<'tcx> {
89 fn local_decls(&self) -> &LocalDecls<'tcx> {
94 /// A streamlined trait that you can implement to create a pass; the
95 /// pass will be named after the type, and it will consist of a main
96 /// loop that goes over each available MIR and applies `run_pass`.
97 pub trait MirPass<'tcx> {
98 fn name(&self) -> Cow<'_, str> {
99 let name = std::any::type_name::<Self>();
100 if let Some(tail) = name.rfind(':') {
101 Cow::from(&name[tail + 1..])
107 /// Returns `true` if this pass is enabled with the current combination of compiler flags.
108 fn is_enabled(&self, _sess: &Session) -> bool {
112 fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>);
114 /// If this pass causes the MIR to enter a new phase, return that phase.
115 fn phase_change(&self) -> Option<MirPhase> {
119 fn is_mir_dump_enabled(&self) -> bool {
124 /// The various "big phases" that MIR goes through.
126 /// These phases all describe dialects of MIR. Since all MIR uses the same datastructures, the
127 /// dialects forbid certain variants or values in certain phases.
129 /// Note: Each phase's validation checks all invariants of the *previous* phases' dialects. A phase
130 /// that changes the dialect documents what invariants must be upheld *after* that phase finishes.
132 /// Warning: ordering of variants is significant.
133 #[derive(Copy, Clone, TyEncodable, TyDecodable, Debug, PartialEq, Eq, PartialOrd, Ord)]
134 #[derive(HashStable)]
137 // FIXME(oli-obk): it's unclear whether we still need this phase (and its corresponding query).
138 // We used to have this for pre-miri MIR based const eval.
140 /// This phase checks the MIR for promotable elements and takes them out of the main MIR body
141 /// by creating a new MIR body per promoted element. After this phase (and thus the termination
142 /// of the `mir_promoted` query), these promoted elements are available in the `promoted_mir`
146 /// * the only `AggregateKind`s allowed are `Array` and `Generator`,
147 /// * `DropAndReplace` is gone for good
148 /// * `Drop` now uses explicit drop flags visible in the MIR and reaching a `Drop` terminator
149 /// means that the auto-generated drop glue will be invoked.
151 /// After this phase, generators are explicit state machines (no more `Yield`).
152 /// `AggregateKind::Generator` is gone for good.
153 GeneratorLowering = 4,
158 /// Gets the index of the current MirPhase within the set of all `MirPhase`s.
159 pub fn phase_index(&self) -> usize {
164 /// Where a specific `mir::Body` comes from.
165 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
166 #[derive(HashStable, TyEncodable, TyDecodable, TypeFoldable)]
167 pub struct MirSource<'tcx> {
168 pub instance: InstanceDef<'tcx>,
170 /// If `Some`, this is a promoted rvalue within the parent function.
171 pub promoted: Option<Promoted>,
174 impl<'tcx> MirSource<'tcx> {
175 pub fn item(def_id: DefId) -> Self {
177 instance: InstanceDef::Item(ty::WithOptConstParam::unknown(def_id)),
182 pub fn from_instance(instance: InstanceDef<'tcx>) -> Self {
183 MirSource { instance, promoted: None }
186 pub fn with_opt_param(self) -> ty::WithOptConstParam<DefId> {
187 self.instance.with_opt_param()
191 pub fn def_id(&self) -> DefId {
192 self.instance.def_id()
196 #[derive(Clone, TyEncodable, TyDecodable, Debug, HashStable, TypeFoldable)]
197 pub struct GeneratorInfo<'tcx> {
198 /// The yield type of the function, if it is a generator.
199 pub yield_ty: Option<Ty<'tcx>>,
201 /// Generator drop glue.
202 pub generator_drop: Option<Body<'tcx>>,
204 /// The layout of a generator. Produced by the state transformation.
205 pub generator_layout: Option<GeneratorLayout<'tcx>>,
207 /// If this is a generator then record the type of source expression that caused this generator
209 pub generator_kind: GeneratorKind,
212 /// The lowered representation of a single function.
213 #[derive(Clone, TyEncodable, TyDecodable, Debug, HashStable, TypeFoldable)]
214 pub struct Body<'tcx> {
215 /// A list of basic blocks. References to basic block use a newtyped index type [`BasicBlock`]
216 /// that indexes into this vector.
217 basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
219 /// Records how far through the "desugaring and optimization" process this particular
220 /// MIR has traversed. This is particularly useful when inlining, since in that context
221 /// we instantiate the promoted constants and add them to our promoted vector -- but those
222 /// promoted items have already been optimized, whereas ours have not. This field allows
223 /// us to see the difference and forego optimization on the inlined promoted items.
226 pub source: MirSource<'tcx>,
228 /// A list of source scopes; these are referenced by statements
229 /// and used for debuginfo. Indexed by a `SourceScope`.
230 pub source_scopes: IndexVec<SourceScope, SourceScopeData<'tcx>>,
232 pub generator: Option<Box<GeneratorInfo<'tcx>>>,
234 /// Declarations of locals.
236 /// The first local is the return value pointer, followed by `arg_count`
237 /// locals for the function arguments, followed by any user-declared
238 /// variables and temporaries.
239 pub local_decls: LocalDecls<'tcx>,
241 /// User type annotations.
242 pub user_type_annotations: ty::CanonicalUserTypeAnnotations<'tcx>,
244 /// The number of arguments this function takes.
246 /// Starting at local 1, `arg_count` locals will be provided by the caller
247 /// and can be assumed to be initialized.
249 /// If this MIR was built for a constant, this will be 0.
250 pub arg_count: usize,
252 /// Mark an argument local (which must be a tuple) as getting passed as
253 /// its individual components at the LLVM level.
255 /// This is used for the "rust-call" ABI.
256 pub spread_arg: Option<Local>,
258 /// Debug information pertaining to user variables, including captures.
259 pub var_debug_info: Vec<VarDebugInfo<'tcx>>,
261 /// A span representing this MIR, for error reporting.
264 /// Constants that are required to evaluate successfully for this MIR to be well-formed.
265 /// We hold in this field all the constants we are not able to evaluate yet.
266 pub required_consts: Vec<Constant<'tcx>>,
268 /// Does this body use generic parameters. This is used for the `ConstEvaluatable` check.
270 /// Note that this does not actually mean that this body is not computable right now.
271 /// The repeat count in the following example is polymorphic, but can still be evaluated
272 /// without knowing anything about the type parameter `T`.
276 /// let _ = [0; std::mem::size_of::<*mut T>()];
280 /// **WARNING**: Do not change this flags after the MIR was originally created, even if an optimization
281 /// removed the last mention of all generic params. We do not want to rely on optimizations and
282 /// potentially allow things like `[u8; std::mem::size_of::<T>() * 0]` due to this.
283 pub is_polymorphic: bool,
285 predecessor_cache: PredecessorCache,
286 is_cyclic: GraphIsCyclicCache,
289 impl<'tcx> Body<'tcx> {
291 source: MirSource<'tcx>,
292 basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
293 source_scopes: IndexVec<SourceScope, SourceScopeData<'tcx>>,
294 local_decls: LocalDecls<'tcx>,
295 user_type_annotations: ty::CanonicalUserTypeAnnotations<'tcx>,
297 var_debug_info: Vec<VarDebugInfo<'tcx>>,
299 generator_kind: Option<GeneratorKind>,
301 // We need `arg_count` locals, and one for the return place.
303 local_decls.len() > arg_count,
304 "expected at least {} locals, got {}",
309 let mut body = Body {
310 phase: MirPhase::Build,
314 generator: generator_kind.map(|generator_kind| {
315 Box::new(GeneratorInfo {
317 generator_drop: None,
318 generator_layout: None,
323 user_type_annotations,
328 required_consts: Vec::new(),
329 is_polymorphic: false,
330 predecessor_cache: PredecessorCache::new(),
331 is_cyclic: GraphIsCyclicCache::new(),
333 body.is_polymorphic = body.has_param_types_or_consts();
337 /// Returns a partially initialized MIR body containing only a list of basic blocks.
339 /// The returned MIR contains no `LocalDecl`s (even for the return place) or source scopes. It
340 /// is only useful for testing but cannot be `#[cfg(test)]` because it is used in a different
342 pub fn new_cfg_only(basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>) -> Self {
343 let mut body = Body {
344 phase: MirPhase::Build,
345 source: MirSource::item(DefId::local(CRATE_DEF_INDEX)),
347 source_scopes: IndexVec::new(),
349 local_decls: IndexVec::new(),
350 user_type_annotations: IndexVec::new(),
354 required_consts: Vec::new(),
355 var_debug_info: Vec::new(),
356 is_polymorphic: false,
357 predecessor_cache: PredecessorCache::new(),
358 is_cyclic: GraphIsCyclicCache::new(),
360 body.is_polymorphic = body.has_param_types_or_consts();
365 pub fn basic_blocks(&self) -> &IndexVec<BasicBlock, BasicBlockData<'tcx>> {
370 pub fn basic_blocks_mut(&mut self) -> &mut IndexVec<BasicBlock, BasicBlockData<'tcx>> {
371 // Because the user could mutate basic block terminators via this reference, we need to
372 // invalidate the caches.
374 // FIXME: Use a finer-grained API for this, so only transformations that alter terminators
375 // invalidate the caches.
376 self.predecessor_cache.invalidate();
377 self.is_cyclic.invalidate();
378 &mut self.basic_blocks
382 pub fn basic_blocks_and_local_decls_mut(
384 ) -> (&mut IndexVec<BasicBlock, BasicBlockData<'tcx>>, &mut LocalDecls<'tcx>) {
385 self.predecessor_cache.invalidate();
386 self.is_cyclic.invalidate();
387 (&mut self.basic_blocks, &mut self.local_decls)
391 pub fn basic_blocks_local_decls_mut_and_var_debug_info(
394 &mut IndexVec<BasicBlock, BasicBlockData<'tcx>>,
395 &mut LocalDecls<'tcx>,
396 &mut Vec<VarDebugInfo<'tcx>>,
398 self.predecessor_cache.invalidate();
399 self.is_cyclic.invalidate();
400 (&mut self.basic_blocks, &mut self.local_decls, &mut self.var_debug_info)
403 /// Returns `true` if a cycle exists in the control-flow graph that is reachable from the
405 pub fn is_cfg_cyclic(&self) -> bool {
406 self.is_cyclic.is_cyclic(self)
410 pub fn local_kind(&self, local: Local) -> LocalKind {
411 let index = local.as_usize();
414 self.local_decls[local].mutability == Mutability::Mut,
415 "return place should be mutable"
418 LocalKind::ReturnPointer
419 } else if index < self.arg_count + 1 {
421 } else if self.local_decls[local].is_user_variable() {
428 /// Returns an iterator over all user-declared mutable locals.
430 pub fn mut_vars_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
431 (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
432 let local = Local::new(index);
433 let decl = &self.local_decls[local];
434 if decl.is_user_variable() && decl.mutability == Mutability::Mut {
442 /// Returns an iterator over all user-declared mutable arguments and locals.
444 pub fn mut_vars_and_args_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
445 (1..self.local_decls.len()).filter_map(move |index| {
446 let local = Local::new(index);
447 let decl = &self.local_decls[local];
448 if (decl.is_user_variable() || index < self.arg_count + 1)
449 && decl.mutability == Mutability::Mut
458 /// Returns an iterator over all function arguments.
460 pub fn args_iter(&self) -> impl Iterator<Item = Local> + ExactSizeIterator {
461 (1..self.arg_count + 1).map(Local::new)
464 /// Returns an iterator over all user-defined variables and compiler-generated temporaries (all
465 /// locals that are neither arguments nor the return place).
467 pub fn vars_and_temps_iter(
469 ) -> impl DoubleEndedIterator<Item = Local> + ExactSizeIterator {
470 (self.arg_count + 1..self.local_decls.len()).map(Local::new)
474 pub fn drain_vars_and_temps<'a>(&'a mut self) -> impl Iterator<Item = LocalDecl<'tcx>> + 'a {
475 self.local_decls.drain(self.arg_count + 1..)
478 /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
479 /// invalidating statement indices in `Location`s.
480 pub fn make_statement_nop(&mut self, location: Location) {
481 let block = &mut self.basic_blocks[location.block];
482 debug_assert!(location.statement_index < block.statements.len());
483 block.statements[location.statement_index].make_nop()
486 /// Returns the source info associated with `location`.
487 pub fn source_info(&self, location: Location) -> &SourceInfo {
488 let block = &self[location.block];
489 let stmts = &block.statements;
490 let idx = location.statement_index;
491 if idx < stmts.len() {
492 &stmts[idx].source_info
494 assert_eq!(idx, stmts.len());
495 &block.terminator().source_info
499 /// Returns the return type; it always return first element from `local_decls` array.
501 pub fn return_ty(&self) -> Ty<'tcx> {
502 self.local_decls[RETURN_PLACE].ty
505 /// Gets the location of the terminator for the given block.
507 pub fn terminator_loc(&self, bb: BasicBlock) -> Location {
508 Location { block: bb, statement_index: self[bb].statements.len() }
511 pub fn stmt_at(&self, location: Location) -> Either<&Statement<'tcx>, &Terminator<'tcx>> {
512 let Location { block, statement_index } = location;
513 let block_data = &self.basic_blocks[block];
516 .get(statement_index)
518 .unwrap_or_else(|| Either::Right(block_data.terminator()))
522 pub fn predecessors(&self) -> &Predecessors {
523 self.predecessor_cache.compute(&self.basic_blocks)
527 pub fn dominators(&self) -> Dominators<BasicBlock> {
532 pub fn yield_ty(&self) -> Option<Ty<'tcx>> {
533 self.generator.as_ref().and_then(|generator| generator.yield_ty)
537 pub fn generator_layout(&self) -> Option<&GeneratorLayout<'tcx>> {
538 self.generator.as_ref().and_then(|generator| generator.generator_layout.as_ref())
542 pub fn generator_drop(&self) -> Option<&Body<'tcx>> {
543 self.generator.as_ref().and_then(|generator| generator.generator_drop.as_ref())
547 pub fn generator_kind(&self) -> Option<GeneratorKind> {
548 self.generator.as_ref().map(|generator| generator.generator_kind)
552 #[derive(Copy, Clone, PartialEq, Eq, Debug, TyEncodable, TyDecodable, HashStable)]
555 /// Unsafe because of compiler-generated unsafe code, like `await` desugaring
557 /// Unsafe because of an unsafe fn
559 /// Unsafe because of an `unsafe` block
560 ExplicitUnsafe(hir::HirId),
563 impl<'tcx> Index<BasicBlock> for Body<'tcx> {
564 type Output = BasicBlockData<'tcx>;
567 fn index(&self, index: BasicBlock) -> &BasicBlockData<'tcx> {
568 &self.basic_blocks()[index]
572 impl<'tcx> IndexMut<BasicBlock> for Body<'tcx> {
574 fn index_mut(&mut self, index: BasicBlock) -> &mut BasicBlockData<'tcx> {
575 &mut self.basic_blocks_mut()[index]
579 #[derive(Copy, Clone, Debug, HashStable, TypeFoldable)]
580 pub enum ClearCrossCrate<T> {
585 impl<T> ClearCrossCrate<T> {
586 pub fn as_ref(&self) -> ClearCrossCrate<&T> {
588 ClearCrossCrate::Clear => ClearCrossCrate::Clear,
589 ClearCrossCrate::Set(v) => ClearCrossCrate::Set(v),
593 pub fn assert_crate_local(self) -> T {
595 ClearCrossCrate::Clear => bug!("unwrapping cross-crate data"),
596 ClearCrossCrate::Set(v) => v,
601 const TAG_CLEAR_CROSS_CRATE_CLEAR: u8 = 0;
602 const TAG_CLEAR_CROSS_CRATE_SET: u8 = 1;
604 impl<'tcx, E: TyEncoder<'tcx>, T: Encodable<E>> Encodable<E> for ClearCrossCrate<T> {
606 fn encode(&self, e: &mut E) -> Result<(), E::Error> {
607 if E::CLEAR_CROSS_CRATE {
612 ClearCrossCrate::Clear => TAG_CLEAR_CROSS_CRATE_CLEAR.encode(e),
613 ClearCrossCrate::Set(ref val) => {
614 TAG_CLEAR_CROSS_CRATE_SET.encode(e)?;
620 impl<'tcx, D: TyDecoder<'tcx>, T: Decodable<D>> Decodable<D> for ClearCrossCrate<T> {
622 fn decode(d: &mut D) -> ClearCrossCrate<T> {
623 if D::CLEAR_CROSS_CRATE {
624 return ClearCrossCrate::Clear;
627 let discr = u8::decode(d);
630 TAG_CLEAR_CROSS_CRATE_CLEAR => ClearCrossCrate::Clear,
631 TAG_CLEAR_CROSS_CRATE_SET => {
632 let val = T::decode(d);
633 ClearCrossCrate::Set(val)
635 tag => panic!("Invalid tag for ClearCrossCrate: {:?}", tag),
640 /// Grouped information about the source code origin of a MIR entity.
641 /// Intended to be inspected by diagnostics and debuginfo.
642 /// Most passes can work with it as a whole, within a single function.
643 // The unofficial Cranelift backend, at least as of #65828, needs `SourceInfo` to implement `Eq` and
644 // `Hash`. Please ping @bjorn3 if removing them.
645 #[derive(Copy, Clone, Debug, Eq, PartialEq, TyEncodable, TyDecodable, Hash, HashStable)]
646 pub struct SourceInfo {
647 /// The source span for the AST pertaining to this MIR entity.
650 /// The source scope, keeping track of which bindings can be
651 /// seen by debuginfo, active lint levels, `unsafe {...}`, etc.
652 pub scope: SourceScope,
657 pub fn outermost(span: Span) -> Self {
658 SourceInfo { span, scope: OUTERMOST_SOURCE_SCOPE }
662 ///////////////////////////////////////////////////////////////////////////
665 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, TyEncodable, TyDecodable)]
666 #[derive(Hash, HashStable)]
667 pub enum BorrowKind {
668 /// Data must be immutable and is aliasable.
671 /// The immediately borrowed place must be immutable, but projections from
672 /// it don't need to be. For example, a shallow borrow of `a.b` doesn't
673 /// conflict with a mutable borrow of `a.b.c`.
675 /// This is used when lowering matches: when matching on a place we want to
676 /// ensure that place have the same value from the start of the match until
677 /// an arm is selected. This prevents this code from compiling:
679 /// let mut x = &Some(0);
682 /// Some(_) if { x = &None; false } => (),
686 /// This can't be a shared borrow because mutably borrowing (*x as Some).0
687 /// should not prevent `if let None = x { ... }`, for example, because the
688 /// mutating `(*x as Some).0` can't affect the discriminant of `x`.
689 /// We can also report errors with this kind of borrow differently.
692 /// Data must be immutable but not aliasable. This kind of borrow
693 /// cannot currently be expressed by the user and is used only in
694 /// implicit closure bindings. It is needed when the closure is
695 /// borrowing or mutating a mutable referent, e.g.:
697 /// let x: &mut isize = ...;
698 /// let y = || *x += 5;
700 /// If we were to try to translate this closure into a more explicit
701 /// form, we'd encounter an error with the code as written:
703 /// struct Env { x: & &mut isize }
704 /// let x: &mut isize = ...;
705 /// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn
706 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
708 /// This is then illegal because you cannot mutate an `&mut` found
709 /// in an aliasable location. To solve, you'd have to translate with
710 /// an `&mut` borrow:
712 /// struct Env { x: &mut &mut isize }
713 /// let x: &mut isize = ...;
714 /// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
715 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
717 /// Now the assignment to `**env.x` is legal, but creating a
718 /// mutable pointer to `x` is not because `x` is not mutable. We
719 /// could fix this by declaring `x` as `let mut x`. This is ok in
720 /// user code, if awkward, but extra weird for closures, since the
721 /// borrow is hidden.
723 /// So we introduce a "unique imm" borrow -- the referent is
724 /// immutable, but not aliasable. This solves the problem. For
725 /// simplicity, we don't give users the way to express this
726 /// borrow, it's just used when translating closures.
729 /// Data is mutable and not aliasable.
731 /// `true` if this borrow arose from method-call auto-ref
732 /// (i.e., `adjustment::Adjust::Borrow`).
733 allow_two_phase_borrow: bool,
738 pub fn allows_two_phase_borrow(&self) -> bool {
740 BorrowKind::Shared | BorrowKind::Shallow | BorrowKind::Unique => false,
741 BorrowKind::Mut { allow_two_phase_borrow } => allow_two_phase_borrow,
745 pub fn describe_mutability(&self) -> String {
747 BorrowKind::Shared | BorrowKind::Shallow | BorrowKind::Unique => {
748 "immutable".to_string()
750 BorrowKind::Mut { .. } => "mutable".to_string(),
755 ///////////////////////////////////////////////////////////////////////////
756 // Variables and temps
758 rustc_index::newtype_index! {
761 DEBUG_FORMAT = "_{}",
762 const RETURN_PLACE = 0,
766 impl Atom for Local {
767 fn index(self) -> usize {
772 /// Classifies locals into categories. See `Body::local_kind`.
773 #[derive(Clone, Copy, PartialEq, Eq, Debug, HashStable)]
775 /// User-declared variable binding.
777 /// Compiler-introduced temporary.
779 /// Function argument.
781 /// Location of function's return value.
785 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable)]
786 pub struct VarBindingForm<'tcx> {
787 /// Is variable bound via `x`, `mut x`, `ref x`, or `ref mut x`?
788 pub binding_mode: ty::BindingMode,
789 /// If an explicit type was provided for this variable binding,
790 /// this holds the source Span of that type.
792 /// NOTE: if you want to change this to a `HirId`, be wary that
793 /// doing so breaks incremental compilation (as of this writing),
794 /// while a `Span` does not cause our tests to fail.
795 pub opt_ty_info: Option<Span>,
796 /// Place of the RHS of the =, or the subject of the `match` where this
797 /// variable is initialized. None in the case of `let PATTERN;`.
798 /// Some((None, ..)) in the case of and `let [mut] x = ...` because
799 /// (a) the right-hand side isn't evaluated as a place expression.
800 /// (b) it gives a way to separate this case from the remaining cases
802 pub opt_match_place: Option<(Option<Place<'tcx>>, Span)>,
803 /// The span of the pattern in which this variable was bound.
807 #[derive(Clone, Debug, TyEncodable, TyDecodable)]
808 pub enum BindingForm<'tcx> {
809 /// This is a binding for a non-`self` binding, or a `self` that has an explicit type.
810 Var(VarBindingForm<'tcx>),
811 /// Binding for a `self`/`&self`/`&mut self` binding where the type is implicit.
812 ImplicitSelf(ImplicitSelfKind),
813 /// Reference used in a guard expression to ensure immutability.
817 /// Represents what type of implicit self a function has, if any.
818 #[derive(Clone, Copy, PartialEq, Debug, TyEncodable, TyDecodable, HashStable)]
819 pub enum ImplicitSelfKind {
820 /// Represents a `fn x(self);`.
822 /// Represents a `fn x(mut self);`.
824 /// Represents a `fn x(&self);`.
826 /// Represents a `fn x(&mut self);`.
828 /// Represents when a function does not have a self argument or
829 /// when a function has a `self: X` argument.
833 TrivialTypeFoldableAndLiftImpls! { BindingForm<'tcx>, }
835 mod binding_form_impl {
836 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
837 use rustc_query_system::ich::StableHashingContext;
839 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for super::BindingForm<'tcx> {
840 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
841 use super::BindingForm::*;
842 std::mem::discriminant(self).hash_stable(hcx, hasher);
845 Var(binding) => binding.hash_stable(hcx, hasher),
846 ImplicitSelf(kind) => kind.hash_stable(hcx, hasher),
853 /// `BlockTailInfo` is attached to the `LocalDecl` for temporaries
854 /// created during evaluation of expressions in a block tail
855 /// expression; that is, a block like `{ STMT_1; STMT_2; EXPR }`.
857 /// It is used to improve diagnostics when such temporaries are
858 /// involved in borrow_check errors, e.g., explanations of where the
859 /// temporaries come from, when their destructors are run, and/or how
860 /// one might revise the code to satisfy the borrow checker's rules.
861 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable)]
862 pub struct BlockTailInfo {
863 /// If `true`, then the value resulting from evaluating this tail
864 /// expression is ignored by the block's expression context.
866 /// Examples include `{ ...; tail };` and `let _ = { ...; tail };`
867 /// but not e.g., `let _x = { ...; tail };`
868 pub tail_result_is_ignored: bool,
870 /// `Span` of the tail expression.
876 /// This can be a binding declared by the user, a temporary inserted by the compiler, a function
877 /// argument, or the return place.
878 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
879 pub struct LocalDecl<'tcx> {
880 /// Whether this is a mutable binding (i.e., `let x` or `let mut x`).
882 /// Temporaries and the return place are always mutable.
883 pub mutability: Mutability,
885 // FIXME(matthewjasper) Don't store in this in `Body`
886 pub local_info: Option<Box<LocalInfo<'tcx>>>,
888 /// `true` if this is an internal local.
890 /// These locals are not based on types in the source code and are only used
891 /// for a few desugarings at the moment.
893 /// The generator transformation will sanity check the locals which are live
894 /// across a suspension point against the type components of the generator
895 /// which type checking knows are live across a suspension point. We need to
896 /// flag drop flags to avoid triggering this check as they are introduced
897 /// outside of type inference.
899 /// This should be sound because the drop flags are fully algebraic, and
900 /// therefore don't affect the auto-trait or outlives properties of the
904 /// If this local is a temporary and `is_block_tail` is `Some`,
905 /// then it is a temporary created for evaluation of some
906 /// subexpression of some block's tail expression (with no
907 /// intervening statement context).
908 // FIXME(matthewjasper) Don't store in this in `Body`
909 pub is_block_tail: Option<BlockTailInfo>,
911 /// The type of this local.
914 /// If the user manually ascribed a type to this variable,
915 /// e.g., via `let x: T`, then we carry that type here. The MIR
916 /// borrow checker needs this information since it can affect
917 /// region inference.
918 // FIXME(matthewjasper) Don't store in this in `Body`
919 pub user_ty: Option<Box<UserTypeProjections>>,
921 /// The *syntactic* (i.e., not visibility) source scope the local is defined
922 /// in. If the local was defined in a let-statement, this
923 /// is *within* the let-statement, rather than outside
926 /// This is needed because the visibility source scope of locals within
927 /// a let-statement is weird.
929 /// The reason is that we want the local to be *within* the let-statement
930 /// for lint purposes, but we want the local to be *after* the let-statement
931 /// for names-in-scope purposes.
933 /// That's it, if we have a let-statement like the one in this
937 /// fn foo(x: &str) {
938 /// #[allow(unused_mut)]
939 /// let mut x: u32 = { // <- one unused mut
940 /// let mut y: u32 = x.parse().unwrap();
947 /// Then, from a lint point of view, the declaration of `x: u32`
948 /// (and `y: u32`) are within the `#[allow(unused_mut)]` scope - the
949 /// lint scopes are the same as the AST/HIR nesting.
951 /// However, from a name lookup point of view, the scopes look more like
952 /// as if the let-statements were `match` expressions:
955 /// fn foo(x: &str) {
957 /// match x.parse().unwrap() {
966 /// We care about the name-lookup scopes for debuginfo - if the
967 /// debuginfo instruction pointer is at the call to `x.parse()`, we
968 /// want `x` to refer to `x: &str`, but if it is at the call to
969 /// `drop(x)`, we want it to refer to `x: u32`.
971 /// To allow both uses to work, we need to have more than a single scope
972 /// for a local. We have the `source_info.scope` represent the "syntactic"
973 /// lint scope (with a variable being under its let block) while the
974 /// `var_debug_info.source_info.scope` represents the "local variable"
975 /// scope (where the "rest" of a block is under all prior let-statements).
977 /// The end result looks like this:
981 /// │{ argument x: &str }
983 /// │ │{ #[allow(unused_mut)] } // This is actually split into 2 scopes
984 /// │ │ // in practice because I'm lazy.
986 /// │ │← x.source_info.scope
987 /// │ │← `x.parse().unwrap()`
989 /// │ │ │← y.source_info.scope
991 /// │ │ │{ let y: u32 }
993 /// │ │ │← y.var_debug_info.source_info.scope
996 /// │ │{ let x: u32 }
997 /// │ │← x.var_debug_info.source_info.scope
998 /// │ │← `drop(x)` // This accesses `x: u32`.
1000 pub source_info: SourceInfo,
1003 // `LocalDecl` is used a lot. Make sure it doesn't unintentionally get bigger.
1004 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
1005 static_assert_size!(LocalDecl<'_>, 56);
1007 /// Extra information about a some locals that's used for diagnostics and for
1008 /// classifying variables into local variables, statics, etc, which is needed e.g.
1009 /// for unsafety checking.
1011 /// Not used for non-StaticRef temporaries, the return place, or anonymous
1012 /// function parameters.
1013 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
1014 pub enum LocalInfo<'tcx> {
1015 /// A user-defined local variable or function parameter
1017 /// The `BindingForm` is solely used for local diagnostics when generating
1018 /// warnings/errors when compiling the current crate, and therefore it need
1019 /// not be visible across crates.
1020 User(ClearCrossCrate<BindingForm<'tcx>>),
1021 /// A temporary created that references the static with the given `DefId`.
1022 StaticRef { def_id: DefId, is_thread_local: bool },
1023 /// A temporary created that references the const with the given `DefId`
1024 ConstRef { def_id: DefId },
1025 /// A temporary created during the creation of an aggregate
1026 /// (e.g. a temporary for `foo` in `MyStruct { my_field: foo }`)
1030 impl<'tcx> LocalDecl<'tcx> {
1031 /// Returns `true` only if local is a binding that can itself be
1032 /// made mutable via the addition of the `mut` keyword, namely
1033 /// something like the occurrences of `x` in:
1034 /// - `fn foo(x: Type) { ... }`,
1035 /// - `let x = ...`,
1036 /// - or `match ... { C(x) => ... }`
1037 pub fn can_be_made_mutable(&self) -> bool {
1040 Some(box LocalInfo::User(ClearCrossCrate::Set(
1041 BindingForm::Var(VarBindingForm {
1042 binding_mode: ty::BindingMode::BindByValue(_),
1046 }) | BindingForm::ImplicitSelf(ImplicitSelfKind::Imm),
1051 /// Returns `true` if local is definitely not a `ref ident` or
1052 /// `ref mut ident` binding. (Such bindings cannot be made into
1053 /// mutable bindings, but the inverse does not necessarily hold).
1054 pub fn is_nonref_binding(&self) -> bool {
1057 Some(box LocalInfo::User(ClearCrossCrate::Set(
1058 BindingForm::Var(VarBindingForm {
1059 binding_mode: ty::BindingMode::BindByValue(_),
1063 }) | BindingForm::ImplicitSelf(_),
1068 /// Returns `true` if this variable is a named variable or function
1069 /// parameter declared by the user.
1071 pub fn is_user_variable(&self) -> bool {
1072 matches!(self.local_info, Some(box LocalInfo::User(_)))
1075 /// Returns `true` if this is a reference to a variable bound in a `match`
1076 /// expression that is used to access said variable for the guard of the
1078 pub fn is_ref_for_guard(&self) -> bool {
1081 Some(box LocalInfo::User(ClearCrossCrate::Set(BindingForm::RefForGuard)))
1085 /// Returns `Some` if this is a reference to a static item that is used to
1086 /// access that static.
1087 pub fn is_ref_to_static(&self) -> bool {
1088 matches!(self.local_info, Some(box LocalInfo::StaticRef { .. }))
1091 /// Returns `Some` if this is a reference to a thread-local static item that is used to
1092 /// access that static.
1093 pub fn is_ref_to_thread_local(&self) -> bool {
1094 match self.local_info {
1095 Some(box LocalInfo::StaticRef { is_thread_local, .. }) => is_thread_local,
1100 /// Returns `true` is the local is from a compiler desugaring, e.g.,
1101 /// `__next` from a `for` loop.
1103 pub fn from_compiler_desugaring(&self) -> bool {
1104 self.source_info.span.desugaring_kind().is_some()
1107 /// Creates a new `LocalDecl` for a temporary: mutable, non-internal.
1109 pub fn new(ty: Ty<'tcx>, span: Span) -> Self {
1110 Self::with_source_info(ty, SourceInfo::outermost(span))
1113 /// Like `LocalDecl::new`, but takes a `SourceInfo` instead of a `Span`.
1115 pub fn with_source_info(ty: Ty<'tcx>, source_info: SourceInfo) -> Self {
1117 mutability: Mutability::Mut,
1120 is_block_tail: None,
1127 /// Converts `self` into same `LocalDecl` except tagged as internal.
1129 pub fn internal(mut self) -> Self {
1130 self.internal = true;
1134 /// Converts `self` into same `LocalDecl` except tagged as immutable.
1136 pub fn immutable(mut self) -> Self {
1137 self.mutability = Mutability::Not;
1141 /// Converts `self` into same `LocalDecl` except tagged as internal temporary.
1143 pub fn block_tail(mut self, info: BlockTailInfo) -> Self {
1144 assert!(self.is_block_tail.is_none());
1145 self.is_block_tail = Some(info);
1150 #[derive(Clone, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
1151 pub enum VarDebugInfoContents<'tcx> {
1152 /// NOTE(eddyb) There's an unenforced invariant that this `Place` is
1153 /// based on a `Local`, not a `Static`, and contains no indexing.
1155 Const(Constant<'tcx>),
1158 impl<'tcx> Debug for VarDebugInfoContents<'tcx> {
1159 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1161 VarDebugInfoContents::Const(c) => write!(fmt, "{}", c),
1162 VarDebugInfoContents::Place(p) => write!(fmt, "{:?}", p),
1167 /// Debug information pertaining to a user variable.
1168 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
1169 pub struct VarDebugInfo<'tcx> {
1172 /// Source info of the user variable, including the scope
1173 /// within which the variable is visible (to debuginfo)
1174 /// (see `LocalDecl`'s `source_info` field for more details).
1175 pub source_info: SourceInfo,
1177 /// Where the data for this user variable is to be found.
1178 pub value: VarDebugInfoContents<'tcx>,
1181 ///////////////////////////////////////////////////////////////////////////
1184 rustc_index::newtype_index! {
1185 /// A node in the MIR [control-flow graph][CFG].
1187 /// There are no branches (e.g., `if`s, function calls, etc.) within a basic block, which makes
1188 /// it easier to do [data-flow analyses] and optimizations. Instead, branches are represented
1189 /// as an edge in a graph between basic blocks.
1191 /// Basic blocks consist of a series of [statements][Statement], ending with a
1192 /// [terminator][Terminator]. Basic blocks can have multiple predecessors and successors,
1193 /// however there is a MIR pass ([`CriticalCallEdges`]) that removes *critical edges*, which
1194 /// are edges that go from a multi-successor node to a multi-predecessor node. This pass is
1195 /// needed because some analyses require that there are no critical edges in the CFG.
1197 /// Note that this type is just an index into [`Body.basic_blocks`](Body::basic_blocks);
1198 /// the actual data that a basic block holds is in [`BasicBlockData`].
1200 /// Read more about basic blocks in the [rustc-dev-guide][guide-mir].
1202 /// [CFG]: https://rustc-dev-guide.rust-lang.org/appendix/background.html#cfg
1203 /// [data-flow analyses]:
1204 /// https://rustc-dev-guide.rust-lang.org/appendix/background.html#what-is-a-dataflow-analysis
1205 /// [`CriticalCallEdges`]: ../../rustc_const_eval/transform/add_call_guards/enum.AddCallGuards.html#variant.CriticalCallEdges
1206 /// [guide-mir]: https://rustc-dev-guide.rust-lang.org/mir/
1207 pub struct BasicBlock {
1209 DEBUG_FORMAT = "bb{}",
1210 const START_BLOCK = 0,
1215 pub fn start_location(self) -> Location {
1216 Location { block: self, statement_index: 0 }
1220 ///////////////////////////////////////////////////////////////////////////
1221 // BasicBlockData and Terminator
1223 /// See [`BasicBlock`] for documentation on what basic blocks are at a high level.
1224 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
1225 pub struct BasicBlockData<'tcx> {
1226 /// List of statements in this block.
1227 pub statements: Vec<Statement<'tcx>>,
1229 /// Terminator for this block.
1231 /// N.B., this should generally ONLY be `None` during construction.
1232 /// Therefore, you should generally access it via the
1233 /// `terminator()` or `terminator_mut()` methods. The only
1234 /// exception is that certain passes, such as `simplify_cfg`, swap
1235 /// out the terminator temporarily with `None` while they continue
1236 /// to recurse over the set of basic blocks.
1237 pub terminator: Option<Terminator<'tcx>>,
1239 /// If true, this block lies on an unwind path. This is used
1240 /// during codegen where distinct kinds of basic blocks may be
1241 /// generated (particularly for MSVC cleanup). Unwind blocks must
1242 /// only branch to other unwind blocks.
1243 pub is_cleanup: bool,
1246 /// Information about an assertion failure.
1247 #[derive(Clone, TyEncodable, TyDecodable, Hash, HashStable, PartialEq, PartialOrd)]
1248 pub enum AssertKind<O> {
1249 BoundsCheck { len: O, index: O },
1250 Overflow(BinOp, O, O),
1254 ResumedAfterReturn(GeneratorKind),
1255 ResumedAfterPanic(GeneratorKind),
1258 #[derive(Clone, Debug, PartialEq, TyEncodable, TyDecodable, Hash, HashStable, TypeFoldable)]
1259 pub enum InlineAsmOperand<'tcx> {
1261 reg: InlineAsmRegOrRegClass,
1262 value: Operand<'tcx>,
1265 reg: InlineAsmRegOrRegClass,
1267 place: Option<Place<'tcx>>,
1270 reg: InlineAsmRegOrRegClass,
1272 in_value: Operand<'tcx>,
1273 out_place: Option<Place<'tcx>>,
1276 value: Box<Constant<'tcx>>,
1279 value: Box<Constant<'tcx>>,
1286 /// Type for MIR `Assert` terminator error messages.
1287 pub type AssertMessage<'tcx> = AssertKind<Operand<'tcx>>;
1289 pub type Successors<'a> =
1290 iter::Chain<option::IntoIter<&'a BasicBlock>, slice::Iter<'a, BasicBlock>>;
1291 pub type SuccessorsMut<'a> =
1292 iter::Chain<option::IntoIter<&'a mut BasicBlock>, slice::IterMut<'a, BasicBlock>>;
1294 impl<'tcx> BasicBlockData<'tcx> {
1295 pub fn new(terminator: Option<Terminator<'tcx>>) -> BasicBlockData<'tcx> {
1296 BasicBlockData { statements: vec![], terminator, is_cleanup: false }
1299 /// Accessor for terminator.
1301 /// Terminator may not be None after construction of the basic block is complete. This accessor
1302 /// provides a convenience way to reach the terminator.
1304 pub fn terminator(&self) -> &Terminator<'tcx> {
1305 self.terminator.as_ref().expect("invalid terminator state")
1309 pub fn terminator_mut(&mut self) -> &mut Terminator<'tcx> {
1310 self.terminator.as_mut().expect("invalid terminator state")
1313 pub fn retain_statements<F>(&mut self, mut f: F)
1315 F: FnMut(&mut Statement<'_>) -> bool,
1317 for s in &mut self.statements {
1324 pub fn expand_statements<F, I>(&mut self, mut f: F)
1326 F: FnMut(&mut Statement<'tcx>) -> Option<I>,
1327 I: iter::TrustedLen<Item = Statement<'tcx>>,
1329 // Gather all the iterators we'll need to splice in, and their positions.
1330 let mut splices: Vec<(usize, I)> = vec![];
1331 let mut extra_stmts = 0;
1332 for (i, s) in self.statements.iter_mut().enumerate() {
1333 if let Some(mut new_stmts) = f(s) {
1334 if let Some(first) = new_stmts.next() {
1335 // We can already store the first new statement.
1338 // Save the other statements for optimized splicing.
1339 let remaining = new_stmts.size_hint().0;
1341 splices.push((i + 1 + extra_stmts, new_stmts));
1342 extra_stmts += remaining;
1350 // Splice in the new statements, from the end of the block.
1351 // FIXME(eddyb) This could be more efficient with a "gap buffer"
1352 // where a range of elements ("gap") is left uninitialized, with
1353 // splicing adding new elements to the end of that gap and moving
1354 // existing elements from before the gap to the end of the gap.
1355 // For now, this is safe code, emulating a gap but initializing it.
1356 let mut gap = self.statements.len()..self.statements.len() + extra_stmts;
1357 self.statements.resize(
1359 Statement { source_info: SourceInfo::outermost(DUMMY_SP), kind: StatementKind::Nop },
1361 for (splice_start, new_stmts) in splices.into_iter().rev() {
1362 let splice_end = splice_start + new_stmts.size_hint().0;
1363 while gap.end > splice_end {
1366 self.statements.swap(gap.start, gap.end);
1368 self.statements.splice(splice_start..splice_end, new_stmts);
1369 gap.end = splice_start;
1373 pub fn visitable(&self, index: usize) -> &dyn MirVisitable<'tcx> {
1374 if index < self.statements.len() { &self.statements[index] } else { &self.terminator }
1378 impl<O> AssertKind<O> {
1379 /// Getting a description does not require `O` to be printable, and does not
1380 /// require allocation.
1381 /// The caller is expected to handle `BoundsCheck` separately.
1382 pub fn description(&self) -> &'static str {
1385 Overflow(BinOp::Add, _, _) => "attempt to add with overflow",
1386 Overflow(BinOp::Sub, _, _) => "attempt to subtract with overflow",
1387 Overflow(BinOp::Mul, _, _) => "attempt to multiply with overflow",
1388 Overflow(BinOp::Div, _, _) => "attempt to divide with overflow",
1389 Overflow(BinOp::Rem, _, _) => "attempt to calculate the remainder with overflow",
1390 OverflowNeg(_) => "attempt to negate with overflow",
1391 Overflow(BinOp::Shr, _, _) => "attempt to shift right with overflow",
1392 Overflow(BinOp::Shl, _, _) => "attempt to shift left with overflow",
1393 Overflow(op, _, _) => bug!("{:?} cannot overflow", op),
1394 DivisionByZero(_) => "attempt to divide by zero",
1395 RemainderByZero(_) => "attempt to calculate the remainder with a divisor of zero",
1396 ResumedAfterReturn(GeneratorKind::Gen) => "generator resumed after completion",
1397 ResumedAfterReturn(GeneratorKind::Async(_)) => "`async fn` resumed after completion",
1398 ResumedAfterPanic(GeneratorKind::Gen) => "generator resumed after panicking",
1399 ResumedAfterPanic(GeneratorKind::Async(_)) => "`async fn` resumed after panicking",
1400 BoundsCheck { .. } => bug!("Unexpected AssertKind"),
1404 /// Format the message arguments for the `assert(cond, msg..)` terminator in MIR printing.
1405 pub fn fmt_assert_args<W: Write>(&self, f: &mut W) -> fmt::Result
1411 BoundsCheck { ref len, ref index } => write!(
1413 "\"index out of bounds: the length is {{}} but the index is {{}}\", {:?}, {:?}",
1417 OverflowNeg(op) => {
1418 write!(f, "\"attempt to negate `{{}}`, which would overflow\", {:?}", op)
1420 DivisionByZero(op) => write!(f, "\"attempt to divide `{{}}` by zero\", {:?}", op),
1421 RemainderByZero(op) => write!(
1423 "\"attempt to calculate the remainder of `{{}}` with a divisor of zero\", {:?}",
1426 Overflow(BinOp::Add, l, r) => write!(
1428 "\"attempt to compute `{{}} + {{}}`, which would overflow\", {:?}, {:?}",
1431 Overflow(BinOp::Sub, l, r) => write!(
1433 "\"attempt to compute `{{}} - {{}}`, which would overflow\", {:?}, {:?}",
1436 Overflow(BinOp::Mul, l, r) => write!(
1438 "\"attempt to compute `{{}} * {{}}`, which would overflow\", {:?}, {:?}",
1441 Overflow(BinOp::Div, l, r) => write!(
1443 "\"attempt to compute `{{}} / {{}}`, which would overflow\", {:?}, {:?}",
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 impl<O: fmt::Debug> fmt::Debug for AssertKind<O> {
1463 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1466 BoundsCheck { ref len, ref index } => write!(
1468 "index out of bounds: the length is {:?} but the index is {:?}",
1471 OverflowNeg(op) => write!(f, "attempt to negate `{:#?}`, which would overflow", op),
1472 DivisionByZero(op) => write!(f, "attempt to divide `{:#?}` by zero", op),
1473 RemainderByZero(op) => write!(
1475 "attempt to calculate the remainder of `{:#?}` with a divisor of zero",
1478 Overflow(BinOp::Add, l, r) => {
1479 write!(f, "attempt to compute `{:#?} + {:#?}`, which would overflow", l, r)
1481 Overflow(BinOp::Sub, l, r) => {
1482 write!(f, "attempt to compute `{:#?} - {:#?}`, which would overflow", l, r)
1484 Overflow(BinOp::Mul, l, r) => {
1485 write!(f, "attempt to compute `{:#?} * {:#?}`, which would overflow", l, r)
1487 Overflow(BinOp::Div, l, r) => {
1488 write!(f, "attempt to compute `{:#?} / {:#?}`, which would overflow", l, r)
1490 Overflow(BinOp::Rem, l, r) => write!(
1492 "attempt to compute the remainder of `{:#?} % {:#?}`, which would overflow",
1495 Overflow(BinOp::Shr, _, r) => {
1496 write!(f, "attempt to shift right by `{:#?}`, which would overflow", r)
1498 Overflow(BinOp::Shl, _, r) => {
1499 write!(f, "attempt to shift left by `{:#?}`, which would overflow", r)
1501 _ => write!(f, "{}", self.description()),
1506 ///////////////////////////////////////////////////////////////////////////
1509 #[derive(Clone, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
1510 pub struct Statement<'tcx> {
1511 pub source_info: SourceInfo,
1512 pub kind: StatementKind<'tcx>,
1515 // `Statement` is used a lot. Make sure it doesn't unintentionally get bigger.
1516 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
1517 static_assert_size!(Statement<'_>, 32);
1519 impl Statement<'_> {
1520 /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
1521 /// invalidating statement indices in `Location`s.
1522 pub fn make_nop(&mut self) {
1523 self.kind = StatementKind::Nop
1526 /// Changes a statement to a nop and returns the original statement.
1527 #[must_use = "If you don't need the statement, use `make_nop` instead"]
1528 pub fn replace_nop(&mut self) -> Self {
1530 source_info: self.source_info,
1531 kind: mem::replace(&mut self.kind, StatementKind::Nop),
1536 #[derive(Clone, Debug, PartialEq, TyEncodable, TyDecodable, Hash, HashStable, TypeFoldable)]
1537 pub enum StatementKind<'tcx> {
1538 /// Write the RHS Rvalue to the LHS Place.
1539 Assign(Box<(Place<'tcx>, Rvalue<'tcx>)>),
1541 /// This represents all the reading that a pattern match may do
1542 /// (e.g., inspecting constants and discriminant values), and the
1543 /// kind of pattern it comes from. This is in order to adapt potential
1544 /// error messages to these specific patterns.
1546 /// Note that this also is emitted for regular `let` bindings to ensure that locals that are
1547 /// never accessed still get some sanity checks for, e.g., `let x: ! = ..;`
1548 FakeRead(Box<(FakeReadCause, Place<'tcx>)>),
1550 /// Write the discriminant for a variant to the enum Place.
1551 SetDiscriminant { place: Box<Place<'tcx>>, variant_index: VariantIdx },
1553 /// Start a live range for the storage of the local.
1556 /// End the current live range for the storage of the local.
1559 /// Retag references in the given place, ensuring they got fresh tags. This is
1560 /// part of the Stacked Borrows model. These statements are currently only interpreted
1561 /// by miri and only generated when "-Z mir-emit-retag" is passed.
1562 /// See <https://internals.rust-lang.org/t/stacked-borrows-an-aliasing-model-for-rust/8153/>
1563 /// for more details.
1564 Retag(RetagKind, Box<Place<'tcx>>),
1566 /// Encodes a user's type ascription. These need to be preserved
1567 /// intact so that NLL can respect them. For example:
1571 /// The effect of this annotation is to relate the type `T_y` of the place `y`
1572 /// to the user-given type `T`. The effect depends on the specified variance:
1574 /// - `Covariant` -- requires that `T_y <: T`
1575 /// - `Contravariant` -- requires that `T_y :> T`
1576 /// - `Invariant` -- requires that `T_y == T`
1577 /// - `Bivariant` -- no effect
1578 AscribeUserType(Box<(Place<'tcx>, UserTypeProjection)>, ty::Variance),
1580 /// Marks the start of a "coverage region", injected with '-Cinstrument-coverage'. A
1581 /// `Coverage` statement carries metadata about the coverage region, used to inject a coverage
1582 /// map into the binary. If `Coverage::kind` is a `Counter`, the statement also generates
1583 /// executable code, to increment a counter variable at runtime, each time the code region is
1585 Coverage(Box<Coverage>),
1587 /// Denotes a call to the intrinsic function copy_overlapping, where `src_dst` denotes the
1588 /// memory being read from and written to(one field to save memory), and size
1589 /// indicates how many bytes are being copied over.
1590 CopyNonOverlapping(Box<CopyNonOverlapping<'tcx>>),
1592 /// No-op. Useful for deleting instructions without affecting statement indices.
1596 impl<'tcx> StatementKind<'tcx> {
1597 pub fn as_assign_mut(&mut self) -> Option<&mut (Place<'tcx>, Rvalue<'tcx>)> {
1599 StatementKind::Assign(x) => Some(x),
1604 pub fn as_assign(&self) -> Option<&(Place<'tcx>, Rvalue<'tcx>)> {
1606 StatementKind::Assign(x) => Some(x),
1612 /// Describes what kind of retag is to be performed.
1613 #[derive(Copy, Clone, TyEncodable, TyDecodable, Debug, PartialEq, Eq, Hash, HashStable)]
1614 pub enum RetagKind {
1615 /// The initial retag when entering a function.
1617 /// Retag preparing for a two-phase borrow.
1619 /// Retagging raw pointers.
1621 /// A "normal" retag.
1625 /// The `FakeReadCause` describes the type of pattern why a FakeRead statement exists.
1626 #[derive(Copy, Clone, TyEncodable, TyDecodable, Debug, Hash, HashStable, PartialEq)]
1627 pub enum FakeReadCause {
1628 /// Inject a fake read of the borrowed input at the end of each guards
1631 /// This should ensure that you cannot change the variant for an enum while
1632 /// you are in the midst of matching on it.
1635 /// `let x: !; match x {}` doesn't generate any read of x so we need to
1636 /// generate a read of x to check that it is initialized and safe.
1638 /// If a closure pattern matches a Place starting with an Upvar, then we introduce a
1639 /// FakeRead for that Place outside the closure, in such a case this option would be
1640 /// Some(closure_def_id).
1641 /// Otherwise, the value of the optional DefId will be None.
1642 ForMatchedPlace(Option<DefId>),
1644 /// A fake read of the RefWithinGuard version of a bind-by-value variable
1645 /// in a match guard to ensure that its value hasn't change by the time
1646 /// we create the OutsideGuard version.
1649 /// Officially, the semantics of
1651 /// `let pattern = <expr>;`
1653 /// is that `<expr>` is evaluated into a temporary and then this temporary is
1654 /// into the pattern.
1656 /// However, if we see the simple pattern `let var = <expr>`, we optimize this to
1657 /// evaluate `<expr>` directly into the variable `var`. This is mostly unobservable,
1658 /// but in some cases it can affect the borrow checker, as in #53695.
1659 /// Therefore, we insert a "fake read" here to ensure that we get
1660 /// appropriate errors.
1662 /// If a closure pattern matches a Place starting with an Upvar, then we introduce a
1663 /// FakeRead for that Place outside the closure, in such a case this option would be
1664 /// Some(closure_def_id).
1665 /// Otherwise, the value of the optional DefId will be None.
1666 ForLet(Option<DefId>),
1668 /// If we have an index expression like
1670 /// (*x)[1][{ x = y; 4}]
1672 /// then the first bounds check is invalidated when we evaluate the second
1673 /// index expression. Thus we create a fake borrow of `x` across the second
1674 /// indexer, which will cause a borrow check error.
1678 impl Debug for Statement<'_> {
1679 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1680 use self::StatementKind::*;
1682 Assign(box (ref place, ref rv)) => write!(fmt, "{:?} = {:?}", place, rv),
1683 FakeRead(box (ref cause, ref place)) => {
1684 write!(fmt, "FakeRead({:?}, {:?})", cause, place)
1686 Retag(ref kind, ref place) => write!(
1690 RetagKind::FnEntry => "[fn entry] ",
1691 RetagKind::TwoPhase => "[2phase] ",
1692 RetagKind::Raw => "[raw] ",
1693 RetagKind::Default => "",
1697 StorageLive(ref place) => write!(fmt, "StorageLive({:?})", place),
1698 StorageDead(ref place) => write!(fmt, "StorageDead({:?})", place),
1699 SetDiscriminant { ref place, variant_index } => {
1700 write!(fmt, "discriminant({:?}) = {:?}", place, variant_index)
1702 AscribeUserType(box (ref place, ref c_ty), ref variance) => {
1703 write!(fmt, "AscribeUserType({:?}, {:?}, {:?})", place, variance, c_ty)
1705 Coverage(box self::Coverage { ref kind, code_region: Some(ref rgn) }) => {
1706 write!(fmt, "Coverage::{:?} for {:?}", kind, rgn)
1708 Coverage(box ref coverage) => write!(fmt, "Coverage::{:?}", coverage.kind),
1709 CopyNonOverlapping(box crate::mir::CopyNonOverlapping {
1714 write!(fmt, "copy_nonoverlapping(src={:?}, dst={:?}, count={:?})", src, dst, count)
1716 Nop => write!(fmt, "nop"),
1721 #[derive(Clone, Debug, PartialEq, TyEncodable, TyDecodable, Hash, HashStable, TypeFoldable)]
1722 pub struct Coverage {
1723 pub kind: CoverageKind,
1724 pub code_region: Option<CodeRegion>,
1727 #[derive(Clone, Debug, PartialEq, TyEncodable, TyDecodable, Hash, HashStable, TypeFoldable)]
1728 pub struct CopyNonOverlapping<'tcx> {
1729 pub src: Operand<'tcx>,
1730 pub dst: Operand<'tcx>,
1731 /// Number of elements to copy from src to dest, not bytes.
1732 pub count: Operand<'tcx>,
1735 ///////////////////////////////////////////////////////////////////////////
1738 /// A path to a value; something that can be evaluated without
1739 /// changing or disturbing program state.
1740 #[derive(Copy, Clone, PartialEq, Eq, Hash, TyEncodable, HashStable)]
1741 pub struct Place<'tcx> {
1744 /// projection out of a place (access a field, deref a pointer, etc)
1745 pub projection: &'tcx List<PlaceElem<'tcx>>,
1748 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
1749 static_assert_size!(Place<'_>, 16);
1751 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
1752 #[derive(TyEncodable, TyDecodable, HashStable)]
1753 pub enum ProjectionElem<V, T> {
1758 /// These indices are generated by slice patterns. Easiest to explain
1762 /// [X, _, .._, _, _] => { offset: 0, min_length: 4, from_end: false },
1763 /// [_, X, .._, _, _] => { offset: 1, min_length: 4, from_end: false },
1764 /// [_, _, .._, X, _] => { offset: 2, min_length: 4, from_end: true },
1765 /// [_, _, .._, _, X] => { offset: 1, min_length: 4, from_end: true },
1768 /// index or -index (in Python terms), depending on from_end
1770 /// The thing being indexed must be at least this long. For arrays this
1771 /// is always the exact length.
1773 /// Counting backwards from end? This is always false when indexing an
1778 /// These indices are generated by slice patterns.
1780 /// If `from_end` is true `slice[from..slice.len() - to]`.
1781 /// Otherwise `array[from..to]`.
1785 /// Whether `to` counts from the start or end of the array/slice.
1786 /// For `PlaceElem`s this is `true` if and only if the base is a slice.
1787 /// For `ProjectionKind`, this can also be `true` for arrays.
1791 /// "Downcast" to a variant of an ADT. Currently, we only introduce
1792 /// this for ADTs with more than one variant. It may be better to
1793 /// just introduce it always, or always for enums.
1795 /// The included Symbol is the name of the variant, used for printing MIR.
1796 Downcast(Option<Symbol>, VariantIdx),
1799 impl<V, T> ProjectionElem<V, T> {
1800 /// Returns `true` if the target of this projection may refer to a different region of memory
1802 fn is_indirect(&self) -> bool {
1804 Self::Deref => true,
1808 | Self::ConstantIndex { .. }
1809 | Self::Subslice { .. }
1810 | Self::Downcast(_, _) => false,
1814 /// Returns `true` if this is a `Downcast` projection with the given `VariantIdx`.
1815 pub fn is_downcast_to(&self, v: VariantIdx) -> bool {
1816 matches!(*self, Self::Downcast(_, x) if x == v)
1819 /// Returns `true` if this is a `Field` projection with the given index.
1820 pub fn is_field_to(&self, f: Field) -> bool {
1821 matches!(*self, Self::Field(x, _) if x == f)
1825 /// Alias for projections as they appear in places, where the base is a place
1826 /// and the index is a local.
1827 pub type PlaceElem<'tcx> = ProjectionElem<Local, Ty<'tcx>>;
1829 // At least on 64 bit systems, `PlaceElem` should not be larger than two pointers.
1830 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
1831 static_assert_size!(PlaceElem<'_>, 24);
1833 /// Alias for projections as they appear in `UserTypeProjection`, where we
1834 /// need neither the `V` parameter for `Index` nor the `T` for `Field`.
1835 pub type ProjectionKind = ProjectionElem<(), ()>;
1837 rustc_index::newtype_index! {
1840 DEBUG_FORMAT = "field[{}]"
1844 #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
1845 pub struct PlaceRef<'tcx> {
1847 pub projection: &'tcx [PlaceElem<'tcx>],
1850 impl<'tcx> Place<'tcx> {
1851 // FIXME change this to a const fn by also making List::empty a const fn.
1852 pub fn return_place() -> Place<'tcx> {
1853 Place { local: RETURN_PLACE, projection: List::empty() }
1856 /// Returns `true` if this `Place` contains a `Deref` projection.
1858 /// If `Place::is_indirect` returns false, the caller knows that the `Place` refers to the
1859 /// same region of memory as its base.
1860 pub fn is_indirect(&self) -> bool {
1861 self.projection.iter().any(|elem| elem.is_indirect())
1864 /// Finds the innermost `Local` from this `Place`, *if* it is either a local itself or
1865 /// a single deref of a local.
1867 pub fn local_or_deref_local(&self) -> Option<Local> {
1868 self.as_ref().local_or_deref_local()
1871 /// If this place represents a local variable like `_X` with no
1872 /// projections, return `Some(_X)`.
1874 pub fn as_local(&self) -> Option<Local> {
1875 self.as_ref().as_local()
1879 pub fn as_ref(&self) -> PlaceRef<'tcx> {
1880 PlaceRef { local: self.local, projection: &self.projection }
1883 /// Iterate over the projections in evaluation order, i.e., the first element is the base with
1884 /// its projection and then subsequently more projections are added.
1885 /// As a concrete example, given the place a.b.c, this would yield:
1889 /// Given a place without projections, the iterator is empty.
1891 pub fn iter_projections(
1893 ) -> impl Iterator<Item = (PlaceRef<'tcx>, PlaceElem<'tcx>)> + DoubleEndedIterator {
1894 self.projection.iter().enumerate().map(move |(i, proj)| {
1895 let base = PlaceRef { local: self.local, projection: &self.projection[..i] };
1901 impl From<Local> for Place<'_> {
1902 fn from(local: Local) -> Self {
1903 Place { local, projection: List::empty() }
1907 impl<'tcx> PlaceRef<'tcx> {
1908 /// Finds the innermost `Local` from this `Place`, *if* it is either a local itself or
1909 /// a single deref of a local.
1910 pub fn local_or_deref_local(&self) -> Option<Local> {
1912 PlaceRef { local, projection: [] }
1913 | PlaceRef { local, projection: [ProjectionElem::Deref] } => Some(local),
1918 /// If this place represents a local variable like `_X` with no
1919 /// projections, return `Some(_X)`.
1921 pub fn as_local(&self) -> Option<Local> {
1923 PlaceRef { local, projection: [] } => Some(local),
1929 pub fn last_projection(&self) -> Option<(PlaceRef<'tcx>, PlaceElem<'tcx>)> {
1930 if let &[ref proj_base @ .., elem] = self.projection {
1931 Some((PlaceRef { local: self.local, projection: proj_base }, elem))
1938 impl Debug for Place<'_> {
1939 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1940 for elem in self.projection.iter().rev() {
1942 ProjectionElem::Downcast(_, _) | ProjectionElem::Field(_, _) => {
1943 write!(fmt, "(").unwrap();
1945 ProjectionElem::Deref => {
1946 write!(fmt, "(*").unwrap();
1948 ProjectionElem::Index(_)
1949 | ProjectionElem::ConstantIndex { .. }
1950 | ProjectionElem::Subslice { .. } => {}
1954 write!(fmt, "{:?}", self.local)?;
1956 for elem in self.projection.iter() {
1958 ProjectionElem::Downcast(Some(name), _index) => {
1959 write!(fmt, " as {})", name)?;
1961 ProjectionElem::Downcast(None, index) => {
1962 write!(fmt, " as variant#{:?})", index)?;
1964 ProjectionElem::Deref => {
1967 ProjectionElem::Field(field, ty) => {
1968 write!(fmt, ".{:?}: {:?})", field.index(), ty)?;
1970 ProjectionElem::Index(ref index) => {
1971 write!(fmt, "[{:?}]", index)?;
1973 ProjectionElem::ConstantIndex { offset, min_length, from_end: false } => {
1974 write!(fmt, "[{:?} of {:?}]", offset, min_length)?;
1976 ProjectionElem::ConstantIndex { offset, min_length, from_end: true } => {
1977 write!(fmt, "[-{:?} of {:?}]", offset, min_length)?;
1979 ProjectionElem::Subslice { from, to, from_end: true } if to == 0 => {
1980 write!(fmt, "[{:?}:]", from)?;
1982 ProjectionElem::Subslice { from, to, from_end: true } if from == 0 => {
1983 write!(fmt, "[:-{:?}]", to)?;
1985 ProjectionElem::Subslice { from, to, from_end: true } => {
1986 write!(fmt, "[{:?}:-{:?}]", from, to)?;
1988 ProjectionElem::Subslice { from, to, from_end: false } => {
1989 write!(fmt, "[{:?}..{:?}]", from, to)?;
1998 ///////////////////////////////////////////////////////////////////////////
2001 rustc_index::newtype_index! {
2002 pub struct SourceScope {
2004 DEBUG_FORMAT = "scope[{}]",
2005 const OUTERMOST_SOURCE_SCOPE = 0,
2010 /// Finds the original HirId this MIR item came from.
2011 /// This is necessary after MIR optimizations, as otherwise we get a HirId
2012 /// from the function that was inlined instead of the function call site.
2013 pub fn lint_root<'tcx>(
2015 source_scopes: &IndexVec<SourceScope, SourceScopeData<'tcx>>,
2016 ) -> Option<HirId> {
2017 let mut data = &source_scopes[self];
2018 // FIXME(oli-obk): we should be able to just walk the `inlined_parent_scope`, but it
2019 // does not work as I thought it would. Needs more investigation and documentation.
2020 while data.inlined.is_some() {
2022 data = &source_scopes[data.parent_scope.unwrap()];
2025 match &data.local_data {
2026 ClearCrossCrate::Set(data) => Some(data.lint_root),
2027 ClearCrossCrate::Clear => None,
2032 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
2033 pub struct SourceScopeData<'tcx> {
2035 pub parent_scope: Option<SourceScope>,
2037 /// Whether this scope is the root of a scope tree of another body,
2038 /// inlined into this body by the MIR inliner.
2039 /// `ty::Instance` is the callee, and the `Span` is the call site.
2040 pub inlined: Option<(ty::Instance<'tcx>, Span)>,
2042 /// Nearest (transitive) parent scope (if any) which is inlined.
2043 /// This is an optimization over walking up `parent_scope`
2044 /// until a scope with `inlined: Some(...)` is found.
2045 pub inlined_parent_scope: Option<SourceScope>,
2047 /// Crate-local information for this source scope, that can't (and
2048 /// needn't) be tracked across crates.
2049 pub local_data: ClearCrossCrate<SourceScopeLocalData>,
2052 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable)]
2053 pub struct SourceScopeLocalData {
2054 /// An `HirId` with lint levels equivalent to this scope's lint levels.
2055 pub lint_root: hir::HirId,
2056 /// The unsafe block that contains this node.
2060 ///////////////////////////////////////////////////////////////////////////
2063 /// These are values that can appear inside an rvalue. They are intentionally
2064 /// limited to prevent rvalues from being nested in one another.
2065 #[derive(Clone, PartialEq, TyEncodable, TyDecodable, Hash, HashStable)]
2066 pub enum Operand<'tcx> {
2067 /// Copy: The value must be available for use afterwards.
2069 /// This implies that the type of the place must be `Copy`; this is true
2070 /// by construction during build, but also checked by the MIR type checker.
2073 /// Move: The value (including old borrows of it) will not be used again.
2075 /// Safe for values of all types (modulo future developments towards `?Move`).
2076 /// Correct usage patterns are enforced by the borrow checker for safe code.
2077 /// `Copy` may be converted to `Move` to enable "last-use" optimizations.
2080 /// Synthesizes a constant value.
2081 Constant(Box<Constant<'tcx>>),
2084 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
2085 static_assert_size!(Operand<'_>, 24);
2087 impl<'tcx> Debug for Operand<'tcx> {
2088 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2089 use self::Operand::*;
2091 Constant(ref a) => write!(fmt, "{:?}", a),
2092 Copy(ref place) => write!(fmt, "{:?}", place),
2093 Move(ref place) => write!(fmt, "move {:?}", place),
2098 impl<'tcx> Operand<'tcx> {
2099 /// Convenience helper to make a constant that refers to the fn
2100 /// with given `DefId` and substs. Since this is used to synthesize
2101 /// MIR, assumes `user_ty` is None.
2102 pub fn function_handle(
2105 substs: SubstsRef<'tcx>,
2108 let ty = tcx.type_of(def_id).subst(tcx, substs);
2109 Operand::Constant(Box::new(Constant {
2112 literal: ConstantKind::Ty(ty::Const::zero_sized(tcx, ty)),
2116 pub fn is_move(&self) -> bool {
2117 matches!(self, Operand::Move(..))
2120 /// Convenience helper to make a literal-like constant from a given scalar value.
2121 /// Since this is used to synthesize MIR, assumes `user_ty` is None.
2122 pub fn const_from_scalar(
2127 ) -> Operand<'tcx> {
2129 let param_env_and_ty = ty::ParamEnv::empty().and(ty);
2131 .layout_of(param_env_and_ty)
2132 .unwrap_or_else(|e| panic!("could not compute layout for {:?}: {:?}", ty, e))
2134 let scalar_size = match val {
2135 Scalar::Int(int) => int.size(),
2136 _ => panic!("Invalid scalar type {:?}", val),
2138 scalar_size == type_size
2140 Operand::Constant(Box::new(Constant {
2143 literal: ConstantKind::Val(ConstValue::Scalar(val), ty),
2147 pub fn to_copy(&self) -> Self {
2149 Operand::Copy(_) | Operand::Constant(_) => self.clone(),
2150 Operand::Move(place) => Operand::Copy(place),
2154 /// Returns the `Place` that is the target of this `Operand`, or `None` if this `Operand` is a
2156 pub fn place(&self) -> Option<Place<'tcx>> {
2158 Operand::Copy(place) | Operand::Move(place) => Some(*place),
2159 Operand::Constant(_) => None,
2163 /// Returns the `Constant` that is the target of this `Operand`, or `None` if this `Operand` is a
2165 pub fn constant(&self) -> Option<&Constant<'tcx>> {
2167 Operand::Constant(x) => Some(&**x),
2168 Operand::Copy(_) | Operand::Move(_) => None,
2173 ///////////////////////////////////////////////////////////////////////////
2176 #[derive(Clone, TyEncodable, TyDecodable, Hash, HashStable, PartialEq)]
2177 pub enum Rvalue<'tcx> {
2178 /// x (either a move or copy, depending on type of x)
2182 Repeat(Operand<'tcx>, &'tcx ty::Const<'tcx>),
2185 Ref(Region<'tcx>, BorrowKind, Place<'tcx>),
2187 /// Accessing a thread local static. This is inherently a runtime operation, even if llvm
2188 /// treats it as an access to a static. This `Rvalue` yields a reference to the thread local
2190 ThreadLocalRef(DefId),
2192 /// Create a raw pointer to the given place
2193 /// Can be generated by raw address of expressions (`&raw const x`),
2194 /// or when casting a reference to a raw pointer.
2195 AddressOf(Mutability, Place<'tcx>),
2197 /// length of a `[X]` or `[X;n]` value
2200 Cast(CastKind, Operand<'tcx>, Ty<'tcx>),
2202 BinaryOp(BinOp, Box<(Operand<'tcx>, Operand<'tcx>)>),
2203 CheckedBinaryOp(BinOp, Box<(Operand<'tcx>, Operand<'tcx>)>),
2205 NullaryOp(NullOp, Ty<'tcx>),
2206 UnaryOp(UnOp, Operand<'tcx>),
2208 /// Read the discriminant of an ADT.
2210 /// Undefined (i.e., no effort is made to make it defined, but there’s no reason why it cannot
2211 /// be defined to return, say, a 0) if ADT is not an enum.
2212 Discriminant(Place<'tcx>),
2214 /// Creates an aggregate value, like a tuple or struct. This is
2215 /// only needed because we want to distinguish `dest = Foo { x:
2216 /// ..., y: ... }` from `dest.x = ...; dest.y = ...;` in the case
2217 /// that `Foo` has a destructor. These rvalues can be optimized
2218 /// away after type-checking and before lowering.
2219 Aggregate(Box<AggregateKind<'tcx>>, Vec<Operand<'tcx>>),
2221 /// Transmutes a `*mut u8` into shallow-initialized `Box<T>`.
2223 /// This is different a normal transmute because dataflow analysis will treat the box
2224 /// as initialized but its content as uninitialized.
2225 ShallowInitBox(Operand<'tcx>, Ty<'tcx>),
2228 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
2229 static_assert_size!(Rvalue<'_>, 40);
2231 #[derive(Clone, Copy, Debug, PartialEq, Eq, TyEncodable, TyDecodable, Hash, HashStable)]
2234 Pointer(PointerCast),
2237 #[derive(Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, Hash, HashStable)]
2238 pub enum AggregateKind<'tcx> {
2239 /// The type is of the element
2243 /// The second field is the variant index. It's equal to 0 for struct
2244 /// and union expressions. The fourth field is
2245 /// active field number and is present only for union expressions
2246 /// -- e.g., for a union expression `SomeUnion { c: .. }`, the
2247 /// active field index would identity the field `c`
2248 Adt(DefId, VariantIdx, SubstsRef<'tcx>, Option<UserTypeAnnotationIndex>, Option<usize>),
2250 Closure(DefId, SubstsRef<'tcx>),
2251 Generator(DefId, SubstsRef<'tcx>, hir::Movability),
2254 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
2255 static_assert_size!(AggregateKind<'_>, 48);
2257 #[derive(Copy, Clone, Debug, PartialEq, PartialOrd, Eq, TyEncodable, TyDecodable, Hash, HashStable)]
2259 /// The `+` operator (addition)
2261 /// The `-` operator (subtraction)
2263 /// The `*` operator (multiplication)
2265 /// The `/` operator (division)
2267 /// Division by zero is UB.
2269 /// The `%` operator (modulus)
2271 /// Using zero as the modulus (second operand) is UB.
2273 /// The `^` operator (bitwise xor)
2275 /// The `&` operator (bitwise and)
2277 /// The `|` operator (bitwise or)
2279 /// The `<<` operator (shift left)
2281 /// The offset is truncated to the size of the first operand before shifting.
2283 /// The `>>` operator (shift right)
2285 /// The offset is truncated to the size of the first operand before shifting.
2287 /// The `==` operator (equality)
2289 /// The `<` operator (less than)
2291 /// The `<=` operator (less than or equal to)
2293 /// The `!=` operator (not equal to)
2295 /// The `>=` operator (greater than or equal to)
2297 /// The `>` operator (greater than)
2299 /// The `ptr.offset` operator
2304 pub fn is_checkable(self) -> bool {
2306 matches!(self, Add | Sub | Mul | Shl | Shr)
2310 #[derive(Copy, Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, Hash, HashStable)]
2312 /// Returns the size of a value of that type
2314 /// Returns the minimum alignment of a type
2318 #[derive(Copy, Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, Hash, HashStable)]
2320 /// The `!` operator for logical inversion
2322 /// The `-` operator for negation
2326 impl<'tcx> Debug for Rvalue<'tcx> {
2327 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2328 use self::Rvalue::*;
2331 Use(ref place) => write!(fmt, "{:?}", place),
2332 Repeat(ref a, ref b) => {
2333 write!(fmt, "[{:?}; ", a)?;
2334 pretty_print_const(b, fmt, false)?;
2337 Len(ref a) => write!(fmt, "Len({:?})", a),
2338 Cast(ref kind, ref place, ref ty) => {
2339 write!(fmt, "{:?} as {:?} ({:?})", place, ty, kind)
2341 BinaryOp(ref op, box (ref a, ref b)) => write!(fmt, "{:?}({:?}, {:?})", op, a, b),
2342 CheckedBinaryOp(ref op, box (ref a, ref b)) => {
2343 write!(fmt, "Checked{:?}({:?}, {:?})", op, a, b)
2345 UnaryOp(ref op, ref a) => write!(fmt, "{:?}({:?})", op, a),
2346 Discriminant(ref place) => write!(fmt, "discriminant({:?})", place),
2347 NullaryOp(ref op, ref t) => write!(fmt, "{:?}({:?})", op, t),
2348 ThreadLocalRef(did) => ty::tls::with(|tcx| {
2349 let muta = tcx.static_mutability(did).unwrap().prefix_str();
2350 write!(fmt, "&/*tls*/ {}{}", muta, tcx.def_path_str(did))
2352 Ref(region, borrow_kind, ref place) => {
2353 let kind_str = match borrow_kind {
2354 BorrowKind::Shared => "",
2355 BorrowKind::Shallow => "shallow ",
2356 BorrowKind::Mut { .. } | BorrowKind::Unique => "mut ",
2359 // When printing regions, add trailing space if necessary.
2360 let print_region = ty::tls::with(|tcx| {
2361 tcx.sess.verbose() || tcx.sess.opts.debugging_opts.identify_regions
2363 let region = if print_region {
2364 let mut region = region.to_string();
2365 if !region.is_empty() {
2370 // Do not even print 'static
2373 write!(fmt, "&{}{}{:?}", region, kind_str, place)
2376 AddressOf(mutability, ref place) => {
2377 let kind_str = match mutability {
2378 Mutability::Mut => "mut",
2379 Mutability::Not => "const",
2382 write!(fmt, "&raw {} {:?}", kind_str, place)
2385 Aggregate(ref kind, ref places) => {
2386 let fmt_tuple = |fmt: &mut Formatter<'_>, name: &str| {
2387 let mut tuple_fmt = fmt.debug_tuple(name);
2388 for place in places {
2389 tuple_fmt.field(place);
2395 AggregateKind::Array(_) => write!(fmt, "{:?}", places),
2397 AggregateKind::Tuple => {
2398 if places.is_empty() {
2405 AggregateKind::Adt(adt_did, variant, substs, _user_ty, _) => {
2406 ty::tls::with(|tcx| {
2407 let mut name = String::new();
2408 let variant_def = &tcx.adt_def(adt_did).variants[variant];
2409 let substs = tcx.lift(substs).expect("could not lift for printing");
2410 FmtPrinter::new(tcx, &mut name, Namespace::ValueNS)
2411 .print_def_path(variant_def.def_id, substs)?;
2413 match variant_def.ctor_kind {
2414 CtorKind::Const => fmt.write_str(&name),
2415 CtorKind::Fn => fmt_tuple(fmt, &name),
2416 CtorKind::Fictive => {
2417 let mut struct_fmt = fmt.debug_struct(&name);
2418 for (field, place) in iter::zip(&variant_def.fields, places) {
2419 struct_fmt.field(field.name.as_str(), place);
2427 AggregateKind::Closure(def_id, substs) => ty::tls::with(|tcx| {
2428 if let Some(def_id) = def_id.as_local() {
2429 let name = if tcx.sess.opts.debugging_opts.span_free_formats {
2430 let substs = tcx.lift(substs).unwrap();
2433 tcx.def_path_str_with_substs(def_id.to_def_id(), substs),
2436 let span = tcx.def_span(def_id);
2439 tcx.sess.source_map().span_to_diagnostic_string(span)
2442 let mut struct_fmt = fmt.debug_struct(&name);
2444 // FIXME(project-rfc-2229#48): This should be a list of capture names/places
2445 if let Some(upvars) = tcx.upvars_mentioned(def_id) {
2446 for (&var_id, place) in iter::zip(upvars.keys(), places) {
2447 let var_name = tcx.hir().name(var_id);
2448 struct_fmt.field(var_name.as_str(), place);
2454 write!(fmt, "[closure]")
2458 AggregateKind::Generator(def_id, _, _) => ty::tls::with(|tcx| {
2459 if let Some(def_id) = def_id.as_local() {
2460 let name = format!("[generator@{:?}]", tcx.def_span(def_id));
2461 let mut struct_fmt = fmt.debug_struct(&name);
2463 // FIXME(project-rfc-2229#48): This should be a list of capture names/places
2464 if let Some(upvars) = tcx.upvars_mentioned(def_id) {
2465 for (&var_id, place) in iter::zip(upvars.keys(), places) {
2466 let var_name = tcx.hir().name(var_id);
2467 struct_fmt.field(var_name.as_str(), place);
2473 write!(fmt, "[generator]")
2479 ShallowInitBox(ref place, ref ty) => {
2480 write!(fmt, "ShallowInitBox({:?}, {:?})", place, ty)
2486 ///////////////////////////////////////////////////////////////////////////
2489 /// Two constants are equal if they are the same constant. Note that
2490 /// this does not necessarily mean that they are `==` in Rust. In
2491 /// particular, one must be wary of `NaN`!
2493 #[derive(Clone, Copy, PartialEq, TyEncodable, TyDecodable, Hash, HashStable)]
2494 pub struct Constant<'tcx> {
2497 /// Optional user-given type: for something like
2498 /// `collect::<Vec<_>>`, this would be present and would
2499 /// indicate that `Vec<_>` was explicitly specified.
2501 /// Needed for NLL to impose user-given type constraints.
2502 pub user_ty: Option<UserTypeAnnotationIndex>,
2504 pub literal: ConstantKind<'tcx>,
2507 #[derive(Clone, Copy, PartialEq, Eq, TyEncodable, TyDecodable, Hash, HashStable, Debug)]
2509 pub enum ConstantKind<'tcx> {
2510 /// This constant came from the type system
2511 Ty(&'tcx ty::Const<'tcx>),
2512 /// This constant cannot go back into the type system, as it represents
2513 /// something the type system cannot handle (e.g. pointers).
2514 Val(interpret::ConstValue<'tcx>, Ty<'tcx>),
2517 impl<'tcx> Constant<'tcx> {
2518 pub fn check_static_ptr(&self, tcx: TyCtxt<'_>) -> Option<DefId> {
2519 match self.literal.const_for_ty()?.val.try_to_scalar() {
2520 Some(Scalar::Ptr(ptr, _size)) => match tcx.global_alloc(ptr.provenance) {
2521 GlobalAlloc::Static(def_id) => {
2522 assert!(!tcx.is_thread_local_static(def_id));
2531 pub fn ty(&self) -> Ty<'tcx> {
2536 impl<'tcx> From<&'tcx ty::Const<'tcx>> for ConstantKind<'tcx> {
2538 fn from(ct: &'tcx ty::Const<'tcx>) -> Self {
2543 impl<'tcx> ConstantKind<'tcx> {
2544 /// Returns `None` if the constant is not trivially safe for use in the type system.
2545 pub fn const_for_ty(&self) -> Option<&'tcx ty::Const<'tcx>> {
2547 ConstantKind::Ty(c) => Some(c),
2548 ConstantKind::Val(..) => None,
2552 pub fn ty(&self) -> Ty<'tcx> {
2554 ConstantKind::Ty(c) => c.ty,
2555 ConstantKind::Val(_, ty) => ty,
2560 pub fn try_to_value(self) -> Option<interpret::ConstValue<'tcx>> {
2562 ConstantKind::Ty(c) => c.val.try_to_value(),
2563 ConstantKind::Val(val, _) => Some(val),
2568 pub fn try_to_scalar(self) -> Option<Scalar> {
2569 self.try_to_value()?.try_to_scalar()
2573 pub fn try_to_scalar_int(self) -> Option<ScalarInt> {
2574 Some(self.try_to_value()?.try_to_scalar()?.assert_int())
2578 pub fn try_to_bits(self, size: Size) -> Option<u128> {
2579 self.try_to_scalar_int()?.to_bits(size).ok()
2583 pub fn try_to_bool(self) -> Option<bool> {
2584 self.try_to_scalar_int()?.try_into().ok()
2588 pub fn try_eval_bits(
2591 param_env: ty::ParamEnv<'tcx>,
2595 Self::Ty(ct) => ct.try_eval_bits(tcx, param_env, ty),
2596 Self::Val(val, t) => {
2599 tcx.layout_of(param_env.with_reveal_all_normalized(tcx).and(ty)).ok()?.size;
2600 val.try_to_bits(size)
2606 pub fn try_eval_bool(&self, tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>) -> Option<bool> {
2608 Self::Ty(ct) => ct.try_eval_bool(tcx, param_env),
2609 Self::Val(val, _) => val.try_to_bool(),
2614 pub fn try_eval_usize(&self, tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>) -> Option<u64> {
2616 Self::Ty(ct) => ct.try_eval_usize(tcx, param_env),
2617 Self::Val(val, _) => val.try_to_machine_usize(tcx),
2622 /// A collection of projections into user types.
2624 /// They are projections because a binding can occur a part of a
2625 /// parent pattern that has been ascribed a type.
2627 /// Its a collection because there can be multiple type ascriptions on
2628 /// the path from the root of the pattern down to the binding itself.
2633 /// struct S<'a>((i32, &'a str), String);
2634 /// let S((_, w): (i32, &'static str), _): S = ...;
2635 /// // ------ ^^^^^^^^^^^^^^^^^^^ (1)
2636 /// // --------------------------------- ^ (2)
2639 /// The highlights labelled `(1)` show the subpattern `(_, w)` being
2640 /// ascribed the type `(i32, &'static str)`.
2642 /// The highlights labelled `(2)` show the whole pattern being
2643 /// ascribed the type `S`.
2645 /// In this example, when we descend to `w`, we will have built up the
2646 /// following two projected types:
2648 /// * base: `S`, projection: `(base.0).1`
2649 /// * base: `(i32, &'static str)`, projection: `base.1`
2651 /// The first will lead to the constraint `w: &'1 str` (for some
2652 /// inferred region `'1`). The second will lead to the constraint `w:
2654 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
2655 pub struct UserTypeProjections {
2656 pub contents: Vec<(UserTypeProjection, Span)>,
2659 impl<'tcx> UserTypeProjections {
2660 pub fn none() -> Self {
2661 UserTypeProjections { contents: vec![] }
2664 pub fn is_empty(&self) -> bool {
2665 self.contents.is_empty()
2668 pub fn projections_and_spans(
2670 ) -> impl Iterator<Item = &(UserTypeProjection, Span)> + ExactSizeIterator {
2671 self.contents.iter()
2674 pub fn projections(&self) -> impl Iterator<Item = &UserTypeProjection> + ExactSizeIterator {
2675 self.contents.iter().map(|&(ref user_type, _span)| user_type)
2678 pub fn push_projection(mut self, user_ty: &UserTypeProjection, span: Span) -> Self {
2679 self.contents.push((user_ty.clone(), span));
2685 mut f: impl FnMut(UserTypeProjection) -> UserTypeProjection,
2687 self.contents = self.contents.into_iter().map(|(proj, span)| (f(proj), span)).collect();
2691 pub fn index(self) -> Self {
2692 self.map_projections(|pat_ty_proj| pat_ty_proj.index())
2695 pub fn subslice(self, from: u64, to: u64) -> Self {
2696 self.map_projections(|pat_ty_proj| pat_ty_proj.subslice(from, to))
2699 pub fn deref(self) -> Self {
2700 self.map_projections(|pat_ty_proj| pat_ty_proj.deref())
2703 pub fn leaf(self, field: Field) -> Self {
2704 self.map_projections(|pat_ty_proj| pat_ty_proj.leaf(field))
2707 pub fn variant(self, adt_def: &'tcx AdtDef, variant_index: VariantIdx, field: Field) -> Self {
2708 self.map_projections(|pat_ty_proj| pat_ty_proj.variant(adt_def, variant_index, field))
2712 /// Encodes the effect of a user-supplied type annotation on the
2713 /// subcomponents of a pattern. The effect is determined by applying the
2714 /// given list of proejctions to some underlying base type. Often,
2715 /// the projection element list `projs` is empty, in which case this
2716 /// directly encodes a type in `base`. But in the case of complex patterns with
2717 /// subpatterns and bindings, we want to apply only a *part* of the type to a variable,
2718 /// in which case the `projs` vector is used.
2722 /// * `let x: T = ...` -- here, the `projs` vector is empty.
2724 /// * `let (x, _): T = ...` -- here, the `projs` vector would contain
2725 /// `field[0]` (aka `.0`), indicating that the type of `s` is
2726 /// determined by finding the type of the `.0` field from `T`.
2727 #[derive(Clone, Debug, TyEncodable, TyDecodable, Hash, HashStable, PartialEq)]
2728 pub struct UserTypeProjection {
2729 pub base: UserTypeAnnotationIndex,
2730 pub projs: Vec<ProjectionKind>,
2733 impl Copy for ProjectionKind {}
2735 impl UserTypeProjection {
2736 pub(crate) fn index(mut self) -> Self {
2737 self.projs.push(ProjectionElem::Index(()));
2741 pub(crate) fn subslice(mut self, from: u64, to: u64) -> Self {
2742 self.projs.push(ProjectionElem::Subslice { from, to, from_end: true });
2746 pub(crate) fn deref(mut self) -> Self {
2747 self.projs.push(ProjectionElem::Deref);
2751 pub(crate) fn leaf(mut self, field: Field) -> Self {
2752 self.projs.push(ProjectionElem::Field(field, ()));
2756 pub(crate) fn variant(
2759 variant_index: VariantIdx,
2762 self.projs.push(ProjectionElem::Downcast(
2763 Some(adt_def.variants[variant_index].name),
2766 self.projs.push(ProjectionElem::Field(field, ()));
2771 TrivialTypeFoldableAndLiftImpls! { ProjectionKind, }
2773 impl<'tcx> TypeFoldable<'tcx> for UserTypeProjection {
2774 fn try_super_fold_with<F: FallibleTypeFolder<'tcx>>(
2777 ) -> Result<Self, F::Error> {
2778 Ok(UserTypeProjection {
2779 base: self.base.try_fold_with(folder)?,
2780 projs: self.projs.try_fold_with(folder)?,
2784 fn super_visit_with<Vs: TypeVisitor<'tcx>>(
2787 ) -> ControlFlow<Vs::BreakTy> {
2788 self.base.visit_with(visitor)
2789 // Note: there's nothing in `self.proj` to visit.
2793 rustc_index::newtype_index! {
2794 pub struct Promoted {
2796 DEBUG_FORMAT = "promoted[{}]"
2800 impl<'tcx> Debug for Constant<'tcx> {
2801 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2802 write!(fmt, "{}", self)
2806 impl<'tcx> Display for Constant<'tcx> {
2807 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2808 match self.ty().kind() {
2810 _ => write!(fmt, "const ")?,
2812 Display::fmt(&self.literal, fmt)
2816 impl<'tcx> Display for ConstantKind<'tcx> {
2817 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2819 ConstantKind::Ty(c) => pretty_print_const(c, fmt, true),
2820 ConstantKind::Val(val, ty) => pretty_print_const_value(val, ty, fmt, true),
2825 fn pretty_print_const<'tcx>(
2826 c: &ty::Const<'tcx>,
2827 fmt: &mut Formatter<'_>,
2830 use crate::ty::print::PrettyPrinter;
2831 ty::tls::with(|tcx| {
2832 let literal = tcx.lift(c).unwrap();
2833 let mut cx = FmtPrinter::new(tcx, fmt, Namespace::ValueNS);
2834 cx.print_alloc_ids = true;
2835 cx.pretty_print_const(literal, print_types)?;
2840 fn pretty_print_const_value<'tcx>(
2841 val: interpret::ConstValue<'tcx>,
2843 fmt: &mut Formatter<'_>,
2846 use crate::ty::print::PrettyPrinter;
2847 ty::tls::with(|tcx| {
2848 let val = tcx.lift(val).unwrap();
2849 let ty = tcx.lift(ty).unwrap();
2850 let mut cx = FmtPrinter::new(tcx, fmt, Namespace::ValueNS);
2851 cx.print_alloc_ids = true;
2852 cx.pretty_print_const_value(val, ty, print_types)?;
2857 impl<'tcx> graph::DirectedGraph for Body<'tcx> {
2858 type Node = BasicBlock;
2861 impl<'tcx> graph::WithNumNodes for Body<'tcx> {
2863 fn num_nodes(&self) -> usize {
2864 self.basic_blocks.len()
2868 impl<'tcx> graph::WithStartNode for Body<'tcx> {
2870 fn start_node(&self) -> Self::Node {
2875 impl<'tcx> graph::WithSuccessors for Body<'tcx> {
2877 fn successors(&self, node: Self::Node) -> <Self as GraphSuccessors<'_>>::Iter {
2878 self.basic_blocks[node].terminator().successors().cloned()
2882 impl<'a, 'b> graph::GraphSuccessors<'b> for Body<'a> {
2883 type Item = BasicBlock;
2884 type Iter = iter::Cloned<Successors<'b>>;
2887 impl<'tcx, 'graph> graph::GraphPredecessors<'graph> for Body<'tcx> {
2888 type Item = BasicBlock;
2889 type Iter = std::iter::Copied<std::slice::Iter<'graph, BasicBlock>>;
2892 impl<'tcx> graph::WithPredecessors for Body<'tcx> {
2894 fn predecessors(&self, node: Self::Node) -> <Self as graph::GraphPredecessors<'_>>::Iter {
2895 self.predecessors()[node].iter().copied()
2899 /// `Location` represents the position of the start of the statement; or, if
2900 /// `statement_index` equals the number of statements, then the start of the
2902 #[derive(Copy, Clone, PartialEq, Eq, Hash, Ord, PartialOrd, HashStable)]
2903 pub struct Location {
2904 /// The block that the location is within.
2905 pub block: BasicBlock,
2907 pub statement_index: usize,
2910 impl fmt::Debug for Location {
2911 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2912 write!(fmt, "{:?}[{}]", self.block, self.statement_index)
2917 pub const START: Location = Location { block: START_BLOCK, statement_index: 0 };
2919 /// Returns the location immediately after this one within the enclosing block.
2921 /// Note that if this location represents a terminator, then the
2922 /// resulting location would be out of bounds and invalid.
2923 pub fn successor_within_block(&self) -> Location {
2924 Location { block: self.block, statement_index: self.statement_index + 1 }
2927 /// Returns `true` if `other` is earlier in the control flow graph than `self`.
2928 pub fn is_predecessor_of<'tcx>(&self, other: Location, body: &Body<'tcx>) -> bool {
2929 // If we are in the same block as the other location and are an earlier statement
2930 // then we are a predecessor of `other`.
2931 if self.block == other.block && self.statement_index < other.statement_index {
2935 let predecessors = body.predecessors();
2937 // If we're in another block, then we want to check that block is a predecessor of `other`.
2938 let mut queue: Vec<BasicBlock> = predecessors[other.block].to_vec();
2939 let mut visited = FxHashSet::default();
2941 while let Some(block) = queue.pop() {
2942 // If we haven't visited this block before, then make sure we visit its predecessors.
2943 if visited.insert(block) {
2944 queue.extend(predecessors[block].iter().cloned());
2949 // If we found the block that `self` is in, then we are a predecessor of `other` (since
2950 // we found that block by looking at the predecessors of `other`).
2951 if self.block == block {
2959 pub fn dominates(&self, other: Location, dominators: &Dominators<BasicBlock>) -> bool {
2960 if self.block == other.block {
2961 self.statement_index <= other.statement_index
2963 dominators.is_dominated_by(other.block, self.block)