]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_middle/src/mir/mod.rs
08cce3d76832a7319ce9e138a555ffc7d56715d5
[rust.git] / compiler / rustc_middle / src / mir / mod.rs
1 //! MIR datatypes and passes. See the [rustc dev guide] for more info.
2 //!
3 //! [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/mir/index.html
4
5 use crate::mir::interpret::{
6     AllocRange, ConstAllocation, ConstValue, ErrorHandled, GlobalAlloc, LitToConstInput, Scalar,
7 };
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};
16
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};
25
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};
35
36 use either::Either;
37
38 use std::borrow::Cow;
39 use std::convert::TryInto;
40 use std::fmt::{self, Debug, Display, Formatter, Write};
41 use std::ops::{ControlFlow, Index, IndexMut};
42 use std::{iter, mem};
43
44 pub use self::query::*;
45 pub use basic_blocks::BasicBlocks;
46
47 mod basic_blocks;
48 pub mod coverage;
49 mod generic_graph;
50 pub mod generic_graphviz;
51 mod graph_cyclic_cache;
52 pub mod graphviz;
53 pub mod interpret;
54 pub mod mono;
55 pub mod patch;
56 mod predecessors;
57 pub mod pretty;
58 mod query;
59 pub mod spanview;
60 mod syntax;
61 pub use syntax::*;
62 mod switch_sources;
63 pub mod tcx;
64 pub mod terminator;
65 pub use terminator::*;
66
67 pub mod traversal;
68 mod type_foldable;
69 mod type_visitable;
70 pub mod visit;
71
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,
76 };
77
78 /// Types for locals
79 pub type LocalDecls<'tcx> = IndexVec<Local, LocalDecl<'tcx>>;
80
81 pub trait HasLocalDecls<'tcx> {
82     fn local_decls(&self) -> &LocalDecls<'tcx>;
83 }
84
85 impl<'tcx> HasLocalDecls<'tcx> for LocalDecls<'tcx> {
86     #[inline]
87     fn local_decls(&self) -> &LocalDecls<'tcx> {
88         self
89     }
90 }
91
92 impl<'tcx> HasLocalDecls<'tcx> for Body<'tcx> {
93     #[inline]
94     fn local_decls(&self) -> &LocalDecls<'tcx> {
95         &self.local_decls
96     }
97 }
98
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 }
106     }
107
108     /// Returns `true` if this pass is enabled with the current combination of compiler flags.
109     fn is_enabled(&self, _sess: &Session) -> bool {
110         true
111     }
112
113     fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>);
114
115     fn is_mir_dump_enabled(&self) -> bool {
116         true
117     }
118 }
119
120 impl MirPhase {
121     /// Gets the index of the current MirPhase within the set of all `MirPhase`s.
122     ///
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;
127         match self {
128             MirPhase::Built => 1,
129             MirPhase::Analysis(analysis_phase) => {
130                 1 + BUILT_PHASE_COUNT + (*analysis_phase as usize)
131             }
132             MirPhase::Runtime(runtime_phase) => {
133                 1 + BUILT_PHASE_COUNT + ANALYSIS_PHASE_COUNT + (*runtime_phase as usize)
134             }
135         }
136     }
137
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() {
141             "built" => {
142                 assert!(phase.is_none(), "Cannot specify a phase for `Built` MIR");
143                 MirPhase::Built
144             }
145             "analysis" => Self::Analysis(AnalysisPhase::parse(phase)),
146             "runtime" => Self::Runtime(RuntimePhase::parse(phase)),
147             _ => panic!("Unknown MIR dialect {}", dialect),
148         }
149     }
150 }
151
152 impl AnalysisPhase {
153     pub fn parse(phase: Option<String>) -> Self {
154         let Some(phase) = phase else {
155             return Self::Initial;
156         };
157
158         match &*phase.to_ascii_lowercase() {
159             "initial" => Self::Initial,
160             "post_cleanup" | "post-cleanup" | "postcleanup" => Self::PostCleanup,
161             _ => panic!("Unknown analysis phase {}", phase),
162         }
163     }
164 }
165
166 impl RuntimePhase {
167     pub fn parse(phase: Option<String>) -> Self {
168         let Some(phase) = phase else {
169             return Self::Initial;
170         };
171
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),
177         }
178     }
179 }
180
181 impl Display for MirPhase {
182     fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
183         f.write_str(self.name())
184     }
185 }
186
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>,
192
193     /// If `Some`, this is a promoted rvalue within the parent function.
194     pub promoted: Option<Promoted>,
195 }
196
197 impl<'tcx> MirSource<'tcx> {
198     pub fn item(def_id: DefId) -> Self {
199         MirSource {
200             instance: InstanceDef::Item(ty::WithOptConstParam::unknown(def_id)),
201             promoted: None,
202         }
203     }
204
205     pub fn from_instance(instance: InstanceDef<'tcx>) -> Self {
206         MirSource { instance, promoted: None }
207     }
208
209     pub fn with_opt_param(self) -> ty::WithOptConstParam<DefId> {
210         self.instance.with_opt_param()
211     }
212
213     #[inline]
214     pub fn def_id(&self) -> DefId {
215         self.instance.def_id()
216     }
217 }
218
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>>,
223
224     /// Generator drop glue.
225     pub generator_drop: Option<Body<'tcx>>,
226
227     /// The layout of a generator. Produced by the state transformation.
228     pub generator_layout: Option<GeneratorLayout<'tcx>>,
229
230     /// If this is a generator then record the type of source expression that caused this generator
231     /// to be created.
232     pub generator_kind: GeneratorKind,
233 }
234
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>,
241
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.
247     pub phase: MirPhase,
248
249     /// How many passses we have executed since starting the current phase. Used for debug output.
250     pub pass_count: usize,
251
252     pub source: MirSource<'tcx>,
253
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>>,
257
258     pub generator: Option<Box<GeneratorInfo<'tcx>>>,
259
260     /// Declarations of locals.
261     ///
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>,
266
267     /// User type annotations.
268     pub user_type_annotations: ty::CanonicalUserTypeAnnotations<'tcx>,
269
270     /// The number of arguments this function takes.
271     ///
272     /// Starting at local 1, `arg_count` locals will be provided by the caller
273     /// and can be assumed to be initialized.
274     ///
275     /// If this MIR was built for a constant, this will be 0.
276     pub arg_count: usize,
277
278     /// Mark an argument local (which must be a tuple) as getting passed as
279     /// its individual components at the LLVM level.
280     ///
281     /// This is used for the "rust-call" ABI.
282     pub spread_arg: Option<Local>,
283
284     /// Debug information pertaining to user variables, including captures.
285     pub var_debug_info: Vec<VarDebugInfo<'tcx>>,
286
287     /// A span representing this MIR, for error reporting.
288     pub span: Span,
289
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>>,
293
294     /// Does this body use generic parameters. This is used for the `ConstEvaluatable` check.
295     ///
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`.
299     ///
300     /// ```rust
301     /// fn test<T>() {
302     ///     let _ = [0; std::mem::size_of::<*mut T>()];
303     /// }
304     /// ```
305     ///
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,
310
311     /// The phase at which this MIR should be "injected" into the compilation process.
312     ///
313     /// Everything that comes before this `MirPhase` should be skipped.
314     ///
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>,
317
318     pub tainted_by_errors: Option<ErrorGuaranteed>,
319 }
320
321 impl<'tcx> Body<'tcx> {
322     pub fn new(
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>,
328         arg_count: usize,
329         var_debug_info: Vec<VarDebugInfo<'tcx>>,
330         span: Span,
331         generator_kind: Option<GeneratorKind>,
332         tainted_by_errors: Option<ErrorGuaranteed>,
333     ) -> Self {
334         // We need `arg_count` locals, and one for the return place.
335         assert!(
336             local_decls.len() > arg_count,
337             "expected at least {} locals, got {}",
338             arg_count + 1,
339             local_decls.len()
340         );
341
342         let mut body = Body {
343             phase: MirPhase::Built,
344             pass_count: 1,
345             source,
346             basic_blocks: BasicBlocks::new(basic_blocks),
347             source_scopes,
348             generator: generator_kind.map(|generator_kind| {
349                 Box::new(GeneratorInfo {
350                     yield_ty: None,
351                     generator_drop: None,
352                     generator_layout: None,
353                     generator_kind,
354                 })
355             }),
356             local_decls,
357             user_type_annotations,
358             arg_count,
359             spread_arg: None,
360             var_debug_info,
361             span,
362             required_consts: Vec::new(),
363             is_polymorphic: false,
364             injection_phase: None,
365             tainted_by_errors,
366         };
367         body.is_polymorphic = body.has_non_region_param();
368         body
369     }
370
371     /// Returns a partially initialized MIR body containing only a list of basic blocks.
372     ///
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
375     /// crate.
376     pub fn new_cfg_only(basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>) -> Self {
377         let mut body = Body {
378             phase: MirPhase::Built,
379             pass_count: 1,
380             source: MirSource::item(CRATE_DEF_ID.to_def_id()),
381             basic_blocks: BasicBlocks::new(basic_blocks),
382             source_scopes: IndexVec::new(),
383             generator: None,
384             local_decls: IndexVec::new(),
385             user_type_annotations: IndexVec::new(),
386             arg_count: 0,
387             spread_arg: None,
388             span: DUMMY_SP,
389             required_consts: Vec::new(),
390             var_debug_info: Vec::new(),
391             is_polymorphic: false,
392             injection_phase: None,
393             tainted_by_errors: None,
394         };
395         body.is_polymorphic = body.has_non_region_param();
396         body
397     }
398
399     #[inline]
400     pub fn basic_blocks_mut(&mut self) -> &mut IndexVec<BasicBlock, BasicBlockData<'tcx>> {
401         self.basic_blocks.as_mut()
402     }
403
404     #[inline]
405     pub fn local_kind(&self, local: Local) -> LocalKind {
406         let index = local.as_usize();
407         if index == 0 {
408             debug_assert!(
409                 self.local_decls[local].mutability == Mutability::Mut,
410                 "return place should be mutable"
411             );
412
413             LocalKind::ReturnPointer
414         } else if index < self.arg_count + 1 {
415             LocalKind::Arg
416         } else if self.local_decls[local].is_user_variable() {
417             LocalKind::Var
418         } else {
419             LocalKind::Temp
420         }
421     }
422
423     /// Returns an iterator over all user-declared mutable locals.
424     #[inline]
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 {
430                 Some(local)
431             } else {
432                 None
433             }
434         })
435     }
436
437     /// Returns an iterator over all user-declared mutable arguments and locals.
438     #[inline]
439     pub fn mut_vars_and_args_iter<'a>(
440         &'a self,
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
447             {
448                 Some(local)
449             } else {
450                 None
451             }
452         })
453     }
454
455     /// Returns an iterator over all function arguments.
456     #[inline]
457     pub fn args_iter(&self) -> impl Iterator<Item = Local> + ExactSizeIterator {
458         (1..self.arg_count + 1).map(Local::new)
459     }
460
461     /// Returns an iterator over all user-defined variables and compiler-generated temporaries (all
462     /// locals that are neither arguments nor the return place).
463     #[inline]
464     pub fn vars_and_temps_iter(
465         &self,
466     ) -> impl DoubleEndedIterator<Item = Local> + ExactSizeIterator {
467         (self.arg_count + 1..self.local_decls.len()).map(Local::new)
468     }
469
470     #[inline]
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..)
473     }
474
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
482         } else {
483             assert_eq!(idx, stmts.len());
484             &block.terminator().source_info
485         }
486     }
487
488     /// Returns the return type; it always return first element from `local_decls` array.
489     #[inline]
490     pub fn return_ty(&self) -> Ty<'tcx> {
491         self.local_decls[RETURN_PLACE].ty
492     }
493
494     /// Returns the return type; it always return first element from `local_decls` array.
495     #[inline]
496     pub fn bound_return_ty(&self) -> ty::EarlyBinder<Ty<'tcx>> {
497         ty::EarlyBinder(self.local_decls[RETURN_PLACE].ty)
498     }
499
500     /// Gets the location of the terminator for the given block.
501     #[inline]
502     pub fn terminator_loc(&self, bb: BasicBlock) -> Location {
503         Location { block: bb, statement_index: self[bb].statements.len() }
504     }
505
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];
509         block_data
510             .statements
511             .get(statement_index)
512             .map(Either::Left)
513             .unwrap_or_else(|| Either::Right(block_data.terminator()))
514     }
515
516     #[inline]
517     pub fn yield_ty(&self) -> Option<Ty<'tcx>> {
518         self.generator.as_ref().and_then(|generator| generator.yield_ty)
519     }
520
521     #[inline]
522     pub fn generator_layout(&self) -> Option<&GeneratorLayout<'tcx>> {
523         self.generator.as_ref().and_then(|generator| generator.generator_layout.as_ref())
524     }
525
526     #[inline]
527     pub fn generator_drop(&self) -> Option<&Body<'tcx>> {
528         self.generator.as_ref().and_then(|generator| generator.generator_drop.as_ref())
529     }
530
531     #[inline]
532     pub fn generator_kind(&self) -> Option<GeneratorKind> {
533         self.generator.as_ref().map(|generator| generator.generator_kind)
534     }
535
536     #[inline]
537     pub fn should_skip(&self) -> bool {
538         let Some(injection_phase) = self.injection_phase else {
539             return false;
540         };
541         injection_phase > self.phase
542     }
543 }
544
545 #[derive(Copy, Clone, PartialEq, Eq, Debug, TyEncodable, TyDecodable, HashStable)]
546 pub enum Safety {
547     Safe,
548     /// Unsafe because of compiler-generated unsafe code, like `await` desugaring
549     BuiltinUnsafe,
550     /// Unsafe because of an unsafe fn
551     FnUnsafe,
552     /// Unsafe because of an `unsafe` block
553     ExplicitUnsafe(hir::HirId),
554 }
555
556 impl<'tcx> Index<BasicBlock> for Body<'tcx> {
557     type Output = BasicBlockData<'tcx>;
558
559     #[inline]
560     fn index(&self, index: BasicBlock) -> &BasicBlockData<'tcx> {
561         &self.basic_blocks[index]
562     }
563 }
564
565 impl<'tcx> IndexMut<BasicBlock> for Body<'tcx> {
566     #[inline]
567     fn index_mut(&mut self, index: BasicBlock) -> &mut BasicBlockData<'tcx> {
568         &mut self.basic_blocks.as_mut()[index]
569     }
570 }
571
572 #[derive(Copy, Clone, Debug, HashStable, TypeFoldable, TypeVisitable)]
573 pub enum ClearCrossCrate<T> {
574     Clear,
575     Set(T),
576 }
577
578 impl<T> ClearCrossCrate<T> {
579     pub fn as_ref(&self) -> ClearCrossCrate<&T> {
580         match self {
581             ClearCrossCrate::Clear => ClearCrossCrate::Clear,
582             ClearCrossCrate::Set(v) => ClearCrossCrate::Set(v),
583         }
584     }
585
586     pub fn assert_crate_local(self) -> T {
587         match self {
588             ClearCrossCrate::Clear => bug!("unwrapping cross-crate data"),
589             ClearCrossCrate::Set(v) => v,
590         }
591     }
592 }
593
594 const TAG_CLEAR_CROSS_CRATE_CLEAR: u8 = 0;
595 const TAG_CLEAR_CROSS_CRATE_SET: u8 = 1;
596
597 impl<E: TyEncoder, T: Encodable<E>> Encodable<E> for ClearCrossCrate<T> {
598     #[inline]
599     fn encode(&self, e: &mut E) {
600         if E::CLEAR_CROSS_CRATE {
601             return;
602         }
603
604         match *self {
605             ClearCrossCrate::Clear => TAG_CLEAR_CROSS_CRATE_CLEAR.encode(e),
606             ClearCrossCrate::Set(ref val) => {
607                 TAG_CLEAR_CROSS_CRATE_SET.encode(e);
608                 val.encode(e);
609             }
610         }
611     }
612 }
613 impl<D: TyDecoder, T: Decodable<D>> Decodable<D> for ClearCrossCrate<T> {
614     #[inline]
615     fn decode(d: &mut D) -> ClearCrossCrate<T> {
616         if D::CLEAR_CROSS_CRATE {
617             return ClearCrossCrate::Clear;
618         }
619
620         let discr = u8::decode(d);
621
622         match discr {
623             TAG_CLEAR_CROSS_CRATE_CLEAR => ClearCrossCrate::Clear,
624             TAG_CLEAR_CROSS_CRATE_SET => {
625                 let val = T::decode(d);
626                 ClearCrossCrate::Set(val)
627             }
628             tag => panic!("Invalid tag for ClearCrossCrate: {:?}", tag),
629         }
630     }
631 }
632
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.
641     pub span: Span,
642
643     /// The source scope, keeping track of which bindings can be
644     /// seen by debuginfo, active lint levels, `unsafe {...}`, etc.
645     pub scope: SourceScope,
646 }
647
648 impl SourceInfo {
649     #[inline]
650     pub fn outermost(span: Span) -> Self {
651         SourceInfo { span, scope: OUTERMOST_SOURCE_SCOPE }
652     }
653 }
654
655 ///////////////////////////////////////////////////////////////////////////
656 // Variables and temps
657
658 rustc_index::newtype_index! {
659     pub struct Local {
660         derive [HashStable]
661         DEBUG_FORMAT = "_{}",
662         const RETURN_PLACE = 0,
663     }
664 }
665
666 impl Atom for Local {
667     fn index(self) -> usize {
668         Idx::index(self)
669     }
670 }
671
672 /// Classifies locals into categories. See `Body::local_kind`.
673 #[derive(Clone, Copy, PartialEq, Eq, Debug, HashStable)]
674 pub enum LocalKind {
675     /// User-declared variable binding.
676     Var,
677     /// Compiler-introduced temporary.
678     Temp,
679     /// Function argument.
680     Arg,
681     /// Location of function's return value.
682     ReturnPointer,
683 }
684
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.
691     ///
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
701     ///     for diagnostics.
702     pub opt_match_place: Option<(Option<Place<'tcx>>, Span)>,
703     /// The span of the pattern in which this variable was bound.
704     pub pat_span: Span,
705 }
706
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.
714     RefForGuard,
715 }
716
717 TrivialTypeTraversalAndLiftImpls! { BindingForm<'tcx>, }
718
719 mod binding_form_impl {
720     use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
721     use rustc_query_system::ich::StableHashingContext;
722
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);
727
728             match self {
729                 Var(binding) => binding.hash_stable(hcx, hasher),
730                 ImplicitSelf(kind) => kind.hash_stable(hcx, hasher),
731                 RefForGuard => (),
732             }
733         }
734     }
735 }
736
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 }`.
740 ///
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.
749     ///
750     /// Examples include `{ ...; tail };` and `let _ = { ...; tail };`
751     /// but not e.g., `let _x = { ...; tail };`
752     pub tail_result_is_ignored: bool,
753
754     /// `Span` of the tail expression.
755     pub span: Span,
756 }
757
758 /// A MIR local.
759 ///
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`).
765     ///
766     /// Temporaries and the return place are always mutable.
767     pub mutability: Mutability,
768
769     // FIXME(matthewjasper) Don't store in this in `Body`
770     pub local_info: Option<Box<LocalInfo<'tcx>>>,
771
772     /// `true` if this is an internal local.
773     ///
774     /// These locals are not based on types in the source code and are only used
775     /// for a few desugarings at the moment.
776     ///
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.
782     ///
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
785     /// generator.
786     pub internal: bool,
787
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>,
794
795     /// The type of this local.
796     pub ty: Ty<'tcx>,
797
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>>,
804
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
808     /// of it.
809     ///
810     /// This is needed because the visibility source scope of locals within
811     /// a let-statement is weird.
812     ///
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.
816     ///
817     /// That's it, if we have a let-statement like the one in this
818     /// function:
819     ///
820     /// ```
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();
825     ///         y + 2
826     ///     };
827     ///     drop(x);
828     /// }
829     /// ```
830     ///
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.
834     ///
835     /// However, from a name lookup point of view, the scopes look more like
836     /// as if the let-statements were `match` expressions:
837     ///
838     /// ```
839     /// fn foo(x: &str) {
840     ///     match {
841     ///         match x.parse::<u32>().unwrap() {
842     ///             y => y + 2
843     ///         }
844     ///     } {
845     ///         x => drop(x)
846     ///     };
847     /// }
848     /// ```
849     ///
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`.
854     ///
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).
860     ///
861     /// The end result looks like this:
862     ///
863     /// ```text
864     /// ROOT SCOPE
865     ///  │{ argument x: &str }
866     ///  │
867     ///  │ │{ #[allow(unused_mut)] } // This is actually split into 2 scopes
868     ///  │ │                         // in practice because I'm lazy.
869     ///  │ │
870     ///  │ │← x.source_info.scope
871     ///  │ │← `x.parse().unwrap()`
872     ///  │ │
873     ///  │ │ │← y.source_info.scope
874     ///  │ │
875     ///  │ │ │{ let y: u32 }
876     ///  │ │ │
877     ///  │ │ │← y.var_debug_info.source_info.scope
878     ///  │ │ │← `y + 2`
879     ///  │
880     ///  │ │{ let x: u32 }
881     ///  │ │← x.var_debug_info.source_info.scope
882     ///  │ │← `drop(x)` // This accesses `x: u32`.
883     /// ```
884     pub source_info: SourceInfo,
885 }
886
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.
890 ///
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
896     ///
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 }`)
907     AggregateTemp,
908     /// A temporary created during the pass `Derefer` to avoid it's retagging
909     DerefTemp,
910 }
911
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) { ... }`,
917     /// - `let x = ...`,
918     /// - or `match ... { C(x) => ... }`
919     pub fn can_be_made_mutable(&self) -> bool {
920         matches!(
921             self.local_info,
922             Some(box LocalInfo::User(ClearCrossCrate::Set(
923                 BindingForm::Var(VarBindingForm {
924                     binding_mode: ty::BindingMode::BindByValue(_),
925                     opt_ty_info: _,
926                     opt_match_place: _,
927                     pat_span: _,
928                 }) | BindingForm::ImplicitSelf(ImplicitSelfKind::Imm),
929             )))
930         )
931     }
932
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 {
937         matches!(
938             self.local_info,
939             Some(box LocalInfo::User(ClearCrossCrate::Set(
940                 BindingForm::Var(VarBindingForm {
941                     binding_mode: ty::BindingMode::BindByValue(_),
942                     opt_ty_info: _,
943                     opt_match_place: _,
944                     pat_span: _,
945                 }) | BindingForm::ImplicitSelf(_),
946             )))
947         )
948     }
949
950     /// Returns `true` if this variable is a named variable or function
951     /// parameter declared by the user.
952     #[inline]
953     pub fn is_user_variable(&self) -> bool {
954         matches!(self.local_info, Some(box LocalInfo::User(_)))
955     }
956
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
959     /// match arm.
960     pub fn is_ref_for_guard(&self) -> bool {
961         matches!(
962             self.local_info,
963             Some(box LocalInfo::User(ClearCrossCrate::Set(BindingForm::RefForGuard)))
964         )
965     }
966
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 { .. }))
971     }
972
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,
978             _ => false,
979         }
980     }
981
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,
986             _ => (),
987         }
988         return false;
989     }
990
991     /// Returns `true` is the local is from a compiler desugaring, e.g.,
992     /// `__next` from a `for` loop.
993     #[inline]
994     pub fn from_compiler_desugaring(&self) -> bool {
995         self.source_info.span.desugaring_kind().is_some()
996     }
997
998     /// Creates a new `LocalDecl` for a temporary: mutable, non-internal.
999     #[inline]
1000     pub fn new(ty: Ty<'tcx>, span: Span) -> Self {
1001         Self::with_source_info(ty, SourceInfo::outermost(span))
1002     }
1003
1004     /// Like `LocalDecl::new`, but takes a `SourceInfo` instead of a `Span`.
1005     #[inline]
1006     pub fn with_source_info(ty: Ty<'tcx>, source_info: SourceInfo) -> Self {
1007         LocalDecl {
1008             mutability: Mutability::Mut,
1009             local_info: None,
1010             internal: false,
1011             is_block_tail: None,
1012             ty,
1013             user_ty: None,
1014             source_info,
1015         }
1016     }
1017
1018     /// Converts `self` into same `LocalDecl` except tagged as internal.
1019     #[inline]
1020     pub fn internal(mut self) -> Self {
1021         self.internal = true;
1022         self
1023     }
1024
1025     /// Converts `self` into same `LocalDecl` except tagged as immutable.
1026     #[inline]
1027     pub fn immutable(mut self) -> Self {
1028         self.mutability = Mutability::Not;
1029         self
1030     }
1031
1032     /// Converts `self` into same `LocalDecl` except tagged as internal temporary.
1033     #[inline]
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);
1037         self
1038     }
1039 }
1040
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.
1045     Place(Place<'tcx>),
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.
1052     Composite {
1053         /// Type of the original user variable.
1054         ty: Ty<'tcx>,
1055         /// All the parts of the original user variable, which ended
1056         /// up in disjoint places, due to optimizations.
1057         fragments: Vec<VarDebugInfoFragment<'tcx>>,
1058     },
1059 }
1060
1061 impl<'tcx> Debug for VarDebugInfoContents<'tcx> {
1062     fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1063         match self {
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)?;
1070                 }
1071                 write!(fmt, "}}")
1072             }
1073         }
1074     }
1075 }
1076
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>>,
1089
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>,
1094 }
1095
1096 impl Debug for VarDebugInfoFragment<'_> {
1097     fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1098         for elem in self.projection.iter() {
1099             match elem {
1100                 ProjectionElem::Field(field, _) => {
1101                     write!(fmt, ".{:?}", field.index())?;
1102                 }
1103                 _ => bug!("unsupported fragment projection `{:?}`", elem),
1104             }
1105         }
1106
1107         write!(fmt, " => {:?}", self.contents)
1108     }
1109 }
1110
1111 /// Debug information pertaining to a user variable.
1112 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable, TypeVisitable)]
1113 pub struct VarDebugInfo<'tcx> {
1114     pub name: Symbol,
1115
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,
1120
1121     /// Where the data for this user variable is to be found.
1122     pub value: VarDebugInfoContents<'tcx>,
1123 }
1124
1125 ///////////////////////////////////////////////////////////////////////////
1126 // BasicBlock
1127
1128 rustc_index::newtype_index! {
1129     /// A node in the MIR [control-flow graph][CFG].
1130     ///
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.
1134     ///
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.
1140     ///
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`].
1143     ///
1144     /// Read more about basic blocks in the [rustc-dev-guide][guide-mir].
1145     ///
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 {
1152         derive [HashStable]
1153         DEBUG_FORMAT = "bb{}",
1154         const START_BLOCK = 0,
1155     }
1156 }
1157
1158 impl BasicBlock {
1159     pub fn start_location(self) -> Location {
1160         Location { block: self, statement_index: 0 }
1161     }
1162 }
1163
1164 ///////////////////////////////////////////////////////////////////////////
1165 // BasicBlockData
1166
1167 /// Data for a basic block, including a list of its statements.
1168 ///
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>>,
1174
1175     /// Terminator for this block.
1176     ///
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>>,
1184
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,
1190 }
1191
1192 impl<'tcx> BasicBlockData<'tcx> {
1193     pub fn new(terminator: Option<Terminator<'tcx>>) -> BasicBlockData<'tcx> {
1194         BasicBlockData { statements: vec![], terminator, is_cleanup: false }
1195     }
1196
1197     /// Accessor for terminator.
1198     ///
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.
1201     #[inline]
1202     pub fn terminator(&self) -> &Terminator<'tcx> {
1203         self.terminator.as_ref().expect("invalid terminator state")
1204     }
1205
1206     #[inline]
1207     pub fn terminator_mut(&mut self) -> &mut Terminator<'tcx> {
1208         self.terminator.as_mut().expect("invalid terminator state")
1209     }
1210
1211     pub fn retain_statements<F>(&mut self, mut f: F)
1212     where
1213         F: FnMut(&mut Statement<'_>) -> bool,
1214     {
1215         for s in &mut self.statements {
1216             if !f(s) {
1217                 s.make_nop();
1218             }
1219         }
1220     }
1221
1222     pub fn expand_statements<F, I>(&mut self, mut f: F)
1223     where
1224         F: FnMut(&mut Statement<'tcx>) -> Option<I>,
1225         I: iter::TrustedLen<Item = Statement<'tcx>>,
1226     {
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.
1234                     *s = first;
1235
1236                     // Save the other statements for optimized splicing.
1237                     let remaining = new_stmts.size_hint().0;
1238                     if remaining > 0 {
1239                         splices.push((i + 1 + extra_stmts, new_stmts));
1240                         extra_stmts += remaining;
1241                     }
1242                 } else {
1243                     s.make_nop();
1244                 }
1245             }
1246         }
1247
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(
1256             gap.end,
1257             Statement { source_info: SourceInfo::outermost(DUMMY_SP), kind: StatementKind::Nop },
1258         );
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 {
1262                 gap.start -= 1;
1263                 gap.end -= 1;
1264                 self.statements.swap(gap.start, gap.end);
1265             }
1266             self.statements.splice(splice_start..splice_end, new_stmts);
1267             gap.end = splice_start;
1268         }
1269     }
1270
1271     pub fn visitable(&self, index: usize) -> &dyn MirVisitable<'tcx> {
1272         if index < self.statements.len() { &self.statements[index] } else { &self.terminator }
1273     }
1274
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)
1278     }
1279 }
1280
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 {
1286         use AssertKind::*;
1287         match self {
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"),
1304         }
1305     }
1306
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
1309     where
1310         O: Debug,
1311     {
1312         use AssertKind::*;
1313         match self {
1314             BoundsCheck { ref len, ref index } => write!(
1315                 f,
1316                 "\"index out of bounds: the length is {{}} but the index is {{}}\", {:?}, {:?}",
1317                 len, index
1318             ),
1319
1320             OverflowNeg(op) => {
1321                 write!(f, "\"attempt to negate `{{}}`, which would overflow\", {:?}", op)
1322             }
1323             DivisionByZero(op) => write!(f, "\"attempt to divide `{{}}` by zero\", {:?}", op),
1324             RemainderByZero(op) => write!(
1325                 f,
1326                 "\"attempt to calculate the remainder of `{{}}` with a divisor of zero\", {:?}",
1327                 op
1328             ),
1329             Overflow(BinOp::Add, l, r) => write!(
1330                 f,
1331                 "\"attempt to compute `{{}} + {{}}`, which would overflow\", {:?}, {:?}",
1332                 l, r
1333             ),
1334             Overflow(BinOp::Sub, l, r) => write!(
1335                 f,
1336                 "\"attempt to compute `{{}} - {{}}`, which would overflow\", {:?}, {:?}",
1337                 l, r
1338             ),
1339             Overflow(BinOp::Mul, l, r) => write!(
1340                 f,
1341                 "\"attempt to compute `{{}} * {{}}`, which would overflow\", {:?}, {:?}",
1342                 l, r
1343             ),
1344             Overflow(BinOp::Div, l, r) => write!(
1345                 f,
1346                 "\"attempt to compute `{{}} / {{}}`, which would overflow\", {:?}, {:?}",
1347                 l, r
1348             ),
1349             Overflow(BinOp::Rem, l, r) => write!(
1350                 f,
1351                 "\"attempt to compute the remainder of `{{}} % {{}}`, which would overflow\", {:?}, {:?}",
1352                 l, r
1353             ),
1354             Overflow(BinOp::Shr, _, r) => {
1355                 write!(f, "\"attempt to shift right by `{{}}`, which would overflow\", {:?}", r)
1356             }
1357             Overflow(BinOp::Shl, _, r) => {
1358                 write!(f, "\"attempt to shift left by `{{}}`, which would overflow\", {:?}", r)
1359             }
1360             _ => write!(f, "\"{}\"", self.description()),
1361         }
1362     }
1363 }
1364
1365 impl<O: fmt::Debug> fmt::Debug for AssertKind<O> {
1366     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1367         use AssertKind::*;
1368         match self {
1369             BoundsCheck { ref len, ref index } => write!(
1370                 f,
1371                 "index out of bounds: the length is {:?} but the index is {:?}",
1372                 len, index
1373             ),
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!(
1377                 f,
1378                 "attempt to calculate the remainder of `{:#?}` with a divisor of zero",
1379                 op
1380             ),
1381             Overflow(BinOp::Add, l, r) => {
1382                 write!(f, "attempt to compute `{:#?} + {:#?}`, which would overflow", l, r)
1383             }
1384             Overflow(BinOp::Sub, l, r) => {
1385                 write!(f, "attempt to compute `{:#?} - {:#?}`, which would overflow", l, r)
1386             }
1387             Overflow(BinOp::Mul, l, r) => {
1388                 write!(f, "attempt to compute `{:#?} * {:#?}`, which would overflow", l, r)
1389             }
1390             Overflow(BinOp::Div, l, r) => {
1391                 write!(f, "attempt to compute `{:#?} / {:#?}`, which would overflow", l, r)
1392             }
1393             Overflow(BinOp::Rem, l, r) => write!(
1394                 f,
1395                 "attempt to compute the remainder of `{:#?} % {:#?}`, which would overflow",
1396                 l, r
1397             ),
1398             Overflow(BinOp::Shr, _, r) => {
1399                 write!(f, "attempt to shift right by `{:#?}`, which would overflow", r)
1400             }
1401             Overflow(BinOp::Shl, _, r) => {
1402                 write!(f, "attempt to shift left by `{:#?}`, which would overflow", r)
1403             }
1404             _ => write!(f, "{}", self.description()),
1405         }
1406     }
1407 }
1408
1409 ///////////////////////////////////////////////////////////////////////////
1410 // Statements
1411
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>,
1417 }
1418
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
1424     }
1425
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 {
1429         Statement {
1430             source_info: self.source_info,
1431             kind: mem::replace(&mut self.kind, StatementKind::Nop),
1432         }
1433     }
1434 }
1435
1436 impl Debug for Statement<'_> {
1437     fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1438         use self::StatementKind::*;
1439         match self.kind {
1440             Assign(box (ref place, ref rv)) => write!(fmt, "{:?} = {:?}", place, rv),
1441             FakeRead(box (ref cause, ref place)) => {
1442                 write!(fmt, "FakeRead({:?}, {:?})", cause, place)
1443             }
1444             Retag(ref kind, ref place) => write!(
1445                 fmt,
1446                 "Retag({}{:?})",
1447                 match kind {
1448                     RetagKind::FnEntry => "[fn entry] ",
1449                     RetagKind::TwoPhase => "[2phase] ",
1450                     RetagKind::Raw => "[raw] ",
1451                     RetagKind::Default => "",
1452                 },
1453                 place,
1454             ),
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)
1459             }
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)
1463             }
1464             Coverage(box self::Coverage { ref kind, code_region: Some(ref rgn) }) => {
1465                 write!(fmt, "Coverage::{:?} for {:?}", kind, rgn)
1466             }
1467             Coverage(box ref coverage) => write!(fmt, "Coverage::{:?}", coverage.kind),
1468             Intrinsic(box ref intrinsic) => write!(fmt, "{intrinsic}"),
1469             Nop => write!(fmt, "nop"),
1470         }
1471     }
1472 }
1473
1474 impl<'tcx> StatementKind<'tcx> {
1475     pub fn as_assign_mut(&mut self) -> Option<&mut (Place<'tcx>, Rvalue<'tcx>)> {
1476         match self {
1477             StatementKind::Assign(x) => Some(x),
1478             _ => None,
1479         }
1480     }
1481
1482     pub fn as_assign(&self) -> Option<&(Place<'tcx>, Rvalue<'tcx>)> {
1483         match self {
1484             StatementKind::Assign(x) => Some(x),
1485             _ => None,
1486         }
1487     }
1488 }
1489
1490 ///////////////////////////////////////////////////////////////////////////
1491 // Places
1492
1493 impl<V, T> ProjectionElem<V, T> {
1494     /// Returns `true` if the target of this projection may refer to a different region of memory
1495     /// than the base.
1496     fn is_indirect(&self) -> bool {
1497         match self {
1498             Self::Deref => true,
1499
1500             Self::Field(_, _)
1501             | Self::Index(_)
1502             | Self::OpaqueCast(_)
1503             | Self::ConstantIndex { .. }
1504             | Self::Subslice { .. }
1505             | Self::Downcast(_, _) => false,
1506         }
1507     }
1508
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)
1512     }
1513
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)
1517     }
1518 }
1519
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<(), ()>;
1523
1524 rustc_index::newtype_index! {
1525     /// A [newtype'd][wrapper] index type in the MIR [control-flow graph][CFG]
1526     ///
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]
1531     ///
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
1535     pub struct Field {
1536         derive [HashStable]
1537         DEBUG_FORMAT = "field[{}]"
1538     }
1539 }
1540
1541 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1542 pub struct PlaceRef<'tcx> {
1543     pub local: Local,
1544     pub projection: &'tcx [PlaceElem<'tcx>],
1545 }
1546
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> {}
1552
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() }
1557     }
1558
1559     /// Returns `true` if this `Place` contains a `Deref` projection.
1560     ///
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())
1565     }
1566
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
1571         debug_assert!(
1572             self.projection.is_empty() || !self.projection[1..].contains(&PlaceElem::Deref)
1573         );
1574         self.projection.first() == Some(&PlaceElem::Deref)
1575     }
1576
1577     /// Finds the innermost `Local` from this `Place`, *if* it is either a local itself or
1578     /// a single deref of a local.
1579     #[inline(always)]
1580     pub fn local_or_deref_local(&self) -> Option<Local> {
1581         self.as_ref().local_or_deref_local()
1582     }
1583
1584     /// If this place represents a local variable like `_X` with no
1585     /// projections, return `Some(_X)`.
1586     #[inline(always)]
1587     pub fn as_local(&self) -> Option<Local> {
1588         self.as_ref().as_local()
1589     }
1590
1591     #[inline]
1592     pub fn as_ref(&self) -> PlaceRef<'tcx> {
1593         PlaceRef { local: self.local, projection: &self.projection }
1594     }
1595
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:
1599     /// - (a, .b)
1600     /// - (a.b, .c)
1601     ///
1602     /// Given a place without projections, the iterator is empty.
1603     #[inline]
1604     pub fn iter_projections(
1605         self,
1606     ) -> impl Iterator<Item = (PlaceRef<'tcx>, PlaceElem<'tcx>)> + DoubleEndedIterator {
1607         self.as_ref().iter_projections()
1608     }
1609
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() {
1614             return self;
1615         }
1616
1617         let mut v: Vec<PlaceElem<'tcx>>;
1618
1619         let new_projections = if self.projection.is_empty() {
1620             more_projections
1621         } else {
1622             v = Vec::with_capacity(self.projection.len() + more_projections.len());
1623             v.extend(self.projection);
1624             v.extend(more_projections);
1625             &v
1626         };
1627
1628         Place { local: self.local, projection: tcx.intern_place_elems(new_projections) }
1629     }
1630 }
1631
1632 impl From<Local> for Place<'_> {
1633     #[inline]
1634     fn from(local: Local) -> Self {
1635         Place { local, projection: List::empty() }
1636     }
1637 }
1638
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> {
1643         match *self {
1644             PlaceRef { local, projection: [] }
1645             | PlaceRef { local, projection: [ProjectionElem::Deref] } => Some(local),
1646             _ => None,
1647         }
1648     }
1649
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)
1654     }
1655
1656     /// If this place represents a local variable like `_X` with no
1657     /// projections, return `Some(_X)`.
1658     #[inline]
1659     pub fn as_local(&self) -> Option<Local> {
1660         match *self {
1661             PlaceRef { local, projection: [] } => Some(local),
1662             _ => None,
1663         }
1664     }
1665
1666     #[inline]
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))
1670         } else {
1671             None
1672         }
1673     }
1674
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:
1678     /// - (a, .b)
1679     /// - (a.b, .c)
1680     ///
1681     /// Given a place without projections, the iterator is empty.
1682     #[inline]
1683     pub fn iter_projections(
1684         self,
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] };
1688             (base, *proj)
1689         })
1690     }
1691 }
1692
1693 impl Debug for Place<'_> {
1694     fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1695         for elem in self.projection.iter().rev() {
1696             match elem {
1697                 ProjectionElem::OpaqueCast(_)
1698                 | ProjectionElem::Downcast(_, _)
1699                 | ProjectionElem::Field(_, _) => {
1700                     write!(fmt, "(").unwrap();
1701                 }
1702                 ProjectionElem::Deref => {
1703                     write!(fmt, "(*").unwrap();
1704                 }
1705                 ProjectionElem::Index(_)
1706                 | ProjectionElem::ConstantIndex { .. }
1707                 | ProjectionElem::Subslice { .. } => {}
1708             }
1709         }
1710
1711         write!(fmt, "{:?}", self.local)?;
1712
1713         for elem in self.projection.iter() {
1714             match elem {
1715                 ProjectionElem::OpaqueCast(ty) => {
1716                     write!(fmt, " as {})", ty)?;
1717                 }
1718                 ProjectionElem::Downcast(Some(name), _index) => {
1719                     write!(fmt, " as {})", name)?;
1720                 }
1721                 ProjectionElem::Downcast(None, index) => {
1722                     write!(fmt, " as variant#{:?})", index)?;
1723                 }
1724                 ProjectionElem::Deref => {
1725                     write!(fmt, ")")?;
1726                 }
1727                 ProjectionElem::Field(field, ty) => {
1728                     write!(fmt, ".{:?}: {:?})", field.index(), ty)?;
1729                 }
1730                 ProjectionElem::Index(ref index) => {
1731                     write!(fmt, "[{:?}]", index)?;
1732                 }
1733                 ProjectionElem::ConstantIndex { offset, min_length, from_end: false } => {
1734                     write!(fmt, "[{:?} of {:?}]", offset, min_length)?;
1735                 }
1736                 ProjectionElem::ConstantIndex { offset, min_length, from_end: true } => {
1737                     write!(fmt, "[-{:?} of {:?}]", offset, min_length)?;
1738                 }
1739                 ProjectionElem::Subslice { from, to, from_end: true } if to == 0 => {
1740                     write!(fmt, "[{:?}:]", from)?;
1741                 }
1742                 ProjectionElem::Subslice { from, to, from_end: true } if from == 0 => {
1743                     write!(fmt, "[:-{:?}]", to)?;
1744                 }
1745                 ProjectionElem::Subslice { from, to, from_end: true } => {
1746                     write!(fmt, "[{:?}:-{:?}]", from, to)?;
1747                 }
1748                 ProjectionElem::Subslice { from, to, from_end: false } => {
1749                     write!(fmt, "[{:?}..{:?}]", from, to)?;
1750                 }
1751             }
1752         }
1753
1754         Ok(())
1755     }
1756 }
1757
1758 ///////////////////////////////////////////////////////////////////////////
1759 // Scopes
1760
1761 rustc_index::newtype_index! {
1762     pub struct SourceScope {
1763         derive [HashStable]
1764         DEBUG_FORMAT = "scope[{}]",
1765         const OUTERMOST_SOURCE_SCOPE = 0,
1766     }
1767 }
1768
1769 impl SourceScope {
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>(
1774         self,
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() {
1781             trace!(?data);
1782             data = &source_scopes[data.parent_scope.unwrap()];
1783         }
1784         trace!(?data);
1785         match &data.local_data {
1786             ClearCrossCrate::Set(data) => Some(data.lint_root),
1787             ClearCrossCrate::Clear => None,
1788         }
1789     }
1790
1791     /// The instance this source scope was inlined from, if any.
1792     #[inline]
1793     pub fn inlined_instance<'tcx>(
1794         self,
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)
1802         } else {
1803             None
1804         }
1805     }
1806 }
1807
1808 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable, TypeVisitable)]
1809 pub struct SourceScopeData<'tcx> {
1810     pub span: Span,
1811     pub parent_scope: Option<SourceScope>,
1812
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)>,
1817
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>,
1822
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>,
1826 }
1827
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.
1833     pub safety: Safety,
1834 }
1835
1836 ///////////////////////////////////////////////////////////////////////////
1837 // Operands
1838
1839 impl<'tcx> Debug for Operand<'tcx> {
1840     fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1841         use self::Operand::*;
1842         match *self {
1843             Constant(ref a) => write!(fmt, "{:?}", a),
1844             Copy(ref place) => write!(fmt, "{:?}", place),
1845             Move(ref place) => write!(fmt, "move {:?}", place),
1846         }
1847     }
1848 }
1849
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(
1855         tcx: TyCtxt<'tcx>,
1856         def_id: DefId,
1857         substs: SubstsRef<'tcx>,
1858         span: Span,
1859     ) -> Self {
1860         let ty = tcx.mk_fn_def(def_id, substs);
1861         Operand::Constant(Box::new(Constant {
1862             span,
1863             user_ty: None,
1864             literal: ConstantKind::Val(ConstValue::ZeroSized, ty),
1865         }))
1866     }
1867
1868     pub fn is_move(&self) -> bool {
1869         matches!(self, Operand::Move(..))
1870     }
1871
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(
1875         tcx: TyCtxt<'tcx>,
1876         ty: Ty<'tcx>,
1877         val: Scalar,
1878         span: Span,
1879     ) -> Operand<'tcx> {
1880         debug_assert!({
1881             let param_env_and_ty = ty::ParamEnv::empty().and(ty);
1882             let type_size = tcx
1883                 .layout_of(param_env_and_ty)
1884                 .unwrap_or_else(|e| panic!("could not compute layout for {:?}: {:?}", ty, e))
1885                 .size;
1886             let scalar_size = match val {
1887                 Scalar::Int(int) => int.size(),
1888                 _ => panic!("Invalid scalar type {:?}", val),
1889             };
1890             scalar_size == type_size
1891         });
1892         Operand::Constant(Box::new(Constant {
1893             span,
1894             user_ty: None,
1895             literal: ConstantKind::Val(ConstValue::Scalar(val), ty),
1896         }))
1897     }
1898
1899     pub fn to_copy(&self) -> Self {
1900         match *self {
1901             Operand::Copy(_) | Operand::Constant(_) => self.clone(),
1902             Operand::Move(place) => Operand::Copy(place),
1903         }
1904     }
1905
1906     /// Returns the `Place` that is the target of this `Operand`, or `None` if this `Operand` is a
1907     /// constant.
1908     pub fn place(&self) -> Option<Place<'tcx>> {
1909         match self {
1910             Operand::Copy(place) | Operand::Move(place) => Some(*place),
1911             Operand::Constant(_) => None,
1912         }
1913     }
1914
1915     /// Returns the `Constant` that is the target of this `Operand`, or `None` if this `Operand` is a
1916     /// place.
1917     pub fn constant(&self) -> Option<&Constant<'tcx>> {
1918         match self {
1919             Operand::Constant(x) => Some(&**x),
1920             Operand::Copy(_) | Operand::Move(_) => None,
1921         }
1922     }
1923
1924     /// Gets the `ty::FnDef` from an operand if it's a constant function item.
1925     ///
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 }
1931     }
1932 }
1933
1934 ///////////////////////////////////////////////////////////////////////////
1935 /// Rvalues
1936
1937 impl<'tcx> Rvalue<'tcx> {
1938     /// Returns true if rvalue can be safely removed when the result is unused.
1939     #[inline]
1940     pub fn is_safe_to_remove(&self) -> bool {
1941         match self {
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,
1946
1947             Rvalue::Use(_)
1948             | Rvalue::CopyForDeref(_)
1949             | Rvalue::Repeat(_, _)
1950             | Rvalue::Ref(_, _, _)
1951             | Rvalue::ThreadLocalRef(_)
1952             | Rvalue::AddressOf(_, _)
1953             | Rvalue::Len(_)
1954             | Rvalue::Cast(
1955                 CastKind::IntToInt
1956                 | CastKind::FloatToInt
1957                 | CastKind::FloatToFloat
1958                 | CastKind::IntToFloat
1959                 | CastKind::FnPtrToPtr
1960                 | CastKind::PtrToPtr
1961                 | CastKind::Pointer(_)
1962                 | CastKind::PointerFromExposedAddress
1963                 | CastKind::DynStar,
1964                 _,
1965                 _,
1966             )
1967             | Rvalue::BinaryOp(_, _)
1968             | Rvalue::CheckedBinaryOp(_, _)
1969             | Rvalue::NullaryOp(_, _)
1970             | Rvalue::UnaryOp(_, _)
1971             | Rvalue::Discriminant(_)
1972             | Rvalue::Aggregate(_, _)
1973             | Rvalue::ShallowInitBox(_, _) => true,
1974         }
1975     }
1976 }
1977
1978 impl BorrowKind {
1979     pub fn allows_two_phase_borrow(&self) -> bool {
1980         match *self {
1981             BorrowKind::Shared | BorrowKind::Shallow | BorrowKind::Unique => false,
1982             BorrowKind::Mut { allow_two_phase_borrow } => allow_two_phase_borrow,
1983         }
1984     }
1985
1986     // FIXME: won't be used after diagnostic migration
1987     pub fn describe_mutability(&self) -> &str {
1988         match *self {
1989             BorrowKind::Shared | BorrowKind::Shallow | BorrowKind::Unique => "immutable",
1990             BorrowKind::Mut { .. } => "mutable",
1991         }
1992     }
1993 }
1994
1995 impl BinOp {
1996     pub fn is_checkable(self) -> bool {
1997         use self::BinOp::*;
1998         matches!(self, Add | Sub | Mul | Shl | Shr)
1999     }
2000 }
2001
2002 impl<'tcx> Debug for Rvalue<'tcx> {
2003     fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2004         use self::Rvalue::*;
2005
2006         match *self {
2007             Use(ref place) => write!(fmt, "{:?}", place),
2008             Repeat(ref a, b) => {
2009                 write!(fmt, "[{:?}; ", a)?;
2010                 pretty_print_const(b, fmt, false)?;
2011                 write!(fmt, "]")
2012             }
2013             Len(ref a) => write!(fmt, "Len({:?})", a),
2014             Cast(ref kind, ref place, ref ty) => {
2015                 write!(fmt, "{:?} as {:?} ({:?})", place, ty, kind)
2016             }
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)
2020             }
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))
2027             }),
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 ",
2033                 };
2034
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
2038                 });
2039                 let region = if print_region {
2040                     let mut region = region.to_string();
2041                     if !region.is_empty() {
2042                         region.push(' ');
2043                     }
2044                     region
2045                 } else {
2046                     // Do not even print 'static
2047                     String::new()
2048                 };
2049                 write!(fmt, "&{}{}{:?}", region, kind_str, place)
2050             }
2051
2052             CopyForDeref(ref place) => write!(fmt, "deref_copy {:#?}", place),
2053
2054             AddressOf(mutability, ref place) => {
2055                 let kind_str = match mutability {
2056                     Mutability::Mut => "mut",
2057                     Mutability::Not => "const",
2058                 };
2059
2060                 write!(fmt, "&raw {} {:?}", kind_str, place)
2061             }
2062
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);
2068                     }
2069                     tuple_fmt.finish()
2070                 };
2071
2072                 match **kind {
2073                     AggregateKind::Array(_) => write!(fmt, "{:?}", places),
2074
2075                     AggregateKind::Tuple => {
2076                         if places.is_empty() {
2077                             write!(fmt, "()")
2078                         } else {
2079                             fmt_tuple(fmt, "")
2080                         }
2081                     }
2082
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)?
2089                                 .into_buffer();
2090
2091                             match variant_def.ctor_kind() {
2092                                 Some(CtorKind::Const) => fmt.write_str(&name),
2093                                 Some(CtorKind::Fn) => fmt_tuple(fmt, &name),
2094                                 None => {
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);
2098                                     }
2099                                     struct_fmt.finish()
2100                                 }
2101                             }
2102                         })
2103                     }
2104
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();
2108                             format!(
2109                                 "[closure@{}]",
2110                                 tcx.def_path_str_with_substs(def_id.to_def_id(), substs),
2111                             )
2112                         } else {
2113                             let span = tcx.def_span(def_id);
2114                             format!(
2115                                 "[closure@{}]",
2116                                 tcx.sess.source_map().span_to_diagnostic_string(span)
2117                             )
2118                         };
2119                         let mut struct_fmt = fmt.debug_struct(&name);
2120
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);
2126                             }
2127                         }
2128
2129                         struct_fmt.finish()
2130                     }),
2131
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);
2135
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);
2141                             }
2142                         }
2143
2144                         struct_fmt.finish()
2145                     }),
2146                 }
2147             }
2148
2149             ShallowInitBox(ref place, ref ty) => {
2150                 write!(fmt, "ShallowInitBox({:?}, {:?})", place, ty)
2151             }
2152         }
2153     }
2154 }
2155
2156 ///////////////////////////////////////////////////////////////////////////
2157 /// Constants
2158 ///
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`!
2162
2163 #[derive(Clone, Copy, PartialEq, TyEncodable, TyDecodable, Hash, HashStable)]
2164 #[derive(TypeFoldable, TypeVisitable)]
2165 pub struct Constant<'tcx> {
2166     pub span: Span,
2167
2168     /// Optional user-given type: for something like
2169     /// `collect::<Vec<_>>`, this would be present and would
2170     /// indicate that `Vec<_>` was explicitly specified.
2171     ///
2172     /// Needed for NLL to impose user-given type constraints.
2173     pub user_ty: Option<UserTypeAnnotationIndex>,
2174
2175     pub literal: ConstantKind<'tcx>,
2176 }
2177
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>),
2183
2184     /// An unevaluated mir constant which is not part of the type system.
2185     Unevaluated(UnevaluatedConst<'tcx>, Ty<'tcx>),
2186
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>),
2190 }
2191
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));
2198                     Some(def_id)
2199                 }
2200                 _ => None,
2201             },
2202             _ => None,
2203         }
2204     }
2205     #[inline]
2206     pub fn ty(&self) -> Ty<'tcx> {
2207         self.literal.ty()
2208     }
2209 }
2210
2211 impl<'tcx> ConstantKind<'tcx> {
2212     #[inline(always)]
2213     pub fn ty(&self) -> Ty<'tcx> {
2214         match self {
2215             ConstantKind::Ty(c) => c.ty(),
2216             ConstantKind::Val(_, ty) | ConstantKind::Unevaluated(_, ty) => *ty,
2217         }
2218     }
2219
2220     #[inline]
2221     pub fn try_to_value(self, tcx: TyCtxt<'tcx>) -> Option<interpret::ConstValue<'tcx>> {
2222         match self {
2223             ConstantKind::Ty(c) => match c.kind() {
2224                 ty::ConstKind::Value(valtree) => Some(tcx.valtree_to_const_val((c.ty(), valtree))),
2225                 _ => None,
2226             },
2227             ConstantKind::Val(val, _) => Some(val),
2228             ConstantKind::Unevaluated(..) => None,
2229         }
2230     }
2231
2232     #[inline]
2233     pub fn try_to_scalar(self) -> Option<Scalar> {
2234         match self {
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,
2239                 },
2240                 _ => None,
2241             },
2242             ConstantKind::Val(val, _) => val.try_to_scalar(),
2243             ConstantKind::Unevaluated(..) => None,
2244         }
2245     }
2246
2247     #[inline]
2248     pub fn try_to_scalar_int(self) -> Option<ScalarInt> {
2249         Some(self.try_to_scalar()?.assert_int())
2250     }
2251
2252     #[inline]
2253     pub fn try_to_bits(self, size: Size) -> Option<u128> {
2254         self.try_to_scalar_int()?.to_bits(size).ok()
2255     }
2256
2257     #[inline]
2258     pub fn try_to_bool(self) -> Option<bool> {
2259         self.try_to_scalar_int()?.try_into().ok()
2260     }
2261
2262     #[inline]
2263     pub fn eval(self, tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>) -> Self {
2264         match self {
2265             Self::Ty(c) => {
2266                 if let Some(val) = c.kind().try_eval_for_mir(tcx, param_env) {
2267                     match val {
2268                         Ok(val) => Self::Val(val, c.ty()),
2269                         Err(_) => Self::Ty(tcx.const_error(self.ty())),
2270                     }
2271                 } else {
2272                     self
2273                 }
2274             }
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))
2283                     }
2284                 }
2285             }
2286         }
2287     }
2288
2289     /// Panics if the value cannot be evaluated or doesn't contain a valid integer of the given type.
2290     #[inline]
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))
2294     }
2295
2296     #[inline]
2297     pub fn try_eval_bits(
2298         &self,
2299         tcx: TyCtxt<'tcx>,
2300         param_env: ty::ParamEnv<'tcx>,
2301         ty: Ty<'tcx>,
2302     ) -> Option<u128> {
2303         match self {
2304             Self::Ty(ct) => ct.try_eval_bits(tcx, param_env, ty),
2305             Self::Val(val, t) => {
2306                 assert_eq!(*t, ty);
2307                 let size =
2308                     tcx.layout_of(param_env.with_reveal_all_normalized(tcx).and(ty)).ok()?.size;
2309                 val.try_to_bits(size)
2310             }
2311             Self::Unevaluated(uneval, ty) => {
2312                 match tcx.const_eval_resolve(param_env, *uneval, None) {
2313                     Ok(val) => {
2314                         let size = tcx
2315                             .layout_of(param_env.with_reveal_all_normalized(tcx).and(*ty))
2316                             .ok()?
2317                             .size;
2318                         val.try_to_bits(size)
2319                     }
2320                     Err(_) => None,
2321                 }
2322             }
2323         }
2324     }
2325
2326     #[inline]
2327     pub fn try_eval_bool(&self, tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>) -> Option<bool> {
2328         match self {
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(),
2334                     Err(_) => None,
2335                 }
2336             }
2337         }
2338     }
2339
2340     #[inline]
2341     pub fn try_eval_usize(&self, tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>) -> Option<u64> {
2342         match self {
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),
2348                     Err(_) => None,
2349                 }
2350             }
2351         }
2352     }
2353
2354     #[inline]
2355     pub fn from_value(val: ConstValue<'tcx>, ty: Ty<'tcx>) -> Self {
2356         Self::Val(val, ty)
2357     }
2358
2359     pub fn from_bits(
2360         tcx: TyCtxt<'tcx>,
2361         bits: u128,
2362         param_env_ty: ty::ParamEnvAnd<'tcx, Ty<'tcx>>,
2363     ) -> Self {
2364         let size = tcx
2365             .layout_of(param_env_ty)
2366             .unwrap_or_else(|e| {
2367                 bug!("could not compute layout for {:?}: {:?}", param_env_ty.value, e)
2368             })
2369             .size;
2370         let cv = ConstValue::Scalar(Scalar::from_uint(bits, size));
2371
2372         Self::Val(cv, param_env_ty.value)
2373     }
2374
2375     #[inline]
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)
2379     }
2380
2381     #[inline]
2382     pub fn zero_sized(ty: Ty<'tcx>) -> Self {
2383         let cv = ConstValue::ZeroSized;
2384         Self::Val(cv, ty)
2385     }
2386
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))
2390     }
2391
2392     #[inline]
2393     pub fn from_scalar(_tcx: TyCtxt<'tcx>, s: Scalar, ty: Ty<'tcx>) -> Self {
2394         let val = ConstValue::Scalar(s);
2395         Self::Val(val, ty)
2396     }
2397
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(
2401         tcx: TyCtxt<'tcx>,
2402         def_id: LocalDefId,
2403         param_env: ty::ParamEnv<'tcx>,
2404     ) -> Self {
2405         Self::from_opt_const_arg_anon_const(tcx, ty::WithOptConstParam::unknown(def_id), param_env)
2406     }
2407
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,
2413             _ => span_bug!(
2414                 tcx.def_span(def_id.to_def_id()),
2415                 "from_inline_const can only process anonymous constants"
2416             ),
2417         };
2418         let expr = &tcx.hir().body(body_id).value;
2419         let ty = tcx.typeck(def_id).node_type(hir_id);
2420
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 })
2426                 }
2427                 _ => None,
2428             },
2429             _ => None,
2430         };
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
2433             // mir.
2434             match tcx.at(expr.span).lit_to_mir_constant(lit_input) {
2435                 Ok(c) => return c,
2436                 Err(_) => {}
2437             }
2438         }
2439
2440         let typeck_root_def_id = tcx.typeck_root_def_id(def_id.to_def_id());
2441         let parent_substs =
2442             tcx.erase_regions(InternalSubsts::identity_for_item(tcx, typeck_root_def_id));
2443         let substs =
2444             ty::InlineConstSubsts::new(tcx, ty::InlineConstSubstsParts { parent_substs, ty })
2445                 .substs;
2446
2447         let uneval = UnevaluatedConst {
2448             def: ty::WithOptConstParam::unknown(def_id).to_global(),
2449             substs,
2450             promoted: None,
2451         };
2452         debug_assert!(!uneval.has_free_regions());
2453
2454         Self::Unevaluated(uneval, ty)
2455     }
2456
2457     #[instrument(skip(tcx), level = "debug", ret)]
2458     fn from_opt_const_arg_anon_const(
2459         tcx: TyCtxt<'tcx>,
2460         def: ty::WithOptConstParam<LocalDefId>,
2461         param_env: ty::ParamEnv<'tcx>,
2462     ) -> Self {
2463         let body_id = match tcx.hir().get_by_def_id(def.did) {
2464             hir::Node::AnonConst(ac) => ac.body,
2465             _ => span_bug!(
2466                 tcx.def_span(def.did.to_def_id()),
2467                 "from_anon_const can only process anonymous constants"
2468             ),
2469         };
2470
2471         let expr = &tcx.hir().body(body_id).value;
2472         debug!(?expr);
2473
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()
2479             }
2480             _ => expr,
2481         };
2482         debug!("expr.kind: {:?}", expr.kind);
2483
2484         let ty = tcx.type_of(def.def_id_for_type_of());
2485         debug!(?ty);
2486
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.
2491         //
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};
2495         match expr.kind {
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);
2504                 debug!(?ty_const);
2505
2506                 return Self::Ty(ty_const);
2507             }
2508             _ => {}
2509         }
2510
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())
2515             } else {
2516                 tcx.mk_substs(Vec::<GenericArg<'tcx>>::new().into_iter())
2517             }
2518         } else {
2519             tcx.mk_substs(Vec::<GenericArg<'tcx>>::new().into_iter())
2520         };
2521         debug!(?parent_substs);
2522
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()));
2526         debug!(?substs);
2527
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);
2532
2533         match tcx.const_eval_resolve(param_env, uneval, Some(span)) {
2534             Ok(val) => {
2535                 debug!("evaluated const value");
2536                 Self::Val(val, ty)
2537             }
2538             Err(_) => {
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
2542                 Self::Unevaluated(
2543                     UnevaluatedConst {
2544                         def: def.to_global(),
2545                         substs: InternalSubsts::identity_for_item(tcx, def.did.to_def_id()),
2546                         promoted: None,
2547                     },
2548                     ty,
2549                 )
2550             }
2551         }
2552     }
2553
2554     pub fn from_const(c: ty::Const<'tcx>, tcx: TyCtxt<'tcx>) -> Self {
2555         match c.kind() {
2556             ty::ConstKind::Value(valtree) => {
2557                 let const_val = tcx.valtree_to_const_val((c.ty(), valtree));
2558                 Self::Val(const_val, c.ty())
2559             }
2560             ty::ConstKind::Unevaluated(uv) => Self::Unevaluated(uv.expand(), c.ty()),
2561             _ => Self::Ty(c),
2562         }
2563     }
2564 }
2565
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>,
2573 }
2574
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.
2578     #[inline]
2579     pub fn shrink(self) -> ty::UnevaluatedConst<'tcx> {
2580         ty::UnevaluatedConst { def: self.def, substs: self.substs }
2581     }
2582 }
2583
2584 impl<'tcx> UnevaluatedConst<'tcx> {
2585     #[inline]
2586     pub fn new(
2587         def: ty::WithOptConstParam<DefId>,
2588         substs: SubstsRef<'tcx>,
2589     ) -> UnevaluatedConst<'tcx> {
2590         UnevaluatedConst { def, substs, promoted: Default::default() }
2591     }
2592 }
2593
2594 /// A collection of projections into user types.
2595 ///
2596 /// They are projections because a binding can occur a part of a
2597 /// parent pattern that has been ascribed a type.
2598 ///
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.
2601 ///
2602 /// An example:
2603 ///
2604 /// ```ignore (illustrative)
2605 /// struct S<'a>((i32, &'a str), String);
2606 /// let S((_, w): (i32, &'static str), _): S = ...;
2607 /// //    ------  ^^^^^^^^^^^^^^^^^^^ (1)
2608 /// //  ---------------------------------  ^ (2)
2609 /// ```
2610 ///
2611 /// The highlights labelled `(1)` show the subpattern `(_, w)` being
2612 /// ascribed the type `(i32, &'static str)`.
2613 ///
2614 /// The highlights labelled `(2)` show the whole pattern being
2615 /// ascribed the type `S`.
2616 ///
2617 /// In this example, when we descend to `w`, we will have built up the
2618 /// following two projected types:
2619 ///
2620 ///   * base: `S`,                   projection: `(base.0).1`
2621 ///   * base: `(i32, &'static str)`, projection: `base.1`
2622 ///
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:
2625 /// &'static str`.
2626 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable, TypeVisitable)]
2627 pub struct UserTypeProjections {
2628     pub contents: Vec<(UserTypeProjection, Span)>,
2629 }
2630
2631 impl<'tcx> UserTypeProjections {
2632     pub fn none() -> Self {
2633         UserTypeProjections { contents: vec![] }
2634     }
2635
2636     pub fn is_empty(&self) -> bool {
2637         self.contents.is_empty()
2638     }
2639
2640     pub fn projections_and_spans(
2641         &self,
2642     ) -> impl Iterator<Item = &(UserTypeProjection, Span)> + ExactSizeIterator {
2643         self.contents.iter()
2644     }
2645
2646     pub fn projections(&self) -> impl Iterator<Item = &UserTypeProjection> + ExactSizeIterator {
2647         self.contents.iter().map(|&(ref user_type, _span)| user_type)
2648     }
2649
2650     pub fn push_projection(mut self, user_ty: &UserTypeProjection, span: Span) -> Self {
2651         self.contents.push((user_ty.clone(), span));
2652         self
2653     }
2654
2655     fn map_projections(
2656         mut self,
2657         mut f: impl FnMut(UserTypeProjection) -> UserTypeProjection,
2658     ) -> Self {
2659         self.contents = self.contents.into_iter().map(|(proj, span)| (f(proj), span)).collect();
2660         self
2661     }
2662
2663     pub fn index(self) -> Self {
2664         self.map_projections(|pat_ty_proj| pat_ty_proj.index())
2665     }
2666
2667     pub fn subslice(self, from: u64, to: u64) -> Self {
2668         self.map_projections(|pat_ty_proj| pat_ty_proj.subslice(from, to))
2669     }
2670
2671     pub fn deref(self) -> Self {
2672         self.map_projections(|pat_ty_proj| pat_ty_proj.deref())
2673     }
2674
2675     pub fn leaf(self, field: Field) -> Self {
2676         self.map_projections(|pat_ty_proj| pat_ty_proj.leaf(field))
2677     }
2678
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))
2681     }
2682 }
2683
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.
2691 ///
2692 /// Examples:
2693 ///
2694 /// * `let x: T = ...` -- here, the `projs` vector is empty.
2695 ///
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>,
2703 }
2704
2705 impl Copy for ProjectionKind {}
2706
2707 impl UserTypeProjection {
2708     pub(crate) fn index(mut self) -> Self {
2709         self.projs.push(ProjectionElem::Index(()));
2710         self
2711     }
2712
2713     pub(crate) fn subslice(mut self, from: u64, to: u64) -> Self {
2714         self.projs.push(ProjectionElem::Subslice { from, to, from_end: true });
2715         self
2716     }
2717
2718     pub(crate) fn deref(mut self) -> Self {
2719         self.projs.push(ProjectionElem::Deref);
2720         self
2721     }
2722
2723     pub(crate) fn leaf(mut self, field: Field) -> Self {
2724         self.projs.push(ProjectionElem::Field(field, ()));
2725         self
2726     }
2727
2728     pub(crate) fn variant(
2729         mut self,
2730         adt_def: AdtDef<'_>,
2731         variant_index: VariantIdx,
2732         field: Field,
2733     ) -> Self {
2734         self.projs.push(ProjectionElem::Downcast(
2735             Some(adt_def.variant(variant_index).name),
2736             variant_index,
2737         ));
2738         self.projs.push(ProjectionElem::Field(field, ()));
2739         self
2740     }
2741 }
2742
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)?,
2748         })
2749     }
2750 }
2751
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.
2756     }
2757 }
2758
2759 rustc_index::newtype_index! {
2760     pub struct Promoted {
2761         derive [HashStable]
2762         DEBUG_FORMAT = "promoted[{}]"
2763     }
2764 }
2765
2766 impl<'tcx> Debug for Constant<'tcx> {
2767     fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2768         write!(fmt, "{}", self)
2769     }
2770 }
2771
2772 impl<'tcx> Display for Constant<'tcx> {
2773     fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2774         match self.ty().kind() {
2775             ty::FnDef(..) => {}
2776             _ => write!(fmt, "const ")?,
2777         }
2778         Display::fmt(&self.literal, fmt)
2779     }
2780 }
2781
2782 impl<'tcx> Display for ConstantKind<'tcx> {
2783     fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2784         match *self {
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("_")?;
2790                 Ok(())
2791             }
2792         }
2793     }
2794 }
2795
2796 fn pretty_print_const<'tcx>(
2797     c: ty::Const<'tcx>,
2798     fmt: &mut Formatter<'_>,
2799     print_types: bool,
2800 ) -> fmt::Result {
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())?;
2808         Ok(())
2809     })
2810 }
2811
2812 fn pretty_print_byte_str(fmt: &mut Formatter<'_>, byte_str: &[u8]) -> fmt::Result {
2813     write!(fmt, "b\"{}\"", byte_str.escape_ascii())
2814 }
2815
2816 fn comma_sep<'tcx>(fmt: &mut Formatter<'_>, elems: Vec<ConstantKind<'tcx>>) -> fmt::Result {
2817     let mut first = true;
2818     for elem in elems {
2819         if !first {
2820             fmt.write_str(", ")?;
2821         }
2822         fmt.write_str(&format!("{}", elem))?;
2823         first = false;
2824     }
2825     Ok(())
2826 }
2827
2828 // FIXME: Move that into `mir/pretty.rs`.
2829 fn pretty_print_const_value<'tcx>(
2830     ct: ConstValue<'tcx>,
2831     ty: Ty<'tcx>,
2832     fmt: &mut Formatter<'_>,
2833     print_ty: bool,
2834 ) -> fmt::Result {
2835     use crate::ty::print::PrettyPrinter;
2836
2837     ty::tls::with(|tcx| {
2838         let ct = tcx.lift(ct).unwrap();
2839         let ty = tcx.lift(ty).unwrap();
2840
2841         if tcx.sess.verbose() {
2842             fmt.write_str(&format!("ConstValue({:?}: {})", ct, ty))?;
2843             return Ok(());
2844         }
2845
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() {
2851                     ty::Slice(t) => {
2852                         if *t == u8_type {
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.
2856                             let byte_str = data
2857                                 .inner()
2858                                 .inspect_with_uninit_and_ptr_outside_interpreter(start..end);
2859                             pretty_print_byte_str(fmt, byte_str)?;
2860                             return Ok(());
2861                         }
2862                     }
2863                     ty::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.
2867                         let slice = data
2868                             .inner()
2869                             .inspect_with_uninit_and_ptr_outside_interpreter(start..end);
2870                         fmt.write_str(&format!("{:?}", String::from_utf8_lossy(slice)))?;
2871                         return Ok(());
2872                     }
2873                     _ => {}
2874                 }
2875             }
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)?;
2883                 return Ok(());
2884             }
2885             // Aggregates, printed as array/tuple/struct/variant construction syntax.
2886             //
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)
2892             //
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)),
2900                 ) {
2901                     let fields = contents.fields.iter().copied().collect::<Vec<_>>();
2902                     match *ty.kind() {
2903                         ty::Array(..) => {
2904                             fmt.write_str("[")?;
2905                             comma_sep(fmt, fields)?;
2906                             fmt.write_str("]")?;
2907                         }
2908                         ty::Tuple(..) => {
2909                             fmt.write_str("(")?;
2910                             comma_sep(fmt, fields)?;
2911                             if contents.fields.len() == 1 {
2912                                 fmt.write_str(",")?;
2913                             }
2914                             fmt.write_str(")")?;
2915                         }
2916                         ty::Adt(def, _) if def.variants().is_empty() => {
2917                             fmt.write_str(&format!("{{unreachable(): {}}}", ty))?;
2918                         }
2919                         ty::Adt(def, substs) => {
2920                             let variant_idx = contents
2921                                 .variant
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())?;
2929
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(")")?;
2936                                 }
2937                                 None => {
2938                                     fmt.write_str(" {{ ")?;
2939                                     let mut first = true;
2940                                     for (field_def, field) in iter::zip(&variant_def.fields, fields)
2941                                     {
2942                                         if !first {
2943                                             fmt.write_str(", ")?;
2944                                         }
2945                                         fmt.write_str(&format!("{}: {}", field_def.name, field))?;
2946                                         first = false;
2947                                     }
2948                                     fmt.write_str(" }}")?;
2949                                 }
2950                             }
2951                         }
2952                         _ => unreachable!(),
2953                     }
2954                     return Ok(());
2955                 } else {
2956                     // Fall back to debug pretty printing for invalid constants.
2957                     fmt.write_str(&format!("{:?}", ct))?;
2958                     if print_ty {
2959                         fmt.write_str(&format!(": {}", ty))?;
2960                     }
2961                     return Ok(());
2962                 };
2963             }
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())?;
2970                 return Ok(());
2971             }
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())?;
2977                 return Ok(());
2978             }
2979             // FIXME(oli-obk): also pretty print arrays and other aggregate constants by reading
2980             // their fields instead of just dumping the memory.
2981             _ => {}
2982         }
2983         // fallback
2984         fmt.write_str(&format!("{:?}", ct))?;
2985         if print_ty {
2986             fmt.write_str(&format!(": {}", ty))?;
2987         }
2988         Ok(())
2989     })
2990 }
2991
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
2994 /// terminator.
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,
2999
3000     pub statement_index: usize,
3001 }
3002
3003 impl fmt::Debug for Location {
3004     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
3005         write!(fmt, "{:?}[{}]", self.block, self.statement_index)
3006     }
3007 }
3008
3009 impl Location {
3010     pub const START: Location = Location { block: START_BLOCK, statement_index: 0 };
3011
3012     /// Returns the location immediately after this one within the enclosing block.
3013     ///
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 }
3018     }
3019
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 {
3025             return true;
3026         }
3027
3028         let predecessors = body.basic_blocks.predecessors();
3029
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();
3033
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());
3038             } else {
3039                 continue;
3040             }
3041
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 {
3045                 return true;
3046             }
3047         }
3048
3049         false
3050     }
3051
3052     pub fn dominates(&self, other: Location, dominators: &Dominators<BasicBlock>) -> bool {
3053         if self.block == other.block {
3054             self.statement_index <= other.statement_index
3055         } else {
3056             dominators.is_dominated_by(other.block, self.block)
3057         }
3058     }
3059 }
3060
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"))]
3063 mod size_asserts {
3064     use super::*;
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
3074 }