1 //! MIR datatypes and passes. See the [rustc dev guide] for more info.
3 //! [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/mir/index.html
5 use crate::mir::interpret::{
6 AllocRange, ConstAllocation, ConstValue, ErrorHandled, GlobalAlloc, LitToConstInput, Scalar,
8 use crate::mir::visit::MirVisitable;
9 use crate::ty::codec::{TyDecoder, TyEncoder};
10 use crate::ty::fold::{FallibleTypeFolder, TypeFoldable};
11 use crate::ty::print::{FmtPrinter, Printer};
12 use crate::ty::visit::{TypeVisitable, TypeVisitor};
13 use crate::ty::{self, DefIdTree, List, Ty, TyCtxt};
14 use crate::ty::{AdtDef, InstanceDef, ScalarInt, UserTypeAnnotationIndex};
15 use crate::ty::{GenericArg, InternalSubsts, SubstsRef};
17 use rustc_data_structures::captures::Captures;
18 use rustc_errors::ErrorGuaranteed;
19 use rustc_hir::def::{CtorKind, Namespace};
20 use rustc_hir::def_id::{DefId, LocalDefId, CRATE_DEF_ID};
21 use rustc_hir::{self, GeneratorKind, ImplicitSelfKind};
22 use rustc_hir::{self as hir, HirId};
23 use rustc_session::Session;
24 use rustc_target::abi::{Size, VariantIdx};
26 use polonius_engine::Atom;
27 pub use rustc_ast::Mutability;
28 use rustc_data_structures::fx::FxHashSet;
29 use rustc_data_structures::graph::dominators::Dominators;
30 use rustc_index::bit_set::BitMatrix;
31 use rustc_index::vec::{Idx, IndexVec};
32 use rustc_serialize::{Decodable, Encodable};
33 use rustc_span::symbol::Symbol;
34 use rustc_span::{Span, DUMMY_SP};
39 use std::convert::TryInto;
40 use std::fmt::{self, Debug, Display, Formatter, Write};
41 use std::ops::{ControlFlow, Index, IndexMut};
44 pub use self::query::*;
45 pub use basic_blocks::BasicBlocks;
50 pub mod generic_graphviz;
51 mod graph_cyclic_cache;
65 pub use terminator::*;
72 pub use self::generic_graph::graphviz_safe_def_name;
73 pub use self::graphviz::write_mir_graphviz;
74 pub use self::pretty::{
75 create_dump_file, display_allocation, dump_enabled, dump_mir, write_mir_pretty, PassWhere,
79 pub type LocalDecls<'tcx> = IndexVec<Local, LocalDecl<'tcx>>;
81 pub trait HasLocalDecls<'tcx> {
82 fn local_decls(&self) -> &LocalDecls<'tcx>;
85 impl<'tcx> HasLocalDecls<'tcx> for LocalDecls<'tcx> {
87 fn local_decls(&self) -> &LocalDecls<'tcx> {
92 impl<'tcx> HasLocalDecls<'tcx> for Body<'tcx> {
94 fn local_decls(&self) -> &LocalDecls<'tcx> {
99 /// A streamlined trait that you can implement to create a pass; the
100 /// pass will be named after the type, and it will consist of a main
101 /// loop that goes over each available MIR and applies `run_pass`.
102 pub trait MirPass<'tcx> {
103 fn name(&self) -> &str {
104 let name = std::any::type_name::<Self>();
105 if let Some((_, tail)) = name.rsplit_once(':') { tail } else { name }
108 /// Returns `true` if this pass is enabled with the current combination of compiler flags.
109 fn is_enabled(&self, _sess: &Session) -> bool {
113 fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>);
115 fn is_mir_dump_enabled(&self) -> bool {
121 /// Gets the index of the current MirPhase within the set of all `MirPhase`s.
123 /// FIXME(JakobDegen): Return a `(usize, usize)` instead.
124 pub fn phase_index(&self) -> usize {
125 const BUILT_PHASE_COUNT: usize = 1;
126 const ANALYSIS_PHASE_COUNT: usize = 2;
128 MirPhase::Built => 1,
129 MirPhase::Analysis(analysis_phase) => {
130 1 + BUILT_PHASE_COUNT + (*analysis_phase as usize)
132 MirPhase::Runtime(runtime_phase) => {
133 1 + BUILT_PHASE_COUNT + ANALYSIS_PHASE_COUNT + (*runtime_phase as usize)
138 /// Parses an `MirPhase` from a pair of strings. Panics if this isn't possible for any reason.
139 pub fn parse(dialect: String, phase: Option<String>) -> Self {
140 match &*dialect.to_ascii_lowercase() {
142 assert!(phase.is_none(), "Cannot specify a phase for `Built` MIR");
145 "analysis" => Self::Analysis(AnalysisPhase::parse(phase)),
146 "runtime" => Self::Runtime(RuntimePhase::parse(phase)),
147 _ => panic!("Unknown MIR dialect {}", dialect),
153 pub fn parse(phase: Option<String>) -> Self {
154 let Some(phase) = phase else {
155 return Self::Initial;
158 match &*phase.to_ascii_lowercase() {
159 "initial" => Self::Initial,
160 "post_cleanup" | "post-cleanup" | "postcleanup" => Self::PostCleanup,
161 _ => panic!("Unknown analysis phase {}", phase),
167 pub fn parse(phase: Option<String>) -> Self {
168 let Some(phase) = phase else {
169 return Self::Initial;
172 match &*phase.to_ascii_lowercase() {
173 "initial" => Self::Initial,
174 "post_cleanup" | "post-cleanup" | "postcleanup" => Self::PostCleanup,
175 "optimized" => Self::Optimized,
176 _ => panic!("Unknown runtime phase {}", phase),
181 impl Display for MirPhase {
182 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
183 f.write_str(self.name())
187 /// Where a specific `mir::Body` comes from.
188 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
189 #[derive(HashStable, TyEncodable, TyDecodable, TypeFoldable, TypeVisitable)]
190 pub struct MirSource<'tcx> {
191 pub instance: InstanceDef<'tcx>,
193 /// If `Some`, this is a promoted rvalue within the parent function.
194 pub promoted: Option<Promoted>,
197 impl<'tcx> MirSource<'tcx> {
198 pub fn item(def_id: DefId) -> Self {
200 instance: InstanceDef::Item(ty::WithOptConstParam::unknown(def_id)),
205 pub fn from_instance(instance: InstanceDef<'tcx>) -> Self {
206 MirSource { instance, promoted: None }
209 pub fn with_opt_param(self) -> ty::WithOptConstParam<DefId> {
210 self.instance.with_opt_param()
214 pub fn def_id(&self) -> DefId {
215 self.instance.def_id()
219 #[derive(Clone, TyEncodable, TyDecodable, Debug, HashStable, TypeFoldable, TypeVisitable)]
220 pub struct GeneratorInfo<'tcx> {
221 /// The yield type of the function, if it is a generator.
222 pub yield_ty: Option<Ty<'tcx>>,
224 /// Generator drop glue.
225 pub generator_drop: Option<Body<'tcx>>,
227 /// The layout of a generator. Produced by the state transformation.
228 pub generator_layout: Option<GeneratorLayout<'tcx>>,
230 /// If this is a generator then record the type of source expression that caused this generator
232 pub generator_kind: GeneratorKind,
235 /// The lowered representation of a single function.
236 #[derive(Clone, TyEncodable, TyDecodable, Debug, HashStable, TypeFoldable, TypeVisitable)]
237 pub struct Body<'tcx> {
238 /// A list of basic blocks. References to basic block use a newtyped index type [`BasicBlock`]
239 /// that indexes into this vector.
240 pub basic_blocks: BasicBlocks<'tcx>,
242 /// Records how far through the "desugaring and optimization" process this particular
243 /// MIR has traversed. This is particularly useful when inlining, since in that context
244 /// we instantiate the promoted constants and add them to our promoted vector -- but those
245 /// promoted items have already been optimized, whereas ours have not. This field allows
246 /// us to see the difference and forego optimization on the inlined promoted items.
249 /// How many passses we have executed since starting the current phase. Used for debug output.
250 pub pass_count: usize,
252 pub source: MirSource<'tcx>,
254 /// A list of source scopes; these are referenced by statements
255 /// and used for debuginfo. Indexed by a `SourceScope`.
256 pub source_scopes: IndexVec<SourceScope, SourceScopeData<'tcx>>,
258 pub generator: Option<Box<GeneratorInfo<'tcx>>>,
260 /// Declarations of locals.
262 /// The first local is the return value pointer, followed by `arg_count`
263 /// locals for the function arguments, followed by any user-declared
264 /// variables and temporaries.
265 pub local_decls: LocalDecls<'tcx>,
267 /// User type annotations.
268 pub user_type_annotations: ty::CanonicalUserTypeAnnotations<'tcx>,
270 /// The number of arguments this function takes.
272 /// Starting at local 1, `arg_count` locals will be provided by the caller
273 /// and can be assumed to be initialized.
275 /// If this MIR was built for a constant, this will be 0.
276 pub arg_count: usize,
278 /// Mark an argument local (which must be a tuple) as getting passed as
279 /// its individual components at the LLVM level.
281 /// This is used for the "rust-call" ABI.
282 pub spread_arg: Option<Local>,
284 /// Debug information pertaining to user variables, including captures.
285 pub var_debug_info: Vec<VarDebugInfo<'tcx>>,
287 /// A span representing this MIR, for error reporting.
290 /// Constants that are required to evaluate successfully for this MIR to be well-formed.
291 /// We hold in this field all the constants we are not able to evaluate yet.
292 pub required_consts: Vec<Constant<'tcx>>,
294 /// Does this body use generic parameters. This is used for the `ConstEvaluatable` check.
296 /// Note that this does not actually mean that this body is not computable right now.
297 /// The repeat count in the following example is polymorphic, but can still be evaluated
298 /// without knowing anything about the type parameter `T`.
302 /// let _ = [0; std::mem::size_of::<*mut T>()];
306 /// **WARNING**: Do not change this flags after the MIR was originally created, even if an optimization
307 /// removed the last mention of all generic params. We do not want to rely on optimizations and
308 /// potentially allow things like `[u8; std::mem::size_of::<T>() * 0]` due to this.
309 pub is_polymorphic: bool,
311 /// The phase at which this MIR should be "injected" into the compilation process.
313 /// Everything that comes before this `MirPhase` should be skipped.
315 /// This is only `Some` if the function that this body comes from was annotated with `rustc_custom_mir`.
316 pub injection_phase: Option<MirPhase>,
318 pub tainted_by_errors: Option<ErrorGuaranteed>,
321 impl<'tcx> Body<'tcx> {
323 source: MirSource<'tcx>,
324 basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
325 source_scopes: IndexVec<SourceScope, SourceScopeData<'tcx>>,
326 local_decls: LocalDecls<'tcx>,
327 user_type_annotations: ty::CanonicalUserTypeAnnotations<'tcx>,
329 var_debug_info: Vec<VarDebugInfo<'tcx>>,
331 generator_kind: Option<GeneratorKind>,
332 tainted_by_errors: Option<ErrorGuaranteed>,
334 // We need `arg_count` locals, and one for the return place.
336 local_decls.len() > arg_count,
337 "expected at least {} locals, got {}",
342 let mut body = Body {
343 phase: MirPhase::Built,
346 basic_blocks: BasicBlocks::new(basic_blocks),
348 generator: generator_kind.map(|generator_kind| {
349 Box::new(GeneratorInfo {
351 generator_drop: None,
352 generator_layout: None,
357 user_type_annotations,
362 required_consts: Vec::new(),
363 is_polymorphic: false,
364 injection_phase: None,
367 body.is_polymorphic = body.has_non_region_param();
371 /// Returns a partially initialized MIR body containing only a list of basic blocks.
373 /// The returned MIR contains no `LocalDecl`s (even for the return place) or source scopes. It
374 /// is only useful for testing but cannot be `#[cfg(test)]` because it is used in a different
376 pub fn new_cfg_only(basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>) -> Self {
377 let mut body = Body {
378 phase: MirPhase::Built,
380 source: MirSource::item(CRATE_DEF_ID.to_def_id()),
381 basic_blocks: BasicBlocks::new(basic_blocks),
382 source_scopes: IndexVec::new(),
384 local_decls: IndexVec::new(),
385 user_type_annotations: IndexVec::new(),
389 required_consts: Vec::new(),
390 var_debug_info: Vec::new(),
391 is_polymorphic: false,
392 injection_phase: None,
393 tainted_by_errors: None,
395 body.is_polymorphic = body.has_non_region_param();
400 pub fn basic_blocks_mut(&mut self) -> &mut IndexVec<BasicBlock, BasicBlockData<'tcx>> {
401 self.basic_blocks.as_mut()
405 pub fn local_kind(&self, local: Local) -> LocalKind {
406 let index = local.as_usize();
409 self.local_decls[local].mutability == Mutability::Mut,
410 "return place should be mutable"
413 LocalKind::ReturnPointer
414 } else if index < self.arg_count + 1 {
416 } else if self.local_decls[local].is_user_variable() {
423 /// Returns an iterator over all user-declared mutable locals.
425 pub fn mut_vars_iter<'a>(&'a self) -> impl Iterator<Item = Local> + Captures<'tcx> + 'a {
426 (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
427 let local = Local::new(index);
428 let decl = &self.local_decls[local];
429 if decl.is_user_variable() && decl.mutability == Mutability::Mut {
437 /// Returns an iterator over all user-declared mutable arguments and locals.
439 pub fn mut_vars_and_args_iter<'a>(
441 ) -> impl Iterator<Item = Local> + Captures<'tcx> + 'a {
442 (1..self.local_decls.len()).filter_map(move |index| {
443 let local = Local::new(index);
444 let decl = &self.local_decls[local];
445 if (decl.is_user_variable() || index < self.arg_count + 1)
446 && decl.mutability == Mutability::Mut
455 /// Returns an iterator over all function arguments.
457 pub fn args_iter(&self) -> impl Iterator<Item = Local> + ExactSizeIterator {
458 (1..self.arg_count + 1).map(Local::new)
461 /// Returns an iterator over all user-defined variables and compiler-generated temporaries (all
462 /// locals that are neither arguments nor the return place).
464 pub fn vars_and_temps_iter(
466 ) -> impl DoubleEndedIterator<Item = Local> + ExactSizeIterator {
467 (self.arg_count + 1..self.local_decls.len()).map(Local::new)
471 pub fn drain_vars_and_temps<'a>(&'a mut self) -> impl Iterator<Item = LocalDecl<'tcx>> + 'a {
472 self.local_decls.drain(self.arg_count + 1..)
475 /// Returns the source info associated with `location`.
476 pub fn source_info(&self, location: Location) -> &SourceInfo {
477 let block = &self[location.block];
478 let stmts = &block.statements;
479 let idx = location.statement_index;
480 if idx < stmts.len() {
481 &stmts[idx].source_info
483 assert_eq!(idx, stmts.len());
484 &block.terminator().source_info
488 /// Returns the return type; it always return first element from `local_decls` array.
490 pub fn return_ty(&self) -> Ty<'tcx> {
491 self.local_decls[RETURN_PLACE].ty
494 /// Returns the return type; it always return first element from `local_decls` array.
496 pub fn bound_return_ty(&self) -> ty::EarlyBinder<Ty<'tcx>> {
497 ty::EarlyBinder(self.local_decls[RETURN_PLACE].ty)
500 /// Gets the location of the terminator for the given block.
502 pub fn terminator_loc(&self, bb: BasicBlock) -> Location {
503 Location { block: bb, statement_index: self[bb].statements.len() }
506 pub fn stmt_at(&self, location: Location) -> Either<&Statement<'tcx>, &Terminator<'tcx>> {
507 let Location { block, statement_index } = location;
508 let block_data = &self.basic_blocks[block];
511 .get(statement_index)
513 .unwrap_or_else(|| Either::Right(block_data.terminator()))
517 pub fn yield_ty(&self) -> Option<Ty<'tcx>> {
518 self.generator.as_ref().and_then(|generator| generator.yield_ty)
522 pub fn generator_layout(&self) -> Option<&GeneratorLayout<'tcx>> {
523 self.generator.as_ref().and_then(|generator| generator.generator_layout.as_ref())
527 pub fn generator_drop(&self) -> Option<&Body<'tcx>> {
528 self.generator.as_ref().and_then(|generator| generator.generator_drop.as_ref())
532 pub fn generator_kind(&self) -> Option<GeneratorKind> {
533 self.generator.as_ref().map(|generator| generator.generator_kind)
537 pub fn should_skip(&self) -> bool {
538 let Some(injection_phase) = self.injection_phase else {
541 injection_phase > self.phase
545 #[derive(Copy, Clone, PartialEq, Eq, Debug, TyEncodable, TyDecodable, HashStable)]
548 /// Unsafe because of compiler-generated unsafe code, like `await` desugaring
550 /// Unsafe because of an unsafe fn
552 /// Unsafe because of an `unsafe` block
553 ExplicitUnsafe(hir::HirId),
556 impl<'tcx> Index<BasicBlock> for Body<'tcx> {
557 type Output = BasicBlockData<'tcx>;
560 fn index(&self, index: BasicBlock) -> &BasicBlockData<'tcx> {
561 &self.basic_blocks[index]
565 impl<'tcx> IndexMut<BasicBlock> for Body<'tcx> {
567 fn index_mut(&mut self, index: BasicBlock) -> &mut BasicBlockData<'tcx> {
568 &mut self.basic_blocks.as_mut()[index]
572 #[derive(Copy, Clone, Debug, HashStable, TypeFoldable, TypeVisitable)]
573 pub enum ClearCrossCrate<T> {
578 impl<T> ClearCrossCrate<T> {
579 pub fn as_ref(&self) -> ClearCrossCrate<&T> {
581 ClearCrossCrate::Clear => ClearCrossCrate::Clear,
582 ClearCrossCrate::Set(v) => ClearCrossCrate::Set(v),
586 pub fn assert_crate_local(self) -> T {
588 ClearCrossCrate::Clear => bug!("unwrapping cross-crate data"),
589 ClearCrossCrate::Set(v) => v,
594 const TAG_CLEAR_CROSS_CRATE_CLEAR: u8 = 0;
595 const TAG_CLEAR_CROSS_CRATE_SET: u8 = 1;
597 impl<E: TyEncoder, T: Encodable<E>> Encodable<E> for ClearCrossCrate<T> {
599 fn encode(&self, e: &mut E) {
600 if E::CLEAR_CROSS_CRATE {
605 ClearCrossCrate::Clear => TAG_CLEAR_CROSS_CRATE_CLEAR.encode(e),
606 ClearCrossCrate::Set(ref val) => {
607 TAG_CLEAR_CROSS_CRATE_SET.encode(e);
613 impl<D: TyDecoder, T: Decodable<D>> Decodable<D> for ClearCrossCrate<T> {
615 fn decode(d: &mut D) -> ClearCrossCrate<T> {
616 if D::CLEAR_CROSS_CRATE {
617 return ClearCrossCrate::Clear;
620 let discr = u8::decode(d);
623 TAG_CLEAR_CROSS_CRATE_CLEAR => ClearCrossCrate::Clear,
624 TAG_CLEAR_CROSS_CRATE_SET => {
625 let val = T::decode(d);
626 ClearCrossCrate::Set(val)
628 tag => panic!("Invalid tag for ClearCrossCrate: {:?}", tag),
633 /// Grouped information about the source code origin of a MIR entity.
634 /// Intended to be inspected by diagnostics and debuginfo.
635 /// Most passes can work with it as a whole, within a single function.
636 // The unofficial Cranelift backend, at least as of #65828, needs `SourceInfo` to implement `Eq` and
637 // `Hash`. Please ping @bjorn3 if removing them.
638 #[derive(Copy, Clone, Debug, Eq, PartialEq, TyEncodable, TyDecodable, Hash, HashStable)]
639 pub struct SourceInfo {
640 /// The source span for the AST pertaining to this MIR entity.
643 /// The source scope, keeping track of which bindings can be
644 /// seen by debuginfo, active lint levels, `unsafe {...}`, etc.
645 pub scope: SourceScope,
650 pub fn outermost(span: Span) -> Self {
651 SourceInfo { span, scope: OUTERMOST_SOURCE_SCOPE }
655 ///////////////////////////////////////////////////////////////////////////
656 // Variables and temps
658 rustc_index::newtype_index! {
661 DEBUG_FORMAT = "_{}",
662 const RETURN_PLACE = 0,
666 impl Atom for Local {
667 fn index(self) -> usize {
672 /// Classifies locals into categories. See `Body::local_kind`.
673 #[derive(Clone, Copy, PartialEq, Eq, Debug, HashStable)]
675 /// User-declared variable binding.
677 /// Compiler-introduced temporary.
679 /// Function argument.
681 /// Location of function's return value.
685 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable)]
686 pub struct VarBindingForm<'tcx> {
687 /// Is variable bound via `x`, `mut x`, `ref x`, or `ref mut x`?
688 pub binding_mode: ty::BindingMode,
689 /// If an explicit type was provided for this variable binding,
690 /// this holds the source Span of that type.
692 /// NOTE: if you want to change this to a `HirId`, be wary that
693 /// doing so breaks incremental compilation (as of this writing),
694 /// while a `Span` does not cause our tests to fail.
695 pub opt_ty_info: Option<Span>,
696 /// Place of the RHS of the =, or the subject of the `match` where this
697 /// variable is initialized. None in the case of `let PATTERN;`.
698 /// Some((None, ..)) in the case of and `let [mut] x = ...` because
699 /// (a) the right-hand side isn't evaluated as a place expression.
700 /// (b) it gives a way to separate this case from the remaining cases
702 pub opt_match_place: Option<(Option<Place<'tcx>>, Span)>,
703 /// The span of the pattern in which this variable was bound.
707 #[derive(Clone, Debug, TyEncodable, TyDecodable)]
708 pub enum BindingForm<'tcx> {
709 /// This is a binding for a non-`self` binding, or a `self` that has an explicit type.
710 Var(VarBindingForm<'tcx>),
711 /// Binding for a `self`/`&self`/`&mut self` binding where the type is implicit.
712 ImplicitSelf(ImplicitSelfKind),
713 /// Reference used in a guard expression to ensure immutability.
717 TrivialTypeTraversalAndLiftImpls! { BindingForm<'tcx>, }
719 mod binding_form_impl {
720 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
721 use rustc_query_system::ich::StableHashingContext;
723 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for super::BindingForm<'tcx> {
724 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
725 use super::BindingForm::*;
726 std::mem::discriminant(self).hash_stable(hcx, hasher);
729 Var(binding) => binding.hash_stable(hcx, hasher),
730 ImplicitSelf(kind) => kind.hash_stable(hcx, hasher),
737 /// `BlockTailInfo` is attached to the `LocalDecl` for temporaries
738 /// created during evaluation of expressions in a block tail
739 /// expression; that is, a block like `{ STMT_1; STMT_2; EXPR }`.
741 /// It is used to improve diagnostics when such temporaries are
742 /// involved in borrow_check errors, e.g., explanations of where the
743 /// temporaries come from, when their destructors are run, and/or how
744 /// one might revise the code to satisfy the borrow checker's rules.
745 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable)]
746 pub struct BlockTailInfo {
747 /// If `true`, then the value resulting from evaluating this tail
748 /// expression is ignored by the block's expression context.
750 /// Examples include `{ ...; tail };` and `let _ = { ...; tail };`
751 /// but not e.g., `let _x = { ...; tail };`
752 pub tail_result_is_ignored: bool,
754 /// `Span` of the tail expression.
760 /// This can be a binding declared by the user, a temporary inserted by the compiler, a function
761 /// argument, or the return place.
762 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable, TypeVisitable)]
763 pub struct LocalDecl<'tcx> {
764 /// Whether this is a mutable binding (i.e., `let x` or `let mut x`).
766 /// Temporaries and the return place are always mutable.
767 pub mutability: Mutability,
769 // FIXME(matthewjasper) Don't store in this in `Body`
770 pub local_info: Option<Box<LocalInfo<'tcx>>>,
772 /// `true` if this is an internal local.
774 /// These locals are not based on types in the source code and are only used
775 /// for a few desugarings at the moment.
777 /// The generator transformation will sanity check the locals which are live
778 /// across a suspension point against the type components of the generator
779 /// which type checking knows are live across a suspension point. We need to
780 /// flag drop flags to avoid triggering this check as they are introduced
781 /// outside of type inference.
783 /// This should be sound because the drop flags are fully algebraic, and
784 /// therefore don't affect the auto-trait or outlives properties of the
788 /// If this local is a temporary and `is_block_tail` is `Some`,
789 /// then it is a temporary created for evaluation of some
790 /// subexpression of some block's tail expression (with no
791 /// intervening statement context).
792 // FIXME(matthewjasper) Don't store in this in `Body`
793 pub is_block_tail: Option<BlockTailInfo>,
795 /// The type of this local.
798 /// If the user manually ascribed a type to this variable,
799 /// e.g., via `let x: T`, then we carry that type here. The MIR
800 /// borrow checker needs this information since it can affect
801 /// region inference.
802 // FIXME(matthewjasper) Don't store in this in `Body`
803 pub user_ty: Option<Box<UserTypeProjections>>,
805 /// The *syntactic* (i.e., not visibility) source scope the local is defined
806 /// in. If the local was defined in a let-statement, this
807 /// is *within* the let-statement, rather than outside
810 /// This is needed because the visibility source scope of locals within
811 /// a let-statement is weird.
813 /// The reason is that we want the local to be *within* the let-statement
814 /// for lint purposes, but we want the local to be *after* the let-statement
815 /// for names-in-scope purposes.
817 /// That's it, if we have a let-statement like the one in this
821 /// fn foo(x: &str) {
822 /// #[allow(unused_mut)]
823 /// let mut x: u32 = { // <- one unused mut
824 /// let mut y: u32 = x.parse().unwrap();
831 /// Then, from a lint point of view, the declaration of `x: u32`
832 /// (and `y: u32`) are within the `#[allow(unused_mut)]` scope - the
833 /// lint scopes are the same as the AST/HIR nesting.
835 /// However, from a name lookup point of view, the scopes look more like
836 /// as if the let-statements were `match` expressions:
839 /// fn foo(x: &str) {
841 /// match x.parse::<u32>().unwrap() {
850 /// We care about the name-lookup scopes for debuginfo - if the
851 /// debuginfo instruction pointer is at the call to `x.parse()`, we
852 /// want `x` to refer to `x: &str`, but if it is at the call to
853 /// `drop(x)`, we want it to refer to `x: u32`.
855 /// To allow both uses to work, we need to have more than a single scope
856 /// for a local. We have the `source_info.scope` represent the "syntactic"
857 /// lint scope (with a variable being under its let block) while the
858 /// `var_debug_info.source_info.scope` represents the "local variable"
859 /// scope (where the "rest" of a block is under all prior let-statements).
861 /// The end result looks like this:
865 /// │{ argument x: &str }
867 /// │ │{ #[allow(unused_mut)] } // This is actually split into 2 scopes
868 /// │ │ // in practice because I'm lazy.
870 /// │ │← x.source_info.scope
871 /// │ │← `x.parse().unwrap()`
873 /// │ │ │← y.source_info.scope
875 /// │ │ │{ let y: u32 }
877 /// │ │ │← y.var_debug_info.source_info.scope
880 /// │ │{ let x: u32 }
881 /// │ │← x.var_debug_info.source_info.scope
882 /// │ │← `drop(x)` // This accesses `x: u32`.
884 pub source_info: SourceInfo,
887 /// Extra information about a some locals that's used for diagnostics and for
888 /// classifying variables into local variables, statics, etc, which is needed e.g.
889 /// for unsafety checking.
891 /// Not used for non-StaticRef temporaries, the return place, or anonymous
892 /// function parameters.
893 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable, TypeVisitable)]
894 pub enum LocalInfo<'tcx> {
895 /// A user-defined local variable or function parameter
897 /// The `BindingForm` is solely used for local diagnostics when generating
898 /// warnings/errors when compiling the current crate, and therefore it need
899 /// not be visible across crates.
900 User(ClearCrossCrate<BindingForm<'tcx>>),
901 /// A temporary created that references the static with the given `DefId`.
902 StaticRef { def_id: DefId, is_thread_local: bool },
903 /// A temporary created that references the const with the given `DefId`
904 ConstRef { def_id: DefId },
905 /// A temporary created during the creation of an aggregate
906 /// (e.g. a temporary for `foo` in `MyStruct { my_field: foo }`)
908 /// A temporary created during the pass `Derefer` to avoid it's retagging
912 impl<'tcx> LocalDecl<'tcx> {
913 /// Returns `true` only if local is a binding that can itself be
914 /// made mutable via the addition of the `mut` keyword, namely
915 /// something like the occurrences of `x` in:
916 /// - `fn foo(x: Type) { ... }`,
918 /// - or `match ... { C(x) => ... }`
919 pub fn can_be_made_mutable(&self) -> bool {
922 Some(box LocalInfo::User(ClearCrossCrate::Set(
923 BindingForm::Var(VarBindingForm {
924 binding_mode: ty::BindingMode::BindByValue(_),
928 }) | BindingForm::ImplicitSelf(ImplicitSelfKind::Imm),
933 /// Returns `true` if local is definitely not a `ref ident` or
934 /// `ref mut ident` binding. (Such bindings cannot be made into
935 /// mutable bindings, but the inverse does not necessarily hold).
936 pub fn is_nonref_binding(&self) -> bool {
939 Some(box LocalInfo::User(ClearCrossCrate::Set(
940 BindingForm::Var(VarBindingForm {
941 binding_mode: ty::BindingMode::BindByValue(_),
945 }) | BindingForm::ImplicitSelf(_),
950 /// Returns `true` if this variable is a named variable or function
951 /// parameter declared by the user.
953 pub fn is_user_variable(&self) -> bool {
954 matches!(self.local_info, Some(box LocalInfo::User(_)))
957 /// Returns `true` if this is a reference to a variable bound in a `match`
958 /// expression that is used to access said variable for the guard of the
960 pub fn is_ref_for_guard(&self) -> bool {
963 Some(box LocalInfo::User(ClearCrossCrate::Set(BindingForm::RefForGuard)))
967 /// Returns `Some` if this is a reference to a static item that is used to
968 /// access that static.
969 pub fn is_ref_to_static(&self) -> bool {
970 matches!(self.local_info, Some(box LocalInfo::StaticRef { .. }))
973 /// Returns `Some` if this is a reference to a thread-local static item that is used to
974 /// access that static.
975 pub fn is_ref_to_thread_local(&self) -> bool {
976 match self.local_info {
977 Some(box LocalInfo::StaticRef { is_thread_local, .. }) => is_thread_local,
982 /// Returns `true` if this is a DerefTemp
983 pub fn is_deref_temp(&self) -> bool {
984 match self.local_info {
985 Some(box LocalInfo::DerefTemp) => return true,
991 /// Returns `true` is the local is from a compiler desugaring, e.g.,
992 /// `__next` from a `for` loop.
994 pub fn from_compiler_desugaring(&self) -> bool {
995 self.source_info.span.desugaring_kind().is_some()
998 /// Creates a new `LocalDecl` for a temporary: mutable, non-internal.
1000 pub fn new(ty: Ty<'tcx>, span: Span) -> Self {
1001 Self::with_source_info(ty, SourceInfo::outermost(span))
1004 /// Like `LocalDecl::new`, but takes a `SourceInfo` instead of a `Span`.
1006 pub fn with_source_info(ty: Ty<'tcx>, source_info: SourceInfo) -> Self {
1008 mutability: Mutability::Mut,
1011 is_block_tail: None,
1018 /// Converts `self` into same `LocalDecl` except tagged as internal.
1020 pub fn internal(mut self) -> Self {
1021 self.internal = true;
1025 /// Converts `self` into same `LocalDecl` except tagged as immutable.
1027 pub fn immutable(mut self) -> Self {
1028 self.mutability = Mutability::Not;
1032 /// Converts `self` into same `LocalDecl` except tagged as internal temporary.
1034 pub fn block_tail(mut self, info: BlockTailInfo) -> Self {
1035 assert!(self.is_block_tail.is_none());
1036 self.is_block_tail = Some(info);
1041 #[derive(Clone, TyEncodable, TyDecodable, HashStable, TypeFoldable, TypeVisitable)]
1042 pub enum VarDebugInfoContents<'tcx> {
1043 /// NOTE(eddyb) There's an unenforced invariant that this `Place` is
1044 /// based on a `Local`, not a `Static`, and contains no indexing.
1046 Const(Constant<'tcx>),
1047 /// The user variable's data is split across several fragments,
1048 /// each described by a `VarDebugInfoFragment`.
1049 /// See DWARF 5's "2.6.1.2 Composite Location Descriptions"
1050 /// and LLVM's `DW_OP_LLVM_fragment` for more details on
1051 /// the underlying debuginfo feature this relies on.
1053 /// Type of the original user variable.
1055 /// All the parts of the original user variable, which ended
1056 /// up in disjoint places, due to optimizations.
1057 fragments: Vec<VarDebugInfoFragment<'tcx>>,
1061 impl<'tcx> Debug for VarDebugInfoContents<'tcx> {
1062 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1064 VarDebugInfoContents::Const(c) => write!(fmt, "{}", c),
1065 VarDebugInfoContents::Place(p) => write!(fmt, "{:?}", p),
1066 VarDebugInfoContents::Composite { ty, fragments } => {
1067 write!(fmt, "{:?}{{ ", ty)?;
1068 for f in fragments.iter() {
1069 write!(fmt, "{:?}, ", f)?;
1077 #[derive(Clone, TyEncodable, TyDecodable, HashStable, TypeFoldable, TypeVisitable)]
1078 pub struct VarDebugInfoFragment<'tcx> {
1079 /// Where in the composite user variable this fragment is,
1080 /// represented as a "projection" into the composite variable.
1081 /// At lower levels, this corresponds to a byte/bit range.
1082 // NOTE(eddyb) there's an unenforced invariant that this contains
1083 // only `Field`s, and not into `enum` variants or `union`s.
1084 // FIXME(eddyb) support this for `enum`s by either using DWARF's
1085 // more advanced control-flow features (unsupported by LLVM?)
1086 // to match on the discriminant, or by using custom type debuginfo
1087 // with non-overlapping variants for the composite variable.
1088 pub projection: Vec<PlaceElem<'tcx>>,
1090 /// Where the data for this fragment can be found.
1091 // NOTE(eddyb) There's an unenforced invariant that this `Place` is
1092 // contains no indexing (with a non-constant index).
1093 pub contents: Place<'tcx>,
1096 impl Debug for VarDebugInfoFragment<'_> {
1097 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1098 for elem in self.projection.iter() {
1100 ProjectionElem::Field(field, _) => {
1101 write!(fmt, ".{:?}", field.index())?;
1103 _ => bug!("unsupported fragment projection `{:?}`", elem),
1107 write!(fmt, " => {:?}", self.contents)
1111 /// Debug information pertaining to a user variable.
1112 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable, TypeVisitable)]
1113 pub struct VarDebugInfo<'tcx> {
1116 /// Source info of the user variable, including the scope
1117 /// within which the variable is visible (to debuginfo)
1118 /// (see `LocalDecl`'s `source_info` field for more details).
1119 pub source_info: SourceInfo,
1121 /// Where the data for this user variable is to be found.
1122 pub value: VarDebugInfoContents<'tcx>,
1125 ///////////////////////////////////////////////////////////////////////////
1128 rustc_index::newtype_index! {
1129 /// A node in the MIR [control-flow graph][CFG].
1131 /// There are no branches (e.g., `if`s, function calls, etc.) within a basic block, which makes
1132 /// it easier to do [data-flow analyses] and optimizations. Instead, branches are represented
1133 /// as an edge in a graph between basic blocks.
1135 /// Basic blocks consist of a series of [statements][Statement], ending with a
1136 /// [terminator][Terminator]. Basic blocks can have multiple predecessors and successors,
1137 /// however there is a MIR pass ([`CriticalCallEdges`]) that removes *critical edges*, which
1138 /// are edges that go from a multi-successor node to a multi-predecessor node. This pass is
1139 /// needed because some analyses require that there are no critical edges in the CFG.
1141 /// Note that this type is just an index into [`Body.basic_blocks`](Body::basic_blocks);
1142 /// the actual data that a basic block holds is in [`BasicBlockData`].
1144 /// Read more about basic blocks in the [rustc-dev-guide][guide-mir].
1146 /// [CFG]: https://rustc-dev-guide.rust-lang.org/appendix/background.html#cfg
1147 /// [data-flow analyses]:
1148 /// https://rustc-dev-guide.rust-lang.org/appendix/background.html#what-is-a-dataflow-analysis
1149 /// [`CriticalCallEdges`]: ../../rustc_const_eval/transform/add_call_guards/enum.AddCallGuards.html#variant.CriticalCallEdges
1150 /// [guide-mir]: https://rustc-dev-guide.rust-lang.org/mir/
1151 pub struct BasicBlock {
1153 DEBUG_FORMAT = "bb{}",
1154 const START_BLOCK = 0,
1159 pub fn start_location(self) -> Location {
1160 Location { block: self, statement_index: 0 }
1164 ///////////////////////////////////////////////////////////////////////////
1167 /// Data for a basic block, including a list of its statements.
1169 /// See [`BasicBlock`] for documentation on what basic blocks are at a high level.
1170 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable, TypeVisitable)]
1171 pub struct BasicBlockData<'tcx> {
1172 /// List of statements in this block.
1173 pub statements: Vec<Statement<'tcx>>,
1175 /// Terminator for this block.
1177 /// N.B., this should generally ONLY be `None` during construction.
1178 /// Therefore, you should generally access it via the
1179 /// `terminator()` or `terminator_mut()` methods. The only
1180 /// exception is that certain passes, such as `simplify_cfg`, swap
1181 /// out the terminator temporarily with `None` while they continue
1182 /// to recurse over the set of basic blocks.
1183 pub terminator: Option<Terminator<'tcx>>,
1185 /// If true, this block lies on an unwind path. This is used
1186 /// during codegen where distinct kinds of basic blocks may be
1187 /// generated (particularly for MSVC cleanup). Unwind blocks must
1188 /// only branch to other unwind blocks.
1189 pub is_cleanup: bool,
1192 impl<'tcx> BasicBlockData<'tcx> {
1193 pub fn new(terminator: Option<Terminator<'tcx>>) -> BasicBlockData<'tcx> {
1194 BasicBlockData { statements: vec![], terminator, is_cleanup: false }
1197 /// Accessor for terminator.
1199 /// Terminator may not be None after construction of the basic block is complete. This accessor
1200 /// provides a convenient way to reach the terminator.
1202 pub fn terminator(&self) -> &Terminator<'tcx> {
1203 self.terminator.as_ref().expect("invalid terminator state")
1207 pub fn terminator_mut(&mut self) -> &mut Terminator<'tcx> {
1208 self.terminator.as_mut().expect("invalid terminator state")
1211 pub fn retain_statements<F>(&mut self, mut f: F)
1213 F: FnMut(&mut Statement<'_>) -> bool,
1215 for s in &mut self.statements {
1222 pub fn expand_statements<F, I>(&mut self, mut f: F)
1224 F: FnMut(&mut Statement<'tcx>) -> Option<I>,
1225 I: iter::TrustedLen<Item = Statement<'tcx>>,
1227 // Gather all the iterators we'll need to splice in, and their positions.
1228 let mut splices: Vec<(usize, I)> = vec![];
1229 let mut extra_stmts = 0;
1230 for (i, s) in self.statements.iter_mut().enumerate() {
1231 if let Some(mut new_stmts) = f(s) {
1232 if let Some(first) = new_stmts.next() {
1233 // We can already store the first new statement.
1236 // Save the other statements for optimized splicing.
1237 let remaining = new_stmts.size_hint().0;
1239 splices.push((i + 1 + extra_stmts, new_stmts));
1240 extra_stmts += remaining;
1248 // Splice in the new statements, from the end of the block.
1249 // FIXME(eddyb) This could be more efficient with a "gap buffer"
1250 // where a range of elements ("gap") is left uninitialized, with
1251 // splicing adding new elements to the end of that gap and moving
1252 // existing elements from before the gap to the end of the gap.
1253 // For now, this is safe code, emulating a gap but initializing it.
1254 let mut gap = self.statements.len()..self.statements.len() + extra_stmts;
1255 self.statements.resize(
1257 Statement { source_info: SourceInfo::outermost(DUMMY_SP), kind: StatementKind::Nop },
1259 for (splice_start, new_stmts) in splices.into_iter().rev() {
1260 let splice_end = splice_start + new_stmts.size_hint().0;
1261 while gap.end > splice_end {
1264 self.statements.swap(gap.start, gap.end);
1266 self.statements.splice(splice_start..splice_end, new_stmts);
1267 gap.end = splice_start;
1271 pub fn visitable(&self, index: usize) -> &dyn MirVisitable<'tcx> {
1272 if index < self.statements.len() { &self.statements[index] } else { &self.terminator }
1275 /// Does the block have no statements and an unreachable terminator?
1276 pub fn is_empty_unreachable(&self) -> bool {
1277 self.statements.is_empty() && matches!(self.terminator().kind, TerminatorKind::Unreachable)
1281 impl<O> AssertKind<O> {
1282 /// Getting a description does not require `O` to be printable, and does not
1283 /// require allocation.
1284 /// The caller is expected to handle `BoundsCheck` separately.
1285 pub fn description(&self) -> &'static str {
1288 Overflow(BinOp::Add, _, _) => "attempt to add with overflow",
1289 Overflow(BinOp::Sub, _, _) => "attempt to subtract with overflow",
1290 Overflow(BinOp::Mul, _, _) => "attempt to multiply with overflow",
1291 Overflow(BinOp::Div, _, _) => "attempt to divide with overflow",
1292 Overflow(BinOp::Rem, _, _) => "attempt to calculate the remainder with overflow",
1293 OverflowNeg(_) => "attempt to negate with overflow",
1294 Overflow(BinOp::Shr, _, _) => "attempt to shift right with overflow",
1295 Overflow(BinOp::Shl, _, _) => "attempt to shift left with overflow",
1296 Overflow(op, _, _) => bug!("{:?} cannot overflow", op),
1297 DivisionByZero(_) => "attempt to divide by zero",
1298 RemainderByZero(_) => "attempt to calculate the remainder with a divisor of zero",
1299 ResumedAfterReturn(GeneratorKind::Gen) => "generator resumed after completion",
1300 ResumedAfterReturn(GeneratorKind::Async(_)) => "`async fn` resumed after completion",
1301 ResumedAfterPanic(GeneratorKind::Gen) => "generator resumed after panicking",
1302 ResumedAfterPanic(GeneratorKind::Async(_)) => "`async fn` resumed after panicking",
1303 BoundsCheck { .. } => bug!("Unexpected AssertKind"),
1307 /// Format the message arguments for the `assert(cond, msg..)` terminator in MIR printing.
1308 pub fn fmt_assert_args<W: Write>(&self, f: &mut W) -> fmt::Result
1314 BoundsCheck { ref len, ref index } => write!(
1316 "\"index out of bounds: the length is {{}} but the index is {{}}\", {:?}, {:?}",
1320 OverflowNeg(op) => {
1321 write!(f, "\"attempt to negate `{{}}`, which would overflow\", {:?}", op)
1323 DivisionByZero(op) => write!(f, "\"attempt to divide `{{}}` by zero\", {:?}", op),
1324 RemainderByZero(op) => write!(
1326 "\"attempt to calculate the remainder of `{{}}` with a divisor of zero\", {:?}",
1329 Overflow(BinOp::Add, l, r) => write!(
1331 "\"attempt to compute `{{}} + {{}}`, which would overflow\", {:?}, {:?}",
1334 Overflow(BinOp::Sub, l, r) => write!(
1336 "\"attempt to compute `{{}} - {{}}`, which would overflow\", {:?}, {:?}",
1339 Overflow(BinOp::Mul, l, r) => write!(
1341 "\"attempt to compute `{{}} * {{}}`, which would overflow\", {:?}, {:?}",
1344 Overflow(BinOp::Div, l, r) => write!(
1346 "\"attempt to compute `{{}} / {{}}`, which would overflow\", {:?}, {:?}",
1349 Overflow(BinOp::Rem, l, r) => write!(
1351 "\"attempt to compute the remainder of `{{}} % {{}}`, which would overflow\", {:?}, {:?}",
1354 Overflow(BinOp::Shr, _, r) => {
1355 write!(f, "\"attempt to shift right by `{{}}`, which would overflow\", {:?}", r)
1357 Overflow(BinOp::Shl, _, r) => {
1358 write!(f, "\"attempt to shift left by `{{}}`, which would overflow\", {:?}", r)
1360 _ => write!(f, "\"{}\"", self.description()),
1365 impl<O: fmt::Debug> fmt::Debug for AssertKind<O> {
1366 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1369 BoundsCheck { ref len, ref index } => write!(
1371 "index out of bounds: the length is {:?} but the index is {:?}",
1374 OverflowNeg(op) => write!(f, "attempt to negate `{:#?}`, which would overflow", op),
1375 DivisionByZero(op) => write!(f, "attempt to divide `{:#?}` by zero", op),
1376 RemainderByZero(op) => write!(
1378 "attempt to calculate the remainder of `{:#?}` with a divisor of zero",
1381 Overflow(BinOp::Add, l, r) => {
1382 write!(f, "attempt to compute `{:#?} + {:#?}`, which would overflow", l, r)
1384 Overflow(BinOp::Sub, l, r) => {
1385 write!(f, "attempt to compute `{:#?} - {:#?}`, which would overflow", l, r)
1387 Overflow(BinOp::Mul, l, r) => {
1388 write!(f, "attempt to compute `{:#?} * {:#?}`, which would overflow", l, r)
1390 Overflow(BinOp::Div, l, r) => {
1391 write!(f, "attempt to compute `{:#?} / {:#?}`, which would overflow", l, r)
1393 Overflow(BinOp::Rem, l, r) => write!(
1395 "attempt to compute the remainder of `{:#?} % {:#?}`, which would overflow",
1398 Overflow(BinOp::Shr, _, r) => {
1399 write!(f, "attempt to shift right by `{:#?}`, which would overflow", r)
1401 Overflow(BinOp::Shl, _, r) => {
1402 write!(f, "attempt to shift left by `{:#?}`, which would overflow", r)
1404 _ => write!(f, "{}", self.description()),
1409 ///////////////////////////////////////////////////////////////////////////
1412 /// A statement in a basic block, including information about its source code.
1413 #[derive(Clone, TyEncodable, TyDecodable, HashStable, TypeFoldable, TypeVisitable)]
1414 pub struct Statement<'tcx> {
1415 pub source_info: SourceInfo,
1416 pub kind: StatementKind<'tcx>,
1419 impl Statement<'_> {
1420 /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
1421 /// invalidating statement indices in `Location`s.
1422 pub fn make_nop(&mut self) {
1423 self.kind = StatementKind::Nop
1426 /// Changes a statement to a nop and returns the original statement.
1427 #[must_use = "If you don't need the statement, use `make_nop` instead"]
1428 pub fn replace_nop(&mut self) -> Self {
1430 source_info: self.source_info,
1431 kind: mem::replace(&mut self.kind, StatementKind::Nop),
1436 impl Debug for Statement<'_> {
1437 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1438 use self::StatementKind::*;
1440 Assign(box (ref place, ref rv)) => write!(fmt, "{:?} = {:?}", place, rv),
1441 FakeRead(box (ref cause, ref place)) => {
1442 write!(fmt, "FakeRead({:?}, {:?})", cause, place)
1444 Retag(ref kind, ref place) => write!(
1448 RetagKind::FnEntry => "[fn entry] ",
1449 RetagKind::TwoPhase => "[2phase] ",
1450 RetagKind::Raw => "[raw] ",
1451 RetagKind::Default => "",
1455 StorageLive(ref place) => write!(fmt, "StorageLive({:?})", place),
1456 StorageDead(ref place) => write!(fmt, "StorageDead({:?})", place),
1457 SetDiscriminant { ref place, variant_index } => {
1458 write!(fmt, "discriminant({:?}) = {:?}", place, variant_index)
1460 Deinit(ref place) => write!(fmt, "Deinit({:?})", place),
1461 AscribeUserType(box (ref place, ref c_ty), ref variance) => {
1462 write!(fmt, "AscribeUserType({:?}, {:?}, {:?})", place, variance, c_ty)
1464 Coverage(box self::Coverage { ref kind, code_region: Some(ref rgn) }) => {
1465 write!(fmt, "Coverage::{:?} for {:?}", kind, rgn)
1467 Coverage(box ref coverage) => write!(fmt, "Coverage::{:?}", coverage.kind),
1468 Intrinsic(box ref intrinsic) => write!(fmt, "{intrinsic}"),
1469 Nop => write!(fmt, "nop"),
1474 impl<'tcx> StatementKind<'tcx> {
1475 pub fn as_assign_mut(&mut self) -> Option<&mut (Place<'tcx>, Rvalue<'tcx>)> {
1477 StatementKind::Assign(x) => Some(x),
1482 pub fn as_assign(&self) -> Option<&(Place<'tcx>, Rvalue<'tcx>)> {
1484 StatementKind::Assign(x) => Some(x),
1490 ///////////////////////////////////////////////////////////////////////////
1493 impl<V, T> ProjectionElem<V, T> {
1494 /// Returns `true` if the target of this projection may refer to a different region of memory
1496 fn is_indirect(&self) -> bool {
1498 Self::Deref => true,
1502 | Self::OpaqueCast(_)
1503 | Self::ConstantIndex { .. }
1504 | Self::Subslice { .. }
1505 | Self::Downcast(_, _) => false,
1509 /// Returns `true` if this is a `Downcast` projection with the given `VariantIdx`.
1510 pub fn is_downcast_to(&self, v: VariantIdx) -> bool {
1511 matches!(*self, Self::Downcast(_, x) if x == v)
1514 /// Returns `true` if this is a `Field` projection with the given index.
1515 pub fn is_field_to(&self, f: Field) -> bool {
1516 matches!(*self, Self::Field(x, _) if x == f)
1520 /// Alias for projections as they appear in `UserTypeProjection`, where we
1521 /// need neither the `V` parameter for `Index` nor the `T` for `Field`.
1522 pub type ProjectionKind = ProjectionElem<(), ()>;
1524 rustc_index::newtype_index! {
1525 /// A [newtype'd][wrapper] index type in the MIR [control-flow graph][CFG]
1527 /// A field (e.g., `f` in `_1.f`) is one variant of [`ProjectionElem`]. Conceptually,
1528 /// rustc can identify that a field projection refers to either two different regions of memory
1529 /// or the same one between the base and the 'projection element'.
1530 /// Read more about projections in the [rustc-dev-guide][mir-datatypes]
1532 /// [wrapper]: https://rustc-dev-guide.rust-lang.org/appendix/glossary.html#newtype
1533 /// [CFG]: https://rustc-dev-guide.rust-lang.org/appendix/background.html#cfg
1534 /// [mir-datatypes]: https://rustc-dev-guide.rust-lang.org/mir/index.html#mir-data-types
1537 DEBUG_FORMAT = "field[{}]"
1541 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1542 pub struct PlaceRef<'tcx> {
1544 pub projection: &'tcx [PlaceElem<'tcx>],
1547 // Once we stop implementing `Ord` for `DefId`,
1548 // this impl will be unnecessary. Until then, we'll
1549 // leave this impl in place to prevent re-adding a
1550 // dependency on the `Ord` impl for `DefId`
1551 impl<'tcx> !PartialOrd for PlaceRef<'tcx> {}
1553 impl<'tcx> Place<'tcx> {
1554 // FIXME change this to a const fn by also making List::empty a const fn.
1555 pub fn return_place() -> Place<'tcx> {
1556 Place { local: RETURN_PLACE, projection: List::empty() }
1559 /// Returns `true` if this `Place` contains a `Deref` projection.
1561 /// If `Place::is_indirect` returns false, the caller knows that the `Place` refers to the
1562 /// same region of memory as its base.
1563 pub fn is_indirect(&self) -> bool {
1564 self.projection.iter().any(|elem| elem.is_indirect())
1567 /// If MirPhase >= Derefered and if projection contains Deref,
1568 /// It's guaranteed to be in the first place
1569 pub fn has_deref(&self) -> bool {
1570 // To make sure this is not accidentally used in wrong mir phase
1572 self.projection.is_empty() || !self.projection[1..].contains(&PlaceElem::Deref)
1574 self.projection.first() == Some(&PlaceElem::Deref)
1577 /// Finds the innermost `Local` from this `Place`, *if* it is either a local itself or
1578 /// a single deref of a local.
1580 pub fn local_or_deref_local(&self) -> Option<Local> {
1581 self.as_ref().local_or_deref_local()
1584 /// If this place represents a local variable like `_X` with no
1585 /// projections, return `Some(_X)`.
1587 pub fn as_local(&self) -> Option<Local> {
1588 self.as_ref().as_local()
1592 pub fn as_ref(&self) -> PlaceRef<'tcx> {
1593 PlaceRef { local: self.local, projection: &self.projection }
1596 /// Iterate over the projections in evaluation order, i.e., the first element is the base with
1597 /// its projection and then subsequently more projections are added.
1598 /// As a concrete example, given the place a.b.c, this would yield:
1602 /// Given a place without projections, the iterator is empty.
1604 pub fn iter_projections(
1606 ) -> impl Iterator<Item = (PlaceRef<'tcx>, PlaceElem<'tcx>)> + DoubleEndedIterator {
1607 self.as_ref().iter_projections()
1610 /// Generates a new place by appending `more_projections` to the existing ones
1611 /// and interning the result.
1612 pub fn project_deeper(self, more_projections: &[PlaceElem<'tcx>], tcx: TyCtxt<'tcx>) -> Self {
1613 if more_projections.is_empty() {
1617 let mut v: Vec<PlaceElem<'tcx>>;
1619 let new_projections = if self.projection.is_empty() {
1622 v = Vec::with_capacity(self.projection.len() + more_projections.len());
1623 v.extend(self.projection);
1624 v.extend(more_projections);
1628 Place { local: self.local, projection: tcx.intern_place_elems(new_projections) }
1632 impl From<Local> for Place<'_> {
1634 fn from(local: Local) -> Self {
1635 Place { local, projection: List::empty() }
1639 impl<'tcx> PlaceRef<'tcx> {
1640 /// Finds the innermost `Local` from this `Place`, *if* it is either a local itself or
1641 /// a single deref of a local.
1642 pub fn local_or_deref_local(&self) -> Option<Local> {
1644 PlaceRef { local, projection: [] }
1645 | PlaceRef { local, projection: [ProjectionElem::Deref] } => Some(local),
1650 /// If MirPhase >= Derefered and if projection contains Deref,
1651 /// It's guaranteed to be in the first place
1652 pub fn has_deref(&self) -> bool {
1653 self.projection.first() == Some(&PlaceElem::Deref)
1656 /// If this place represents a local variable like `_X` with no
1657 /// projections, return `Some(_X)`.
1659 pub fn as_local(&self) -> Option<Local> {
1661 PlaceRef { local, projection: [] } => Some(local),
1667 pub fn last_projection(&self) -> Option<(PlaceRef<'tcx>, PlaceElem<'tcx>)> {
1668 if let &[ref proj_base @ .., elem] = self.projection {
1669 Some((PlaceRef { local: self.local, projection: proj_base }, elem))
1675 /// Iterate over the projections in evaluation order, i.e., the first element is the base with
1676 /// its projection and then subsequently more projections are added.
1677 /// As a concrete example, given the place a.b.c, this would yield:
1681 /// Given a place without projections, the iterator is empty.
1683 pub fn iter_projections(
1685 ) -> impl Iterator<Item = (PlaceRef<'tcx>, PlaceElem<'tcx>)> + DoubleEndedIterator {
1686 self.projection.iter().enumerate().map(move |(i, proj)| {
1687 let base = PlaceRef { local: self.local, projection: &self.projection[..i] };
1693 impl Debug for Place<'_> {
1694 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1695 for elem in self.projection.iter().rev() {
1697 ProjectionElem::OpaqueCast(_)
1698 | ProjectionElem::Downcast(_, _)
1699 | ProjectionElem::Field(_, _) => {
1700 write!(fmt, "(").unwrap();
1702 ProjectionElem::Deref => {
1703 write!(fmt, "(*").unwrap();
1705 ProjectionElem::Index(_)
1706 | ProjectionElem::ConstantIndex { .. }
1707 | ProjectionElem::Subslice { .. } => {}
1711 write!(fmt, "{:?}", self.local)?;
1713 for elem in self.projection.iter() {
1715 ProjectionElem::OpaqueCast(ty) => {
1716 write!(fmt, " as {})", ty)?;
1718 ProjectionElem::Downcast(Some(name), _index) => {
1719 write!(fmt, " as {})", name)?;
1721 ProjectionElem::Downcast(None, index) => {
1722 write!(fmt, " as variant#{:?})", index)?;
1724 ProjectionElem::Deref => {
1727 ProjectionElem::Field(field, ty) => {
1728 write!(fmt, ".{:?}: {:?})", field.index(), ty)?;
1730 ProjectionElem::Index(ref index) => {
1731 write!(fmt, "[{:?}]", index)?;
1733 ProjectionElem::ConstantIndex { offset, min_length, from_end: false } => {
1734 write!(fmt, "[{:?} of {:?}]", offset, min_length)?;
1736 ProjectionElem::ConstantIndex { offset, min_length, from_end: true } => {
1737 write!(fmt, "[-{:?} of {:?}]", offset, min_length)?;
1739 ProjectionElem::Subslice { from, to, from_end: true } if to == 0 => {
1740 write!(fmt, "[{:?}:]", from)?;
1742 ProjectionElem::Subslice { from, to, from_end: true } if from == 0 => {
1743 write!(fmt, "[:-{:?}]", to)?;
1745 ProjectionElem::Subslice { from, to, from_end: true } => {
1746 write!(fmt, "[{:?}:-{:?}]", from, to)?;
1748 ProjectionElem::Subslice { from, to, from_end: false } => {
1749 write!(fmt, "[{:?}..{:?}]", from, to)?;
1758 ///////////////////////////////////////////////////////////////////////////
1761 rustc_index::newtype_index! {
1762 pub struct SourceScope {
1764 DEBUG_FORMAT = "scope[{}]",
1765 const OUTERMOST_SOURCE_SCOPE = 0,
1770 /// Finds the original HirId this MIR item came from.
1771 /// This is necessary after MIR optimizations, as otherwise we get a HirId
1772 /// from the function that was inlined instead of the function call site.
1773 pub fn lint_root<'tcx>(
1775 source_scopes: &IndexVec<SourceScope, SourceScopeData<'tcx>>,
1776 ) -> Option<HirId> {
1777 let mut data = &source_scopes[self];
1778 // FIXME(oli-obk): we should be able to just walk the `inlined_parent_scope`, but it
1779 // does not work as I thought it would. Needs more investigation and documentation.
1780 while data.inlined.is_some() {
1782 data = &source_scopes[data.parent_scope.unwrap()];
1785 match &data.local_data {
1786 ClearCrossCrate::Set(data) => Some(data.lint_root),
1787 ClearCrossCrate::Clear => None,
1791 /// The instance this source scope was inlined from, if any.
1793 pub fn inlined_instance<'tcx>(
1795 source_scopes: &IndexVec<SourceScope, SourceScopeData<'tcx>>,
1796 ) -> Option<ty::Instance<'tcx>> {
1797 let scope_data = &source_scopes[self];
1798 if let Some((inlined_instance, _)) = scope_data.inlined {
1799 Some(inlined_instance)
1800 } else if let Some(inlined_scope) = scope_data.inlined_parent_scope {
1801 Some(source_scopes[inlined_scope].inlined.unwrap().0)
1808 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable, TypeVisitable)]
1809 pub struct SourceScopeData<'tcx> {
1811 pub parent_scope: Option<SourceScope>,
1813 /// Whether this scope is the root of a scope tree of another body,
1814 /// inlined into this body by the MIR inliner.
1815 /// `ty::Instance` is the callee, and the `Span` is the call site.
1816 pub inlined: Option<(ty::Instance<'tcx>, Span)>,
1818 /// Nearest (transitive) parent scope (if any) which is inlined.
1819 /// This is an optimization over walking up `parent_scope`
1820 /// until a scope with `inlined: Some(...)` is found.
1821 pub inlined_parent_scope: Option<SourceScope>,
1823 /// Crate-local information for this source scope, that can't (and
1824 /// needn't) be tracked across crates.
1825 pub local_data: ClearCrossCrate<SourceScopeLocalData>,
1828 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable)]
1829 pub struct SourceScopeLocalData {
1830 /// An `HirId` with lint levels equivalent to this scope's lint levels.
1831 pub lint_root: hir::HirId,
1832 /// The unsafe block that contains this node.
1836 ///////////////////////////////////////////////////////////////////////////
1839 impl<'tcx> Debug for Operand<'tcx> {
1840 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1841 use self::Operand::*;
1843 Constant(ref a) => write!(fmt, "{:?}", a),
1844 Copy(ref place) => write!(fmt, "{:?}", place),
1845 Move(ref place) => write!(fmt, "move {:?}", place),
1850 impl<'tcx> Operand<'tcx> {
1851 /// Convenience helper to make a constant that refers to the fn
1852 /// with given `DefId` and substs. Since this is used to synthesize
1853 /// MIR, assumes `user_ty` is None.
1854 pub fn function_handle(
1857 substs: SubstsRef<'tcx>,
1860 let ty = tcx.mk_fn_def(def_id, substs);
1861 Operand::Constant(Box::new(Constant {
1864 literal: ConstantKind::Val(ConstValue::ZeroSized, ty),
1868 pub fn is_move(&self) -> bool {
1869 matches!(self, Operand::Move(..))
1872 /// Convenience helper to make a literal-like constant from a given scalar value.
1873 /// Since this is used to synthesize MIR, assumes `user_ty` is None.
1874 pub fn const_from_scalar(
1879 ) -> Operand<'tcx> {
1881 let param_env_and_ty = ty::ParamEnv::empty().and(ty);
1883 .layout_of(param_env_and_ty)
1884 .unwrap_or_else(|e| panic!("could not compute layout for {:?}: {:?}", ty, e))
1886 let scalar_size = match val {
1887 Scalar::Int(int) => int.size(),
1888 _ => panic!("Invalid scalar type {:?}", val),
1890 scalar_size == type_size
1892 Operand::Constant(Box::new(Constant {
1895 literal: ConstantKind::Val(ConstValue::Scalar(val), ty),
1899 pub fn to_copy(&self) -> Self {
1901 Operand::Copy(_) | Operand::Constant(_) => self.clone(),
1902 Operand::Move(place) => Operand::Copy(place),
1906 /// Returns the `Place` that is the target of this `Operand`, or `None` if this `Operand` is a
1908 pub fn place(&self) -> Option<Place<'tcx>> {
1910 Operand::Copy(place) | Operand::Move(place) => Some(*place),
1911 Operand::Constant(_) => None,
1915 /// Returns the `Constant` that is the target of this `Operand`, or `None` if this `Operand` is a
1917 pub fn constant(&self) -> Option<&Constant<'tcx>> {
1919 Operand::Constant(x) => Some(&**x),
1920 Operand::Copy(_) | Operand::Move(_) => None,
1924 /// Gets the `ty::FnDef` from an operand if it's a constant function item.
1926 /// While this is unlikely in general, it's the normal case of what you'll
1927 /// find as the `func` in a [`TerminatorKind::Call`].
1928 pub fn const_fn_def(&self) -> Option<(DefId, SubstsRef<'tcx>)> {
1929 let const_ty = self.constant()?.literal.ty();
1930 if let ty::FnDef(def_id, substs) = *const_ty.kind() { Some((def_id, substs)) } else { None }
1934 ///////////////////////////////////////////////////////////////////////////
1937 impl<'tcx> Rvalue<'tcx> {
1938 /// Returns true if rvalue can be safely removed when the result is unused.
1940 pub fn is_safe_to_remove(&self) -> bool {
1942 // Pointer to int casts may be side-effects due to exposing the provenance.
1943 // While the model is undecided, we should be conservative. See
1944 // <https://www.ralfj.de/blog/2022/04/11/provenance-exposed.html>
1945 Rvalue::Cast(CastKind::PointerExposeAddress, _, _) => false,
1948 | Rvalue::CopyForDeref(_)
1949 | Rvalue::Repeat(_, _)
1950 | Rvalue::Ref(_, _, _)
1951 | Rvalue::ThreadLocalRef(_)
1952 | Rvalue::AddressOf(_, _)
1956 | CastKind::FloatToInt
1957 | CastKind::FloatToFloat
1958 | CastKind::IntToFloat
1959 | CastKind::FnPtrToPtr
1960 | CastKind::PtrToPtr
1961 | CastKind::Pointer(_)
1962 | CastKind::PointerFromExposedAddress
1963 | CastKind::DynStar,
1967 | Rvalue::BinaryOp(_, _)
1968 | Rvalue::CheckedBinaryOp(_, _)
1969 | Rvalue::NullaryOp(_, _)
1970 | Rvalue::UnaryOp(_, _)
1971 | Rvalue::Discriminant(_)
1972 | Rvalue::Aggregate(_, _)
1973 | Rvalue::ShallowInitBox(_, _) => true,
1979 pub fn allows_two_phase_borrow(&self) -> bool {
1981 BorrowKind::Shared | BorrowKind::Shallow | BorrowKind::Unique => false,
1982 BorrowKind::Mut { allow_two_phase_borrow } => allow_two_phase_borrow,
1986 // FIXME: won't be used after diagnostic migration
1987 pub fn describe_mutability(&self) -> &str {
1989 BorrowKind::Shared | BorrowKind::Shallow | BorrowKind::Unique => "immutable",
1990 BorrowKind::Mut { .. } => "mutable",
1996 pub fn is_checkable(self) -> bool {
1998 matches!(self, Add | Sub | Mul | Shl | Shr)
2002 impl<'tcx> Debug for Rvalue<'tcx> {
2003 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2004 use self::Rvalue::*;
2007 Use(ref place) => write!(fmt, "{:?}", place),
2008 Repeat(ref a, b) => {
2009 write!(fmt, "[{:?}; ", a)?;
2010 pretty_print_const(b, fmt, false)?;
2013 Len(ref a) => write!(fmt, "Len({:?})", a),
2014 Cast(ref kind, ref place, ref ty) => {
2015 write!(fmt, "{:?} as {:?} ({:?})", place, ty, kind)
2017 BinaryOp(ref op, box (ref a, ref b)) => write!(fmt, "{:?}({:?}, {:?})", op, a, b),
2018 CheckedBinaryOp(ref op, box (ref a, ref b)) => {
2019 write!(fmt, "Checked{:?}({:?}, {:?})", op, a, b)
2021 UnaryOp(ref op, ref a) => write!(fmt, "{:?}({:?})", op, a),
2022 Discriminant(ref place) => write!(fmt, "discriminant({:?})", place),
2023 NullaryOp(ref op, ref t) => write!(fmt, "{:?}({:?})", op, t),
2024 ThreadLocalRef(did) => ty::tls::with(|tcx| {
2025 let muta = tcx.static_mutability(did).unwrap().prefix_str();
2026 write!(fmt, "&/*tls*/ {}{}", muta, tcx.def_path_str(did))
2028 Ref(region, borrow_kind, ref place) => {
2029 let kind_str = match borrow_kind {
2030 BorrowKind::Shared => "",
2031 BorrowKind::Shallow => "shallow ",
2032 BorrowKind::Mut { .. } | BorrowKind::Unique => "mut ",
2035 // When printing regions, add trailing space if necessary.
2036 let print_region = ty::tls::with(|tcx| {
2037 tcx.sess.verbose() || tcx.sess.opts.unstable_opts.identify_regions
2039 let region = if print_region {
2040 let mut region = region.to_string();
2041 if !region.is_empty() {
2046 // Do not even print 'static
2049 write!(fmt, "&{}{}{:?}", region, kind_str, place)
2052 CopyForDeref(ref place) => write!(fmt, "deref_copy {:#?}", place),
2054 AddressOf(mutability, ref place) => {
2055 let kind_str = match mutability {
2056 Mutability::Mut => "mut",
2057 Mutability::Not => "const",
2060 write!(fmt, "&raw {} {:?}", kind_str, place)
2063 Aggregate(ref kind, ref places) => {
2064 let fmt_tuple = |fmt: &mut Formatter<'_>, name: &str| {
2065 let mut tuple_fmt = fmt.debug_tuple(name);
2066 for place in places {
2067 tuple_fmt.field(place);
2073 AggregateKind::Array(_) => write!(fmt, "{:?}", places),
2075 AggregateKind::Tuple => {
2076 if places.is_empty() {
2083 AggregateKind::Adt(adt_did, variant, substs, _user_ty, _) => {
2084 ty::tls::with(|tcx| {
2085 let variant_def = &tcx.adt_def(adt_did).variant(variant);
2086 let substs = tcx.lift(substs).expect("could not lift for printing");
2087 let name = FmtPrinter::new(tcx, Namespace::ValueNS)
2088 .print_def_path(variant_def.def_id, substs)?
2091 match variant_def.ctor_kind() {
2092 Some(CtorKind::Const) => fmt.write_str(&name),
2093 Some(CtorKind::Fn) => fmt_tuple(fmt, &name),
2095 let mut struct_fmt = fmt.debug_struct(&name);
2096 for (field, place) in iter::zip(&variant_def.fields, places) {
2097 struct_fmt.field(field.name.as_str(), place);
2105 AggregateKind::Closure(def_id, substs) => ty::tls::with(|tcx| {
2106 let name = if tcx.sess.opts.unstable_opts.span_free_formats {
2107 let substs = tcx.lift(substs).unwrap();
2110 tcx.def_path_str_with_substs(def_id.to_def_id(), substs),
2113 let span = tcx.def_span(def_id);
2116 tcx.sess.source_map().span_to_diagnostic_string(span)
2119 let mut struct_fmt = fmt.debug_struct(&name);
2121 // FIXME(project-rfc-2229#48): This should be a list of capture names/places
2122 if let Some(upvars) = tcx.upvars_mentioned(def_id) {
2123 for (&var_id, place) in iter::zip(upvars.keys(), places) {
2124 let var_name = tcx.hir().name(var_id);
2125 struct_fmt.field(var_name.as_str(), place);
2132 AggregateKind::Generator(def_id, _, _) => ty::tls::with(|tcx| {
2133 let name = format!("[generator@{:?}]", tcx.def_span(def_id));
2134 let mut struct_fmt = fmt.debug_struct(&name);
2136 // FIXME(project-rfc-2229#48): This should be a list of capture names/places
2137 if let Some(upvars) = tcx.upvars_mentioned(def_id) {
2138 for (&var_id, place) in iter::zip(upvars.keys(), places) {
2139 let var_name = tcx.hir().name(var_id);
2140 struct_fmt.field(var_name.as_str(), place);
2149 ShallowInitBox(ref place, ref ty) => {
2150 write!(fmt, "ShallowInitBox({:?}, {:?})", place, ty)
2156 ///////////////////////////////////////////////////////////////////////////
2159 /// Two constants are equal if they are the same constant. Note that
2160 /// this does not necessarily mean that they are `==` in Rust. In
2161 /// particular, one must be wary of `NaN`!
2163 #[derive(Clone, Copy, PartialEq, TyEncodable, TyDecodable, Hash, HashStable)]
2164 #[derive(TypeFoldable, TypeVisitable)]
2165 pub struct Constant<'tcx> {
2168 /// Optional user-given type: for something like
2169 /// `collect::<Vec<_>>`, this would be present and would
2170 /// indicate that `Vec<_>` was explicitly specified.
2172 /// Needed for NLL to impose user-given type constraints.
2173 pub user_ty: Option<UserTypeAnnotationIndex>,
2175 pub literal: ConstantKind<'tcx>,
2178 #[derive(Clone, Copy, PartialEq, Eq, TyEncodable, TyDecodable, Hash, HashStable, Debug)]
2179 #[derive(Lift, TypeFoldable, TypeVisitable)]
2180 pub enum ConstantKind<'tcx> {
2181 /// This constant came from the type system
2182 Ty(ty::Const<'tcx>),
2184 /// An unevaluated mir constant which is not part of the type system.
2185 Unevaluated(UnevaluatedConst<'tcx>, Ty<'tcx>),
2187 /// This constant cannot go back into the type system, as it represents
2188 /// something the type system cannot handle (e.g. pointers).
2189 Val(interpret::ConstValue<'tcx>, Ty<'tcx>),
2192 impl<'tcx> Constant<'tcx> {
2193 pub fn check_static_ptr(&self, tcx: TyCtxt<'_>) -> Option<DefId> {
2194 match self.literal.try_to_scalar() {
2195 Some(Scalar::Ptr(ptr, _size)) => match tcx.global_alloc(ptr.provenance) {
2196 GlobalAlloc::Static(def_id) => {
2197 assert!(!tcx.is_thread_local_static(def_id));
2206 pub fn ty(&self) -> Ty<'tcx> {
2211 impl<'tcx> ConstantKind<'tcx> {
2213 pub fn ty(&self) -> Ty<'tcx> {
2215 ConstantKind::Ty(c) => c.ty(),
2216 ConstantKind::Val(_, ty) | ConstantKind::Unevaluated(_, ty) => *ty,
2221 pub fn try_to_value(self, tcx: TyCtxt<'tcx>) -> Option<interpret::ConstValue<'tcx>> {
2223 ConstantKind::Ty(c) => match c.kind() {
2224 ty::ConstKind::Value(valtree) => Some(tcx.valtree_to_const_val((c.ty(), valtree))),
2227 ConstantKind::Val(val, _) => Some(val),
2228 ConstantKind::Unevaluated(..) => None,
2233 pub fn try_to_scalar(self) -> Option<Scalar> {
2235 ConstantKind::Ty(c) => match c.kind() {
2236 ty::ConstKind::Value(valtree) => match valtree {
2237 ty::ValTree::Leaf(scalar_int) => Some(Scalar::Int(scalar_int)),
2238 ty::ValTree::Branch(_) => None,
2242 ConstantKind::Val(val, _) => val.try_to_scalar(),
2243 ConstantKind::Unevaluated(..) => None,
2248 pub fn try_to_scalar_int(self) -> Option<ScalarInt> {
2249 Some(self.try_to_scalar()?.assert_int())
2253 pub fn try_to_bits(self, size: Size) -> Option<u128> {
2254 self.try_to_scalar_int()?.to_bits(size).ok()
2258 pub fn try_to_bool(self) -> Option<bool> {
2259 self.try_to_scalar_int()?.try_into().ok()
2263 pub fn eval(self, tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>) -> Self {
2266 if let Some(val) = c.kind().try_eval_for_mir(tcx, param_env) {
2268 Ok(val) => Self::Val(val, c.ty()),
2269 Err(_) => Self::Ty(tcx.const_error(self.ty())),
2275 Self::Val(_, _) => self,
2276 Self::Unevaluated(uneval, ty) => {
2277 // FIXME: We might want to have a `try_eval`-like function on `Unevaluated`
2278 match tcx.const_eval_resolve(param_env, uneval, None) {
2279 Ok(val) => Self::Val(val, ty),
2280 Err(ErrorHandled::TooGeneric) => self,
2281 Err(ErrorHandled::Reported(guar)) => {
2282 Self::Ty(tcx.const_error_with_guaranteed(ty, guar))
2289 /// Panics if the value cannot be evaluated or doesn't contain a valid integer of the given type.
2291 pub fn eval_bits(self, tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>, ty: Ty<'tcx>) -> u128 {
2292 self.try_eval_bits(tcx, param_env, ty)
2293 .unwrap_or_else(|| bug!("expected bits of {:#?}, got {:#?}", ty, self))
2297 pub fn try_eval_bits(
2300 param_env: ty::ParamEnv<'tcx>,
2304 Self::Ty(ct) => ct.try_eval_bits(tcx, param_env, ty),
2305 Self::Val(val, t) => {
2308 tcx.layout_of(param_env.with_reveal_all_normalized(tcx).and(ty)).ok()?.size;
2309 val.try_to_bits(size)
2311 Self::Unevaluated(uneval, ty) => {
2312 match tcx.const_eval_resolve(param_env, *uneval, None) {
2315 .layout_of(param_env.with_reveal_all_normalized(tcx).and(*ty))
2318 val.try_to_bits(size)
2327 pub fn try_eval_bool(&self, tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>) -> Option<bool> {
2329 Self::Ty(ct) => ct.try_eval_bool(tcx, param_env),
2330 Self::Val(val, _) => val.try_to_bool(),
2331 Self::Unevaluated(uneval, _) => {
2332 match tcx.const_eval_resolve(param_env, *uneval, None) {
2333 Ok(val) => val.try_to_bool(),
2341 pub fn try_eval_usize(&self, tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>) -> Option<u64> {
2343 Self::Ty(ct) => ct.try_eval_usize(tcx, param_env),
2344 Self::Val(val, _) => val.try_to_machine_usize(tcx),
2345 Self::Unevaluated(uneval, _) => {
2346 match tcx.const_eval_resolve(param_env, *uneval, None) {
2347 Ok(val) => val.try_to_machine_usize(tcx),
2355 pub fn from_value(val: ConstValue<'tcx>, ty: Ty<'tcx>) -> Self {
2362 param_env_ty: ty::ParamEnvAnd<'tcx, Ty<'tcx>>,
2365 .layout_of(param_env_ty)
2366 .unwrap_or_else(|e| {
2367 bug!("could not compute layout for {:?}: {:?}", param_env_ty.value, e)
2370 let cv = ConstValue::Scalar(Scalar::from_uint(bits, size));
2372 Self::Val(cv, param_env_ty.value)
2376 pub fn from_bool(tcx: TyCtxt<'tcx>, v: bool) -> Self {
2377 let cv = ConstValue::from_bool(v);
2378 Self::Val(cv, tcx.types.bool)
2382 pub fn zero_sized(ty: Ty<'tcx>) -> Self {
2383 let cv = ConstValue::ZeroSized;
2387 pub fn from_usize(tcx: TyCtxt<'tcx>, n: u64) -> Self {
2388 let ty = tcx.types.usize;
2389 Self::from_bits(tcx, n as u128, ty::ParamEnv::empty().and(ty))
2393 pub fn from_scalar(_tcx: TyCtxt<'tcx>, s: Scalar, ty: Ty<'tcx>) -> Self {
2394 let val = ConstValue::Scalar(s);
2398 /// Literals are converted to `ConstantKindVal`, const generic parameters are eagerly
2399 /// converted to a constant, everything else becomes `Unevaluated`.
2400 pub fn from_anon_const(
2403 param_env: ty::ParamEnv<'tcx>,
2405 Self::from_opt_const_arg_anon_const(tcx, ty::WithOptConstParam::unknown(def_id), param_env)
2408 #[instrument(skip(tcx), level = "debug", ret)]
2409 pub fn from_inline_const(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> Self {
2410 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
2411 let body_id = match tcx.hir().get(hir_id) {
2412 hir::Node::AnonConst(ac) => ac.body,
2414 tcx.def_span(def_id.to_def_id()),
2415 "from_inline_const can only process anonymous constants"
2418 let expr = &tcx.hir().body(body_id).value;
2419 let ty = tcx.typeck(def_id).node_type(hir_id);
2421 let lit_input = match expr.kind {
2422 hir::ExprKind::Lit(ref lit) => Some(LitToConstInput { lit: &lit.node, ty, neg: false }),
2423 hir::ExprKind::Unary(hir::UnOp::Neg, ref expr) => match expr.kind {
2424 hir::ExprKind::Lit(ref lit) => {
2425 Some(LitToConstInput { lit: &lit.node, ty, neg: true })
2431 if let Some(lit_input) = lit_input {
2432 // If an error occurred, ignore that it's a literal and leave reporting the error up to
2434 match tcx.at(expr.span).lit_to_mir_constant(lit_input) {
2440 let typeck_root_def_id = tcx.typeck_root_def_id(def_id.to_def_id());
2442 tcx.erase_regions(InternalSubsts::identity_for_item(tcx, typeck_root_def_id));
2444 ty::InlineConstSubsts::new(tcx, ty::InlineConstSubstsParts { parent_substs, ty })
2447 let uneval = UnevaluatedConst {
2448 def: ty::WithOptConstParam::unknown(def_id).to_global(),
2452 debug_assert!(!uneval.has_free_regions());
2454 Self::Unevaluated(uneval, ty)
2457 #[instrument(skip(tcx), level = "debug", ret)]
2458 fn from_opt_const_arg_anon_const(
2460 def: ty::WithOptConstParam<LocalDefId>,
2461 param_env: ty::ParamEnv<'tcx>,
2463 let body_id = match tcx.hir().get_by_def_id(def.did) {
2464 hir::Node::AnonConst(ac) => ac.body,
2466 tcx.def_span(def.did.to_def_id()),
2467 "from_anon_const can only process anonymous constants"
2471 let expr = &tcx.hir().body(body_id).value;
2474 // Unwrap a block, so that e.g. `{ P }` is recognised as a parameter. Const arguments
2475 // currently have to be wrapped in curly brackets, so it's necessary to special-case.
2476 let expr = match &expr.kind {
2477 hir::ExprKind::Block(block, _) if block.stmts.is_empty() && block.expr.is_some() => {
2478 block.expr.as_ref().unwrap()
2482 debug!("expr.kind: {:?}", expr.kind);
2484 let ty = tcx.type_of(def.def_id_for_type_of());
2487 // FIXME(const_generics): We currently have to special case parameters because `min_const_generics`
2488 // does not provide the parents generics to anonymous constants. We still allow generic const
2489 // parameters by themselves however, e.g. `N`. These constants would cause an ICE if we were to
2490 // ever try to substitute the generic parameters in their bodies.
2492 // While this doesn't happen as these constants are always used as `ty::ConstKind::Param`, it does
2493 // cause issues if we were to remove that special-case and try to evaluate the constant instead.
2494 use hir::{def::DefKind::ConstParam, def::Res, ExprKind, Path, QPath};
2496 ExprKind::Path(QPath::Resolved(_, &Path { res: Res::Def(ConstParam, def_id), .. })) => {
2497 // Find the name and index of the const parameter by indexing the generics of
2498 // the parent item and construct a `ParamConst`.
2499 let item_def_id = tcx.parent(def_id);
2500 let generics = tcx.generics_of(item_def_id);
2501 let index = generics.param_def_id_to_index[&def_id];
2502 let name = tcx.item_name(def_id);
2503 let ty_const = tcx.mk_const(ty::ParamConst::new(index, name), ty);
2506 return Self::Ty(ty_const);
2511 let hir_id = tcx.hir().local_def_id_to_hir_id(def.did);
2512 let parent_substs = if let Some(parent_hir_id) = tcx.hir().find_parent_node(hir_id) {
2513 if let Some(parent_did) = tcx.hir().opt_local_def_id(parent_hir_id) {
2514 InternalSubsts::identity_for_item(tcx, parent_did.to_def_id())
2516 tcx.mk_substs(Vec::<GenericArg<'tcx>>::new().into_iter())
2519 tcx.mk_substs(Vec::<GenericArg<'tcx>>::new().into_iter())
2521 debug!(?parent_substs);
2523 let did = def.did.to_def_id();
2524 let child_substs = InternalSubsts::identity_for_item(tcx, did);
2525 let substs = tcx.mk_substs(parent_substs.into_iter().chain(child_substs.into_iter()));
2528 let hir_id = tcx.hir().local_def_id_to_hir_id(def.did);
2529 let span = tcx.hir().span(hir_id);
2530 let uneval = UnevaluatedConst::new(def.to_global(), substs);
2531 debug!(?span, ?param_env);
2533 match tcx.const_eval_resolve(param_env, uneval, Some(span)) {
2535 debug!("evaluated const value");
2539 debug!("error encountered during evaluation");
2540 // Error was handled in `const_eval_resolve`. Here we just create a
2541 // new unevaluated const and error hard later in codegen
2544 def: def.to_global(),
2545 substs: InternalSubsts::identity_for_item(tcx, def.did.to_def_id()),
2554 pub fn from_const(c: ty::Const<'tcx>, tcx: TyCtxt<'tcx>) -> Self {
2556 ty::ConstKind::Value(valtree) => {
2557 let const_val = tcx.valtree_to_const_val((c.ty(), valtree));
2558 Self::Val(const_val, c.ty())
2560 ty::ConstKind::Unevaluated(uv) => Self::Unevaluated(uv.expand(), c.ty()),
2566 /// An unevaluated (potentially generic) constant used in MIR.
2567 #[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord, TyEncodable, TyDecodable, Lift)]
2568 #[derive(Hash, HashStable, TypeFoldable, TypeVisitable)]
2569 pub struct UnevaluatedConst<'tcx> {
2570 pub def: ty::WithOptConstParam<DefId>,
2571 pub substs: SubstsRef<'tcx>,
2572 pub promoted: Option<Promoted>,
2575 impl<'tcx> UnevaluatedConst<'tcx> {
2576 // FIXME: probably should get rid of this method. It's also wrong to
2577 // shrink and then later expand a promoted.
2579 pub fn shrink(self) -> ty::UnevaluatedConst<'tcx> {
2580 ty::UnevaluatedConst { def: self.def, substs: self.substs }
2584 impl<'tcx> UnevaluatedConst<'tcx> {
2587 def: ty::WithOptConstParam<DefId>,
2588 substs: SubstsRef<'tcx>,
2589 ) -> UnevaluatedConst<'tcx> {
2590 UnevaluatedConst { def, substs, promoted: Default::default() }
2594 /// A collection of projections into user types.
2596 /// They are projections because a binding can occur a part of a
2597 /// parent pattern that has been ascribed a type.
2599 /// Its a collection because there can be multiple type ascriptions on
2600 /// the path from the root of the pattern down to the binding itself.
2604 /// ```ignore (illustrative)
2605 /// struct S<'a>((i32, &'a str), String);
2606 /// let S((_, w): (i32, &'static str), _): S = ...;
2607 /// // ------ ^^^^^^^^^^^^^^^^^^^ (1)
2608 /// // --------------------------------- ^ (2)
2611 /// The highlights labelled `(1)` show the subpattern `(_, w)` being
2612 /// ascribed the type `(i32, &'static str)`.
2614 /// The highlights labelled `(2)` show the whole pattern being
2615 /// ascribed the type `S`.
2617 /// In this example, when we descend to `w`, we will have built up the
2618 /// following two projected types:
2620 /// * base: `S`, projection: `(base.0).1`
2621 /// * base: `(i32, &'static str)`, projection: `base.1`
2623 /// The first will lead to the constraint `w: &'1 str` (for some
2624 /// inferred region `'1`). The second will lead to the constraint `w:
2626 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable, TypeVisitable)]
2627 pub struct UserTypeProjections {
2628 pub contents: Vec<(UserTypeProjection, Span)>,
2631 impl<'tcx> UserTypeProjections {
2632 pub fn none() -> Self {
2633 UserTypeProjections { contents: vec![] }
2636 pub fn is_empty(&self) -> bool {
2637 self.contents.is_empty()
2640 pub fn projections_and_spans(
2642 ) -> impl Iterator<Item = &(UserTypeProjection, Span)> + ExactSizeIterator {
2643 self.contents.iter()
2646 pub fn projections(&self) -> impl Iterator<Item = &UserTypeProjection> + ExactSizeIterator {
2647 self.contents.iter().map(|&(ref user_type, _span)| user_type)
2650 pub fn push_projection(mut self, user_ty: &UserTypeProjection, span: Span) -> Self {
2651 self.contents.push((user_ty.clone(), span));
2657 mut f: impl FnMut(UserTypeProjection) -> UserTypeProjection,
2659 self.contents = self.contents.into_iter().map(|(proj, span)| (f(proj), span)).collect();
2663 pub fn index(self) -> Self {
2664 self.map_projections(|pat_ty_proj| pat_ty_proj.index())
2667 pub fn subslice(self, from: u64, to: u64) -> Self {
2668 self.map_projections(|pat_ty_proj| pat_ty_proj.subslice(from, to))
2671 pub fn deref(self) -> Self {
2672 self.map_projections(|pat_ty_proj| pat_ty_proj.deref())
2675 pub fn leaf(self, field: Field) -> Self {
2676 self.map_projections(|pat_ty_proj| pat_ty_proj.leaf(field))
2679 pub fn variant(self, adt_def: AdtDef<'tcx>, variant_index: VariantIdx, field: Field) -> Self {
2680 self.map_projections(|pat_ty_proj| pat_ty_proj.variant(adt_def, variant_index, field))
2684 /// Encodes the effect of a user-supplied type annotation on the
2685 /// subcomponents of a pattern. The effect is determined by applying the
2686 /// given list of projections to some underlying base type. Often,
2687 /// the projection element list `projs` is empty, in which case this
2688 /// directly encodes a type in `base`. But in the case of complex patterns with
2689 /// subpatterns and bindings, we want to apply only a *part* of the type to a variable,
2690 /// in which case the `projs` vector is used.
2694 /// * `let x: T = ...` -- here, the `projs` vector is empty.
2696 /// * `let (x, _): T = ...` -- here, the `projs` vector would contain
2697 /// `field[0]` (aka `.0`), indicating that the type of `s` is
2698 /// determined by finding the type of the `.0` field from `T`.
2699 #[derive(Clone, Debug, TyEncodable, TyDecodable, Hash, HashStable, PartialEq)]
2700 pub struct UserTypeProjection {
2701 pub base: UserTypeAnnotationIndex,
2702 pub projs: Vec<ProjectionKind>,
2705 impl Copy for ProjectionKind {}
2707 impl UserTypeProjection {
2708 pub(crate) fn index(mut self) -> Self {
2709 self.projs.push(ProjectionElem::Index(()));
2713 pub(crate) fn subslice(mut self, from: u64, to: u64) -> Self {
2714 self.projs.push(ProjectionElem::Subslice { from, to, from_end: true });
2718 pub(crate) fn deref(mut self) -> Self {
2719 self.projs.push(ProjectionElem::Deref);
2723 pub(crate) fn leaf(mut self, field: Field) -> Self {
2724 self.projs.push(ProjectionElem::Field(field, ()));
2728 pub(crate) fn variant(
2730 adt_def: AdtDef<'_>,
2731 variant_index: VariantIdx,
2734 self.projs.push(ProjectionElem::Downcast(
2735 Some(adt_def.variant(variant_index).name),
2738 self.projs.push(ProjectionElem::Field(field, ()));
2743 impl<'tcx> TypeFoldable<'tcx> for UserTypeProjection {
2744 fn try_fold_with<F: FallibleTypeFolder<'tcx>>(self, folder: &mut F) -> Result<Self, F::Error> {
2745 Ok(UserTypeProjection {
2746 base: self.base.try_fold_with(folder)?,
2747 projs: self.projs.try_fold_with(folder)?,
2752 impl<'tcx> TypeVisitable<'tcx> for UserTypeProjection {
2753 fn visit_with<Vs: TypeVisitor<'tcx>>(&self, visitor: &mut Vs) -> ControlFlow<Vs::BreakTy> {
2754 self.base.visit_with(visitor)
2755 // Note: there's nothing in `self.proj` to visit.
2759 rustc_index::newtype_index! {
2760 pub struct Promoted {
2762 DEBUG_FORMAT = "promoted[{}]"
2766 impl<'tcx> Debug for Constant<'tcx> {
2767 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2768 write!(fmt, "{}", self)
2772 impl<'tcx> Display for Constant<'tcx> {
2773 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2774 match self.ty().kind() {
2776 _ => write!(fmt, "const ")?,
2778 Display::fmt(&self.literal, fmt)
2782 impl<'tcx> Display for ConstantKind<'tcx> {
2783 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2785 ConstantKind::Ty(c) => pretty_print_const(c, fmt, true),
2786 ConstantKind::Val(val, ty) => pretty_print_const_value(val, ty, fmt, true),
2787 // FIXME(valtrees): Correctly print mir constants.
2788 ConstantKind::Unevaluated(..) => {
2789 fmt.write_str("_")?;
2796 fn pretty_print_const<'tcx>(
2798 fmt: &mut Formatter<'_>,
2801 use crate::ty::print::PrettyPrinter;
2802 ty::tls::with(|tcx| {
2803 let literal = tcx.lift(c).unwrap();
2804 let mut cx = FmtPrinter::new(tcx, Namespace::ValueNS);
2805 cx.print_alloc_ids = true;
2806 let cx = cx.pretty_print_const(literal, print_types)?;
2807 fmt.write_str(&cx.into_buffer())?;
2812 fn pretty_print_byte_str(fmt: &mut Formatter<'_>, byte_str: &[u8]) -> fmt::Result {
2813 write!(fmt, "b\"{}\"", byte_str.escape_ascii())
2816 fn comma_sep<'tcx>(fmt: &mut Formatter<'_>, elems: Vec<ConstantKind<'tcx>>) -> fmt::Result {
2817 let mut first = true;
2820 fmt.write_str(", ")?;
2822 fmt.write_str(&format!("{}", elem))?;
2828 // FIXME: Move that into `mir/pretty.rs`.
2829 fn pretty_print_const_value<'tcx>(
2830 ct: ConstValue<'tcx>,
2832 fmt: &mut Formatter<'_>,
2835 use crate::ty::print::PrettyPrinter;
2837 ty::tls::with(|tcx| {
2838 let ct = tcx.lift(ct).unwrap();
2839 let ty = tcx.lift(ty).unwrap();
2841 if tcx.sess.verbose() {
2842 fmt.write_str(&format!("ConstValue({:?}: {})", ct, ty))?;
2846 let u8_type = tcx.types.u8;
2847 match (ct, ty.kind()) {
2848 // Byte/string slices, printed as (byte) string literals.
2849 (ConstValue::Slice { data, start, end }, ty::Ref(_, inner, _)) => {
2850 match inner.kind() {
2853 // The `inspect` here is okay since we checked the bounds, and `u8` carries
2854 // no provenance (we have an active slice reference here). We don't use
2855 // this result to affect interpreter execution.
2858 .inspect_with_uninit_and_ptr_outside_interpreter(start..end);
2859 pretty_print_byte_str(fmt, byte_str)?;
2864 // The `inspect` here is okay since we checked the bounds, and `str` carries
2865 // no provenance (we have an active `str` reference here). We don't use this
2866 // result to affect interpreter execution.
2869 .inspect_with_uninit_and_ptr_outside_interpreter(start..end);
2870 fmt.write_str(&format!("{:?}", String::from_utf8_lossy(slice)))?;
2876 (ConstValue::ByRef { alloc, offset }, ty::Array(t, n)) if *t == u8_type => {
2877 let n = n.kind().try_to_bits(tcx.data_layout.pointer_size).unwrap();
2878 // cast is ok because we already checked for pointer size (32 or 64 bit) above
2879 let range = AllocRange { start: offset, size: Size::from_bytes(n) };
2880 let byte_str = alloc.inner().get_bytes_strip_provenance(&tcx, range).unwrap();
2881 fmt.write_str("*")?;
2882 pretty_print_byte_str(fmt, byte_str)?;
2885 // Aggregates, printed as array/tuple/struct/variant construction syntax.
2887 // NB: the `has_non_region_param` check ensures that we can use
2888 // the `destructure_const` query with an empty `ty::ParamEnv` without
2889 // introducing ICEs (e.g. via `layout_of`) from missing bounds.
2890 // E.g. `transmute([0usize; 2]): (u8, *mut T)` needs to know `T: Sized`
2891 // to be able to destructure the tuple into `(0u8, *mut T)
2893 // FIXME(eddyb) for `--emit=mir`/`-Z dump-mir`, we should provide the
2894 // correct `ty::ParamEnv` to allow printing *all* constant values.
2895 (_, ty::Array(..) | ty::Tuple(..) | ty::Adt(..)) if !ty.has_non_region_param() => {
2896 let ct = tcx.lift(ct).unwrap();
2897 let ty = tcx.lift(ty).unwrap();
2898 if let Some(contents) = tcx.try_destructure_mir_constant(
2899 ty::ParamEnv::reveal_all().and(ConstantKind::Val(ct, ty)),
2901 let fields = contents.fields.iter().copied().collect::<Vec<_>>();
2904 fmt.write_str("[")?;
2905 comma_sep(fmt, fields)?;
2906 fmt.write_str("]")?;
2909 fmt.write_str("(")?;
2910 comma_sep(fmt, fields)?;
2911 if contents.fields.len() == 1 {
2912 fmt.write_str(",")?;
2914 fmt.write_str(")")?;
2916 ty::Adt(def, _) if def.variants().is_empty() => {
2917 fmt.write_str(&format!("{{unreachable(): {}}}", ty))?;
2919 ty::Adt(def, substs) => {
2920 let variant_idx = contents
2922 .expect("destructed mir constant of adt without variant idx");
2923 let variant_def = &def.variant(variant_idx);
2924 let substs = tcx.lift(substs).unwrap();
2925 let mut cx = FmtPrinter::new(tcx, Namespace::ValueNS);
2926 cx.print_alloc_ids = true;
2927 let cx = cx.print_value_path(variant_def.def_id, substs)?;
2928 fmt.write_str(&cx.into_buffer())?;
2930 match variant_def.ctor_kind() {
2931 Some(CtorKind::Const) => {}
2932 Some(CtorKind::Fn) => {
2933 fmt.write_str("(")?;
2934 comma_sep(fmt, fields)?;
2935 fmt.write_str(")")?;
2938 fmt.write_str(" {{ ")?;
2939 let mut first = true;
2940 for (field_def, field) in iter::zip(&variant_def.fields, fields)
2943 fmt.write_str(", ")?;
2945 fmt.write_str(&format!("{}: {}", field_def.name, field))?;
2948 fmt.write_str(" }}")?;
2952 _ => unreachable!(),
2956 // Fall back to debug pretty printing for invalid constants.
2957 fmt.write_str(&format!("{:?}", ct))?;
2959 fmt.write_str(&format!(": {}", ty))?;
2964 (ConstValue::Scalar(scalar), _) => {
2965 let mut cx = FmtPrinter::new(tcx, Namespace::ValueNS);
2966 cx.print_alloc_ids = true;
2967 let ty = tcx.lift(ty).unwrap();
2968 cx = cx.pretty_print_const_scalar(scalar, ty, print_ty)?;
2969 fmt.write_str(&cx.into_buffer())?;
2972 (ConstValue::ZeroSized, ty::FnDef(d, s)) => {
2973 let mut cx = FmtPrinter::new(tcx, Namespace::ValueNS);
2974 cx.print_alloc_ids = true;
2975 let cx = cx.print_value_path(*d, s)?;
2976 fmt.write_str(&cx.into_buffer())?;
2979 // FIXME(oli-obk): also pretty print arrays and other aggregate constants by reading
2980 // their fields instead of just dumping the memory.
2984 fmt.write_str(&format!("{:?}", ct))?;
2986 fmt.write_str(&format!(": {}", ty))?;
2992 /// `Location` represents the position of the start of the statement; or, if
2993 /// `statement_index` equals the number of statements, then the start of the
2995 #[derive(Copy, Clone, PartialEq, Eq, Hash, Ord, PartialOrd, HashStable)]
2996 pub struct Location {
2997 /// The block that the location is within.
2998 pub block: BasicBlock,
3000 pub statement_index: usize,
3003 impl fmt::Debug for Location {
3004 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
3005 write!(fmt, "{:?}[{}]", self.block, self.statement_index)
3010 pub const START: Location = Location { block: START_BLOCK, statement_index: 0 };
3012 /// Returns the location immediately after this one within the enclosing block.
3014 /// Note that if this location represents a terminator, then the
3015 /// resulting location would be out of bounds and invalid.
3016 pub fn successor_within_block(&self) -> Location {
3017 Location { block: self.block, statement_index: self.statement_index + 1 }
3020 /// Returns `true` if `other` is earlier in the control flow graph than `self`.
3021 pub fn is_predecessor_of<'tcx>(&self, other: Location, body: &Body<'tcx>) -> bool {
3022 // If we are in the same block as the other location and are an earlier statement
3023 // then we are a predecessor of `other`.
3024 if self.block == other.block && self.statement_index < other.statement_index {
3028 let predecessors = body.basic_blocks.predecessors();
3030 // If we're in another block, then we want to check that block is a predecessor of `other`.
3031 let mut queue: Vec<BasicBlock> = predecessors[other.block].to_vec();
3032 let mut visited = FxHashSet::default();
3034 while let Some(block) = queue.pop() {
3035 // If we haven't visited this block before, then make sure we visit its predecessors.
3036 if visited.insert(block) {
3037 queue.extend(predecessors[block].iter().cloned());
3042 // If we found the block that `self` is in, then we are a predecessor of `other` (since
3043 // we found that block by looking at the predecessors of `other`).
3044 if self.block == block {
3052 pub fn dominates(&self, other: Location, dominators: &Dominators<BasicBlock>) -> bool {
3053 if self.block == other.block {
3054 self.statement_index <= other.statement_index
3056 dominators.is_dominated_by(other.block, self.block)
3061 // Some nodes are used a lot. Make sure they don't unintentionally get bigger.
3062 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
3065 use rustc_data_structures::static_assert_size;
3066 // tidy-alphabetical-start
3067 static_assert_size!(BasicBlockData<'_>, 144);
3068 static_assert_size!(LocalDecl<'_>, 56);
3069 static_assert_size!(Statement<'_>, 32);
3070 static_assert_size!(StatementKind<'_>, 16);
3071 static_assert_size!(Terminator<'_>, 112);
3072 static_assert_size!(TerminatorKind<'_>, 96);
3073 // tidy-alphabetical-end