Skip to main content

rustc_mir_build/builder/
mod.rs

1//! This module used to be named `build`, but that was causing GitHub's
2//! "Go to file" feature to silently ignore all files in the module, probably
3//! because it assumes that "build" is a build-output directory.
4//! See <https://github.com/rust-lang/rust/pull/134365>.
5//!
6//! ## The `let this = self;` idiom (LET_THIS_SELF)
7//!
8//! Throughout MIR building there are several places where a `Builder` method
9//! needs to borrow `self`, and then re-expose it to a closure as `|this|`.
10//!
11//! In complex builder methods, potentially with multiple levels of nesting, it
12//! would thus become necessary to mentally keep track of whether the builder
13//! is `self` (at the top level) or `this` (nested in a closure), or to replace
14//! one with the other when moving code in or out of a closure.
15//!
16//! (The borrow checker will prevent incorrect usage, but having to go back and
17//! satisfy the borrow checker still creates contributor friction.)
18//!
19//! To reduce that friction, some builder methods therefore start with
20//! `let this = self;` or similar, allowing subsequent code to uniformly refer
21//! to the builder as `this` (and never `self`), even when not nested.
22
23use itertools::Itertools;
24use rustc_abi::{ExternAbi, FieldIdx};
25use rustc_apfloat::Float;
26use rustc_apfloat::ieee::{Double, Half, Quad, Single};
27use rustc_data_structures::fx::FxHashMap;
28use rustc_data_structures::sorted_map::SortedIndexMultiMap;
29use rustc_errors::ErrorGuaranteed;
30use rustc_hir::def::DefKind;
31use rustc_hir::def_id::LocalDefId;
32use rustc_hir::{self as hir, BindingMode, ByRef, HirId, ItemLocalId, Node, find_attr};
33use rustc_index::bit_set::GrowableBitSet;
34use rustc_index::{Idx, IndexSlice, IndexVec};
35use rustc_infer::infer::{InferCtxt, TyCtxtInferExt};
36use rustc_middle::hir::place::PlaceBase as HirPlaceBase;
37use rustc_middle::middle::region;
38use rustc_middle::mir::*;
39use rustc_middle::thir::{self, ExprId, LocalVarId, Param, ParamId, PatKind, Thir};
40use rustc_middle::ty::{self, ScalarInt, Ty, TyCtxt, TypeVisitableExt, TypingMode};
41use rustc_span::{Span, Symbol, bug, span_bug};
42
43use crate::builder::expr::as_place::PlaceBuilder;
44use crate::builder::scope::LintLevel;
45
46pub(crate) fn closure_saved_names_of_captured_variables<'tcx>(
47    tcx: TyCtxt<'tcx>,
48    def_id: LocalDefId,
49) -> IndexVec<FieldIdx, Symbol> {
50    tcx.closure_captures(def_id)
51        .iter()
52        .map(|captured_place| {
53            let name = captured_place.to_symbol();
54            match captured_place.info.capture_kind {
55                ty::UpvarCapture::ByValue | ty::UpvarCapture::ByUse => name,
56                ty::UpvarCapture::ByRef(..) => Symbol::intern(&::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("_ref__{0}", name))
    })format!("_ref__{name}")),
57            }
58        })
59        .collect()
60}
61
62/// Create the MIR for a given `DefId`, including unreachable code.
63///
64/// This is the implementation of hook `build_mir_inner_impl`, which should only
65/// be called by the query `mir_built`.
66pub(crate) fn build_mir_inner_impl<'tcx>(tcx: TyCtxt<'tcx>, def: LocalDefId) -> Body<'tcx> {
67    tcx.ensure_done().thir_abstract_const(def);
68    if let Err(e) = tcx.ensure_result().check_match(def) {
69        return construct_error(tcx, def, e);
70    }
71
72    if let Err(err) = tcx.ensure_result().check_tail_calls(def) {
73        return construct_error(tcx, def, err);
74    }
75
76    let body = match tcx.thir_body(def) {
77        Err(error_reported) => construct_error(tcx, def, error_reported),
78        Ok((thir, expr)) => {
79            let build_mir = |thir: &Thir<'tcx>| match thir.body_type {
80                thir::BodyTy::Fn(fn_sig) => construct_fn(tcx, def, thir, expr, fn_sig),
81                thir::BodyTy::Const(ty) | thir::BodyTy::GlobalAsm(ty) => {
82                    construct_const(tcx, def, thir, expr, ty)
83                }
84            };
85
86            // Don't steal here, instead steal in unsafeck. This is so that
87            // pattern inline constants can be evaluated as part of building the
88            // THIR of the parent function without a cycle.
89            build_mir(&thir.borrow())
90        }
91    };
92
93    // The borrow checker will replace all the regions here with its own
94    // inference variables. There's no point having non-erased regions here.
95    // The exception is `body.user_type_annotations`, which is used unmodified
96    // by borrow checking.
97    if true {
    if !!(body.local_decls.has_free_regions() ||
                                body.basic_blocks.has_free_regions() ||
                            body.var_debug_info.has_free_regions() ||
                        body.yield_ty().has_free_regions()) {
        {
            ::core::panicking::panic_fmt(format_args!("Unexpected free regions in MIR: {0:?}",
                    body));
        }
    };
};debug_assert!(
98        !(body.local_decls.has_free_regions()
99            || body.basic_blocks.has_free_regions()
100            || body.var_debug_info.has_free_regions()
101            || body.yield_ty().has_free_regions()),
102        "Unexpected free regions in MIR: {body:?}",
103    );
104
105    body
106}
107
108///////////////////////////////////////////////////////////////////////////
109// BuildMir -- walks a crate, looking for fn items and methods to build MIR from
110
111#[derive(#[automatically_derived]
impl ::core::fmt::Debug for BlockFrame {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            BlockFrame::Statement { ignores_expr_result: __self_0 } =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "Statement", "ignores_expr_result", &__self_0),
            BlockFrame::TailExpr { info: __self_0 } =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "TailExpr", "info", &__self_0),
            BlockFrame::SubExpr =>
                ::core::fmt::Formatter::write_str(f, "SubExpr"),
        }
    }
}Debug, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for BlockFrame { }
#[automatically_derived]
impl ::core::cmp::PartialEq for BlockFrame {
    #[inline]
    fn eq(&self, other: &BlockFrame) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr &&
            match (self, other) {
                (BlockFrame::Statement { ignores_expr_result: __self_0 },
                    BlockFrame::Statement { ignores_expr_result: __arg1_0 }) =>
                    __self_0 == __arg1_0,
                (BlockFrame::TailExpr { info: __self_0 },
                    BlockFrame::TailExpr { info: __arg1_0 }) =>
                    __self_0 == __arg1_0,
                _ => true,
            }
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for BlockFrame {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<bool>;
        let _: ::core::cmp::AssertParamIsEq<BlockTailInfo>;
    }
}Eq)]
112enum BlockFrame {
113    /// Evaluation is currently within a statement.
114    ///
115    /// Examples include:
116    /// 1. `EXPR;`
117    /// 2. `let _ = EXPR;`
118    /// 3. `let x = EXPR;`
119    Statement {
120        /// If true, then statement discards result from evaluating
121        /// the expression (such as examples 1 and 2 above).
122        ignores_expr_result: bool,
123    },
124
125    /// Evaluation is currently within the tail expression of a block.
126    ///
127    /// Example: `{ STMT_1; STMT_2; EXPR }`
128    TailExpr { info: BlockTailInfo },
129
130    /// Generic mark meaning that the block occurred as a subexpression
131    /// where the result might be used.
132    ///
133    /// Examples: `foo(EXPR)`, `match EXPR { ... }`
134    SubExpr,
135}
136
137impl BlockFrame {
138    fn is_tail_expr(&self) -> bool {
139        match *self {
140            BlockFrame::TailExpr { .. } => true,
141
142            BlockFrame::Statement { .. } | BlockFrame::SubExpr => false,
143        }
144    }
145    fn is_statement(&self) -> bool {
146        match *self {
147            BlockFrame::Statement { .. } => true,
148
149            BlockFrame::TailExpr { .. } | BlockFrame::SubExpr => false,
150        }
151    }
152}
153
154#[derive(#[automatically_derived]
impl ::core::fmt::Debug for BlockContext {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_tuple_field1_finish(f, "BlockContext",
            &&self.0)
    }
}Debug)]
155struct BlockContext(Vec<BlockFrame>);
156
157struct Builder<'a, 'tcx> {
158    tcx: TyCtxt<'tcx>,
159    // FIXME(@lcnr): Why does this use an `infcx`, there should be
160    // no shared type inference going on here. I feel like it would
161    // clearer to manually construct one where necessary or to provide
162    // a nice API for non-type inference trait system checks.
163    infcx: InferCtxt<'tcx>,
164    region_scope_tree: &'tcx region::ScopeTree,
165    param_env: ty::ParamEnv<'tcx>,
166
167    thir: &'a Thir<'tcx>,
168    cfg: CFG<'tcx>,
169
170    def_id: LocalDefId,
171    hir_id: HirId,
172    check_overflow: bool,
173    fn_span: Span,
174    arg_count: usize,
175    coroutine: Option<Box<CoroutineInfo<'tcx>>>,
176
177    /// The current set of scopes, updated as we traverse;
178    /// see the `scope` module for more details.
179    scopes: scope::Scopes<'tcx>,
180
181    /// The block-context: each time we build the code within an thir::Block,
182    /// we push a frame here tracking whether we are building a statement or
183    /// if we are pushing the tail expression of the block. This is used to
184    /// embed information in generated temps about whether they were created
185    /// for a block tail expression or not.
186    ///
187    /// It would be great if we could fold this into `self.scopes`
188    /// somehow, but right now I think that is very tightly tied to
189    /// the code generation in ways that we cannot (or should not)
190    /// start just throwing new entries onto that vector in order to
191    /// distinguish the context of EXPR1 from the context of EXPR2 in
192    /// `{ STMTS; EXPR1 } + EXPR2`.
193    block_context: BlockContext,
194
195    /// The vector of all scopes that we have created thus far;
196    /// we track this for debuginfo later.
197    source_scopes: IndexVec<SourceScope, SourceScopeData<'tcx>>,
198    source_scope: SourceScope,
199
200    /// The guard-context: each time we build the guard expression for
201    /// a match arm, we push onto this stack, and then pop when we
202    /// finish building it.
203    guard_context: Vec<GuardFrame>,
204
205    /// Temporaries with fixed indexes. Used so that if-let guards on arms
206    /// with an or-pattern are only created once.
207    fixed_temps: FxHashMap<ExprId, Local>,
208    /// Scope of temporaries that should be deduplicated using [Self::fixed_temps].
209    fixed_temps_scope: Option<region::Scope>,
210
211    /// Maps `HirId`s of variable bindings to the `Local`s created for them.
212    /// (A match binding can have two locals; the 2nd is for the arm's guard.)
213    var_indices: FxHashMap<LocalVarId, LocalsForNode>,
214    local_decls: IndexVec<Local, LocalDecl<'tcx>>,
215    canonical_user_type_annotations: ty::CanonicalUserTypeAnnotations<'tcx>,
216    upvars: CaptureMap<'tcx>,
217    unit_temp: Option<Place<'tcx>>,
218
219    var_debug_info: Vec<VarDebugInfo<'tcx>>,
220
221    // A cache for `maybe_lint_level_roots_bounded`. That function is called
222    // repeatedly, and each time it effectively traces a path through a tree
223    // structure from a node towards the root, doing an attribute check on each
224    // node along the way. This cache records which nodes trace all the way to
225    // the root (most of them do) and saves us from retracing many sub-paths
226    // many times, and rechecking many nodes.
227    lint_level_roots_cache: GrowableBitSet<hir::ItemLocalId>,
228
229    /// Collects additional coverage information during MIR building.
230    /// Only present if coverage is enabled and this function is eligible.
231    coverage_info: Option<coverageinfo::CoverageInfoBuilder>,
232}
233
234type CaptureMap<'tcx> = SortedIndexMultiMap<usize, ItemLocalId, Capture<'tcx>>;
235
236#[derive(#[automatically_derived]
impl<'tcx> ::core::fmt::Debug for Capture<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field3_finish(f, "Capture",
            "captured_place", &self.captured_place, "use_place",
            &self.use_place, "mutability", &&self.mutability)
    }
}Debug)]
237struct Capture<'tcx> {
238    captured_place: &'tcx ty::CapturedPlace<'tcx>,
239    use_place: Place<'tcx>,
240    mutability: Mutability,
241}
242
243impl<'a, 'tcx> Builder<'a, 'tcx> {
244    fn typing_env(&self) -> ty::TypingEnv<'tcx> {
245        self.infcx.typing_env(self.param_env)
246    }
247
248    fn is_bound_var_in_guard(&self, id: LocalVarId) -> bool {
249        self.guard_context.iter().any(|frame| frame.locals.iter().any(|local| local.id == id))
250    }
251
252    fn var_local_id(&self, id: LocalVarId, for_guard: ForGuard) -> Local {
253        self.var_indices[&id].local_id(for_guard)
254    }
255}
256
257impl BlockContext {
258    fn new() -> Self {
259        BlockContext(::alloc::vec::Vec::new()vec![])
260    }
261    fn push(&mut self, bf: BlockFrame) {
262        self.0.push(bf);
263    }
264    fn pop(&mut self) -> Option<BlockFrame> {
265        self.0.pop()
266    }
267
268    /// Traverses the frames on the `BlockContext`, searching for either
269    /// the first block-tail expression frame with no intervening
270    /// statement frame.
271    ///
272    /// Notably, this skips over `SubExpr` frames; this method is
273    /// meant to be used in the context of understanding the
274    /// relationship of a temp (created within some complicated
275    /// expression) with its containing expression, and whether the
276    /// value of that *containing expression* (not the temp!) is
277    /// ignored.
278    fn currently_in_block_tail(&self) -> Option<BlockTailInfo> {
279        for bf in self.0.iter().rev() {
280            match bf {
281                BlockFrame::SubExpr => continue,
282                BlockFrame::Statement { .. } => break,
283                &BlockFrame::TailExpr { info } => return Some(info),
284            }
285        }
286
287        None
288    }
289
290    /// Looks at the topmost frame on the BlockContext and reports
291    /// whether its one that would discard a block tail result.
292    ///
293    /// Unlike `currently_within_ignored_tail_expression`, this does
294    /// *not* skip over `SubExpr` frames: here, we want to know
295    /// whether the block result itself is discarded.
296    fn currently_ignores_tail_results(&self) -> bool {
297        match self.0.last() {
298            // no context: conservatively assume result is read
299            None => false,
300
301            // sub-expression: block result feeds into some computation
302            Some(BlockFrame::SubExpr) => false,
303
304            // otherwise: use accumulated is_ignored state.
305            Some(
306                BlockFrame::TailExpr { info: BlockTailInfo { tail_result_is_ignored: ign, .. } }
307                | BlockFrame::Statement { ignores_expr_result: ign },
308            ) => *ign,
309        }
310    }
311}
312
313#[derive(#[automatically_derived]
impl ::core::fmt::Debug for LocalsForNode {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            LocalsForNode::One(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "One",
                    &__self_0),
            LocalsForNode::ForGuard {
                ref_for_guard: __self_0, for_arm_body: __self_1 } =>
                ::core::fmt::Formatter::debug_struct_field2_finish(f,
                    "ForGuard", "ref_for_guard", __self_0, "for_arm_body",
                    &__self_1),
        }
    }
}Debug)]
314enum LocalsForNode {
315    /// In the usual case, a `HirId` for an identifier maps to at most
316    /// one `Local` declaration.
317    One(Local),
318
319    /// The exceptional case is identifiers in a match arm's pattern
320    /// that are referenced in a guard of that match arm. For these,
321    /// we have `2` Locals.
322    ///
323    /// * `for_arm_body` is the Local used in the arm body (which is
324    ///   just like the `One` case above),
325    ///
326    /// * `ref_for_guard` is the Local used in the arm's guard (which
327    ///   is a reference to a temp that is an alias of
328    ///   `for_arm_body`).
329    ForGuard { ref_for_guard: Local, for_arm_body: Local },
330}
331
332#[derive(#[automatically_derived]
impl ::core::fmt::Debug for GuardFrameLocal {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field1_finish(f,
            "GuardFrameLocal", "id", &&self.id)
    }
}Debug)]
333struct GuardFrameLocal {
334    id: LocalVarId,
335}
336
337impl GuardFrameLocal {
338    fn new(id: LocalVarId) -> Self {
339        GuardFrameLocal { id }
340    }
341}
342
343#[derive(#[automatically_derived]
impl ::core::fmt::Debug for GuardFrame {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field1_finish(f, "GuardFrame",
            "locals", &&self.locals)
    }
}Debug)]
344struct GuardFrame {
345    /// These are the id's of names that are bound by patterns of the
346    /// arm of *this* guard.
347    ///
348    /// (Frames higher up the stack will have the id's bound in arms
349    /// further out, such as in a case like:
350    ///
351    /// match E1 {
352    ///      P1(id1) if (... (match E2 { P2(id2) if ... => B2 })) => B1,
353    /// }
354    ///
355    /// here, when building for FIXME.
356    locals: Vec<GuardFrameLocal>,
357}
358
359/// `ForGuard` indicates whether we are talking about:
360///   1. The variable for use outside of guard expressions, or
361///   2. The temp that holds reference to (1.), which is actually what the
362///      guard expressions see.
363#[derive(#[automatically_derived]
impl ::core::marker::Copy for ForGuard { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for ForGuard { }
#[automatically_derived]
impl ::core::clone::Clone for ForGuard {
    #[inline]
    fn clone(&self) -> ForGuard { *self }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for ForGuard {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                ForGuard::RefWithinGuard => "RefWithinGuard",
                ForGuard::OutsideGuard => "OutsideGuard",
            })
    }
}Debug, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for ForGuard { }
#[automatically_derived]
impl ::core::cmp::PartialEq for ForGuard {
    #[inline]
    fn eq(&self, other: &ForGuard) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for ForGuard { }Eq)]
364enum ForGuard {
365    RefWithinGuard,
366    OutsideGuard,
367}
368
369impl LocalsForNode {
370    fn local_id(&self, for_guard: ForGuard) -> Local {
371        match (self, for_guard) {
372            (&LocalsForNode::One(local_id), ForGuard::OutsideGuard)
373            | (
374                &LocalsForNode::ForGuard { ref_for_guard: local_id, .. },
375                ForGuard::RefWithinGuard,
376            )
377            | (&LocalsForNode::ForGuard { for_arm_body: local_id, .. }, ForGuard::OutsideGuard) => {
378                local_id
379            }
380
381            (&LocalsForNode::One(_), ForGuard::RefWithinGuard) => {
382                bug_impl(None,
    format_args!("anything with one local should never be within a guard."),
    Location::caller())bug!("anything with one local should never be within a guard.")
383            }
384        }
385    }
386}
387
388struct CFG<'tcx> {
389    basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
390}
391
392#[automatically_derived]
impl ::core::marker::Copy for ScopeId { }
impl ScopeId {
    #[doc = r" Maximum value the index can take, as a `u32`."]
    const MAX_AS_U32: u32 = 0xFFFF_FF00;
    #[doc = r" Maximum value the index can take."]
    const MAX: Self = Self::from_u32(0xFFFF_FF00);
    #[doc = r" Zero value of the index."]
    const ZERO: Self = Self::from_u32(0);
    #[doc = r" Creates a new index from a given `usize`."]
    #[doc = r""]
    #[doc = r" # Panics"]
    #[doc = r""]
    #[doc = r" Will panic if `value` exceeds `MAX`."]
    #[inline]
    const fn from_usize(value: usize) -> Self {
        if !(value <= (0xFFFF_FF00 as usize)) {
            ::core::panicking::panic("assertion failed: value <= (0xFFFF_FF00 as usize)")
        };
        unsafe { Self::from_u32_unchecked(value as u32) }
    }
    #[doc = r" Creates a new index from a given `u32`."]
    #[doc = r""]
    #[doc = r" # Panics"]
    #[doc = r""]
    #[doc = r" Will panic if `value` exceeds `MAX`."]
    #[inline]
    const fn from_u32(value: u32) -> Self {
        if !(value <= 0xFFFF_FF00) {
            ::core::panicking::panic("assertion failed: value <= 0xFFFF_FF00")
        };
        unsafe { Self::from_u32_unchecked(value) }
    }
    #[doc = r" Creates a new index from a given `u16`."]
    #[doc = r""]
    #[doc = r" # Panics"]
    #[doc = r""]
    #[doc = r" Will panic if `value` exceeds `MAX`."]
    #[inline]
    const fn from_u16(value: u16) -> Self {
        let value = value as u32;
        if !(value <= 0xFFFF_FF00) {
            ::core::panicking::panic("assertion failed: value <= 0xFFFF_FF00")
        };
        unsafe { Self::from_u32_unchecked(value) }
    }
    #[doc = r" Creates a new index from a given `u32`."]
    #[doc = r""]
    #[doc = r" # Safety"]
    #[doc = r""]
    #[doc =
    r" The provided value must be less than or equal to the maximum value for the newtype."]
    #[doc =
    r" Providing a value outside this range is undefined due to layout restrictions."]
    #[doc = r""]
    #[doc = r" Prefer using `from_u32`."]
    #[inline]
    const unsafe fn from_u32_unchecked(value: u32) -> Self {
        Self {
            private_use_as_methods_instead: unsafe {
                std::mem::transmute(value)
            },
        }
    }
    #[doc = r" Extracts the value of this index as a `usize`."]
    #[inline]
    const fn index(self) -> usize { self.as_usize() }
    #[doc = r" Extracts the value of this index as a `u32`."]
    #[inline]
    const fn as_u32(self) -> u32 {
        unsafe { std::mem::transmute(self.private_use_as_methods_instead) }
    }
    #[doc = r" Extracts the value of this index as a `usize`."]
    #[inline]
    const fn as_usize(self) -> usize { self.as_u32() as usize }
}
impl std::ops::Add<usize> for ScopeId {
    type Output = Self;
    #[inline]
    fn add(self, other: usize) -> Self {
        Self::from_usize(self.index() + other)
    }
}
impl std::ops::AddAssign<usize> for ScopeId {
    #[inline]
    fn add_assign(&mut self, other: usize) { *self = *self + other; }
}
impl rustc_index::Idx for ScopeId {
    #[inline]
    fn new(value: usize) -> Self { Self::from_usize(value) }
    #[inline]
    fn index(self) -> usize { self.as_usize() }
}
impl From<ScopeId> for u32 {
    #[inline]
    fn from(v: ScopeId) -> u32 { v.as_u32() }
}
impl From<ScopeId> for usize {
    #[inline]
    fn from(v: ScopeId) -> usize { v.as_usize() }
}
impl From<usize> for ScopeId {
    #[inline]
    fn from(value: usize) -> Self { Self::from_usize(value) }
}
impl From<u32> for ScopeId {
    #[inline]
    fn from(value: u32) -> Self { Self::from_u32(value) }
}
impl ::std::cmp::Eq for ScopeId {}
impl ::std::cmp::PartialEq for ScopeId {
    fn eq(&self, other: &Self) -> bool { self.as_u32().eq(&other.as_u32()) }
}
impl ::std::marker::StructuralPartialEq for ScopeId {}
impl ::std::hash::Hash for ScopeId {
    fn hash<H: ::std::hash::Hasher>(&self, state: &mut H) {
        self.as_u32().hash(state)
    }
}
impl ::std::fmt::Debug for ScopeId {
    fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
        fmt.write_fmt(format_args!("{0}", self.as_u32()))
    }
}rustc_index::newtype_index! {
393    struct ScopeId {}
394}
395
396#[derive(#[automatically_derived]
impl ::core::fmt::Debug for NeedsTemporary {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                NeedsTemporary::No => "No",
                NeedsTemporary::Maybe => "Maybe",
            })
    }
}Debug)]
397enum NeedsTemporary {
398    /// Use this variant when whatever you are converting with `as_operand`
399    /// is the last thing you are converting. This means that if we introduced
400    /// an intermediate temporary, we'd only read it immediately after, so we can
401    /// also avoid it.
402    No,
403    /// For all cases where you aren't sure or that are too expensive to compute
404    /// for now. It is always safe to fall back to this.
405    Maybe,
406}
407
408/// The `BlockAnd` "monad" packages up the new basic block along with a
409/// produced value (sometimes just unit, of course). The `unpack!`
410/// macro (and methods below) makes working with `BlockAnd` much more
411/// convenient.
412#[must_use = "if you don't use one of these results, you're leaving a dangling edge"]
413struct BlockAnd<T>(BasicBlock, T);
414
415impl BlockAnd<()> {
416    /// Unpacks `BlockAnd<()>` into a [`BasicBlock`].
417    #[must_use]
418    fn into_block(self) -> BasicBlock {
419        let Self(block, ()) = self;
420        block
421    }
422}
423
424trait BlockAndExtension {
425    fn and<T>(self, v: T) -> BlockAnd<T>;
426    fn unit(self) -> BlockAnd<()>;
427}
428
429impl BlockAndExtension for BasicBlock {
430    fn and<T>(self, v: T) -> BlockAnd<T> {
431        BlockAnd(self, v)
432    }
433
434    fn unit(self) -> BlockAnd<()> {
435        BlockAnd(self, ())
436    }
437}
438
439/// Update a block pointer and return the value.
440/// Use it like `let x = unpack!(block = self.foo(block, foo))`.
441macro_rules! unpack {
442    ($x:ident = $c:expr) => {{
443        let BlockAnd(b, v) = $c;
444        $x = b;
445        v
446    }};
447}
448
449/// The main entry point for building MIR for a function.
450fn construct_fn<'tcx>(
451    tcx: TyCtxt<'tcx>,
452    fn_def: LocalDefId,
453    thir: &Thir<'tcx>,
454    expr: ExprId,
455    fn_sig: ty::FnSig<'tcx>,
456) -> Body<'tcx> {
457    let span = tcx.def_span(fn_def);
458    let fn_id = tcx.local_def_id_to_hir_id(fn_def);
459
460    // Figure out what primary body this item has.
461    let body = tcx.hir_body_owned_by(fn_def);
462    let span_with_body = tcx.hir_span_with_body(fn_id);
463    let return_ty_span = tcx
464        .hir_fn_decl_by_hir_id(fn_id)
465        .unwrap_or_else(|| bug_impl(Some(span), format_args!("can\'t build MIR for {0:?}", fn_def),
    Location::caller())span_bug!(span, "can't build MIR for {:?}", fn_def))
466        .output
467        .span();
468
469    let mut abi = fn_sig.abi();
470    if let DefKind::Closure = tcx.def_kind(fn_def) {
471        // HACK(eddyb) Avoid having RustCall on closures,
472        // as it adds unnecessary (and wrong) auto-tupling.
473        abi = ExternAbi::Rust;
474    }
475
476    let arguments = &thir.params;
477
478    let return_ty = fn_sig.output();
479
480    if let Some((dialect, phase)) =
481        {
    {
        'done:
            {
            for i in ::rustc_attr_ir::HasAttrs::get_attrs(fn_id, &tcx) {
                #[allow(unused_imports)]
                use ::rustc_attr_ir::AttributeKind::*;
                let i: &::rustc_attr_ir::Attribute = i;
                match i {
                    ::rustc_attr_ir::Attribute::Parsed(CustomMir(dialect,
                        phase)) => {
                        break 'done Some((dialect, phase));
                    }
                    ::rustc_attr_ir::Attribute::Unparsed(..) =>
                        {}
                        #[deny(unreachable_patterns)]
                        _ => {}
                }
            }
            None
        }
    }
}find_attr!(tcx, fn_id, CustomMir(dialect, phase) => (dialect, phase))
482    {
483        return custom::build_custom_mir(
484            tcx,
485            fn_def.to_def_id(),
486            fn_id,
487            thir,
488            expr,
489            arguments,
490            return_ty,
491            return_ty_span,
492            span_with_body,
493            dialect.as_ref().map(|(d, _)| *d),
494            phase.as_ref().map(|(p, _)| *p),
495        );
496    }
497
498    let typing_mode = if tcx.use_typing_mode_post_typeck_until_borrowck() {
499        TypingMode::borrowck(tcx, fn_def)
500    } else {
501        // FIXME(#132279): This should be able to reveal opaque
502        // types defined during HIR typeck.
503        TypingMode::non_body_analysis()
504    };
505
506    let infcx = tcx.infer_ctxt().build(typing_mode);
507
508    let defining_ty = tcx.type_of(fn_def).instantiate_identity().skip_normalization();
509    let defining_ty = if infcx.next_trait_solver() {
510        // Closure types come from HIR typeck results, where they were already
511        // normalized during writeback. Wrapping them in an `EarlyBinder`
512        // conservatively makes aliases non-rigid, so restore their rigidness
513        // instead of normalizing them again during MIR build.
514        ty::set_aliases_to_rigid(tcx, defining_ty)
515    } else {
516        defining_ty
517    };
518    let coroutine = match defining_ty.kind() {
519        ty::Coroutine(_, args) => Some(Box::new(CoroutineInfo::initial(
520            tcx.coroutine_kind(fn_def).unwrap(),
521            args.as_coroutine().yield_ty(),
522            args.as_coroutine().resume_ty(),
523        ))),
524        ty::Closure(..) | ty::CoroutineClosure(..) | ty::FnDef(..) => None,
525        ty => bug_impl(Some(span_with_body),
    format_args!("unexpected type of body: {0:?}", ty), Location::caller())span_bug!(span_with_body, "unexpected type of body: {ty:?}"),
526    };
527
528    let mut builder = Builder::new(
529        thir,
530        infcx,
531        fn_def,
532        fn_id,
533        span_with_body,
534        arguments.len(),
535        return_ty,
536        return_ty_span,
537        coroutine,
538    );
539
540    let call_site_scope =
541        region::Scope { local_id: body.id().hir_id.local_id, data: region::ScopeData::CallSite };
542    let arg_scope =
543        region::Scope { local_id: body.id().hir_id.local_id, data: region::ScopeData::Arguments };
544    let source_info = builder.source_info(span);
545    let call_site_s = (call_site_scope, source_info);
546    let _: BlockAnd<()> = builder.in_scope(call_site_s, LintLevel::Inherited, |builder| {
547        let arg_scope_s = (arg_scope, source_info);
548        // Attribute epilogue to function's closing brace
549        let fn_end = span_with_body.shrink_to_hi();
550        let return_block = builder
551            .in_breakable_scope(None, Place::return_place(), fn_end, |builder| {
552                Some(builder.in_scope(arg_scope_s, LintLevel::Inherited, |builder| {
553                    builder.args_and_body(START_BLOCK, arguments, arg_scope, expr)
554                }))
555            })
556            .into_block();
557        let source_info = builder.source_info(fn_end);
558        builder.push_coverage_point_for_fn_end(return_block, source_info, fn_id);
559        builder.cfg.terminate(return_block, source_info, TerminatorKind::Return);
560        builder.build_drop_trees();
561        return_block.unit()
562    });
563
564    let mut body = builder.finish();
565
566    body.spread_arg = if abi == ExternAbi::RustCall {
567        // RustCall pseudo-ABI untuples the last argument.
568        // FIXME(splat): splat can untuple any argument, set spread_arg here
569        Some(Local::new(arguments.len()))
570    } else {
571        None
572    };
573
574    body
575}
576
577fn construct_const<'a, 'tcx>(
578    tcx: TyCtxt<'tcx>,
579    def: LocalDefId,
580    thir: &'a Thir<'tcx>,
581    expr: ExprId,
582    const_ty: Ty<'tcx>,
583) -> Body<'tcx> {
584    let hir_id = tcx.local_def_id_to_hir_id(def);
585
586    // Figure out what primary body this item has.
587    let (span, const_ty_span) = match tcx.hir_node(hir_id) {
588        Node::Item(hir::Item {
589            kind: hir::ItemKind::Static(_, _, ty, _) | hir::ItemKind::Const(_, _, ty, _),
590            span,
591            ..
592        })
593        | Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Const(ty, _), span, .. })
594        | Node::TraitItem(hir::TraitItem {
595            kind: hir::TraitItemKind::Const(ty, Some(_)),
596            span,
597            ..
598        }) => (*span, ty.span),
599        Node::AnonConst(ct) => (ct.span, ct.span),
600        Node::ConstBlock(_) => {
601            let span = tcx.def_span(def);
602            (span, span)
603        }
604        Node::Item(hir::Item { kind: hir::ItemKind::GlobalAsm { .. }, span, .. }) => (*span, *span),
605        _ => bug_impl(Some(tcx.def_span(def)),
    format_args!("can\'t build MIR for {0:?}", def), Location::caller())span_bug!(tcx.def_span(def), "can't build MIR for {:?}", def),
606    };
607
608    let typing_mode = if tcx.use_typing_mode_post_typeck_until_borrowck() {
609        TypingMode::borrowck(tcx, def)
610    } else {
611        // FIXME(#132279): This should be able to reveal opaque
612        // types defined during HIR typeck.
613        TypingMode::non_body_analysis()
614    };
615
616    let infcx = tcx.infer_ctxt().build(typing_mode);
617    let mut builder =
618        Builder::new(thir, infcx, def, hir_id, span, 0, const_ty, const_ty_span, None);
619
620    let mut block = START_BLOCK;
621    block = builder.expr_into_dest(Place::return_place(), block, expr).into_block();
622
623    let source_info = builder.source_info(span);
624    builder.cfg.terminate(block, source_info, TerminatorKind::Return);
625
626    builder.build_drop_trees();
627    builder.finish()
628}
629
630/// Construct MIR for an item that has had errors in type checking.
631///
632/// This is required because we may still want to run MIR passes on an item
633/// with type errors, but normal MIR construction can't handle that in general.
634fn construct_error(tcx: TyCtxt<'_>, def_id: LocalDefId, guar: ErrorGuaranteed) -> Body<'_> {
635    let span = tcx.def_span(def_id);
636    let hir_id = tcx.local_def_id_to_hir_id(def_id);
637
638    let (inputs, output, coroutine) = match tcx.def_kind(def_id) {
639        DefKind::Const
640        | DefKind::AssocConst
641        | DefKind::AnonConst
642        | DefKind::Static { .. }
643        | DefKind::GlobalAsm => {
644            (::alloc::vec::Vec::new()vec![], tcx.type_of(def_id).instantiate_identity().skip_norm_wip(), None)
645        }
646        DefKind::Ctor(..) | DefKind::Fn | DefKind::AssocFn => {
647            let sig = tcx.liberate_late_bound_regions(
648                def_id.to_def_id(),
649                tcx.fn_sig(def_id).instantiate_identity().skip_norm_wip(),
650            );
651            (sig.inputs().to_vec(), sig.output(), None)
652        }
653        DefKind::Closure => {
654            let closure_ty = tcx.type_of(def_id).instantiate_identity().skip_norm_wip();
655            match closure_ty.kind() {
656                ty::Closure(_, args) => {
657                    let args = args.as_closure();
658                    let sig = tcx.liberate_late_bound_regions(def_id.to_def_id(), args.sig());
659                    let self_ty = match args.kind() {
660                        ty::ClosureKind::Fn => {
661                            Ty::new_imm_ref(tcx, tcx.lifetimes.re_erased, closure_ty)
662                        }
663                        ty::ClosureKind::FnMut => {
664                            Ty::new_mut_ref(tcx, tcx.lifetimes.re_erased, closure_ty)
665                        }
666                        ty::ClosureKind::FnOnce => closure_ty,
667                    };
668                    (
669                        [self_ty].into_iter().chain(sig.inputs()[0].tuple_fields()).collect(),
670                        sig.output(),
671                        None,
672                    )
673                }
674                ty::Coroutine(_, args) => {
675                    let args = args.as_coroutine();
676                    let resume_ty = args.resume_ty();
677                    let yield_ty = args.yield_ty();
678                    let return_ty = args.return_ty();
679                    (
680                        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [closure_ty, resume_ty]))vec![closure_ty, resume_ty],
681                        return_ty,
682                        Some(Box::new(CoroutineInfo::initial(
683                            tcx.coroutine_kind(def_id).unwrap(),
684                            yield_ty,
685                            resume_ty,
686                        ))),
687                    )
688                }
689                ty::CoroutineClosure(did, args) => {
690                    let args = args.as_coroutine_closure();
691                    let sig = tcx.liberate_late_bound_regions(
692                        def_id.to_def_id(),
693                        args.coroutine_closure_sig(),
694                    );
695                    let self_ty = match args.kind() {
696                        ty::ClosureKind::Fn => {
697                            Ty::new_imm_ref(tcx, tcx.lifetimes.re_erased, closure_ty)
698                        }
699                        ty::ClosureKind::FnMut => {
700                            Ty::new_mut_ref(tcx, tcx.lifetimes.re_erased, closure_ty)
701                        }
702                        ty::ClosureKind::FnOnce => closure_ty,
703                    };
704                    (
705                        [self_ty].into_iter().chain(sig.tupled_inputs_ty.tuple_fields()).collect(),
706                        sig.to_coroutine(
707                            tcx,
708                            args.parent_args(),
709                            args.kind_ty(),
710                            tcx.coroutine_for_closure(*did),
711                            Ty::new_error(tcx, guar),
712                        ),
713                        None,
714                    )
715                }
716                ty::Error(_) => (::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [closure_ty, closure_ty]))vec![closure_ty, closure_ty], closure_ty, None),
717                kind => {
718                    bug_impl(Some(span),
    format_args!("expected type of closure body to be a closure or coroutine, got {0:?}",
        kind), Location::caller());span_bug!(
719                        span,
720                        "expected type of closure body to be a closure or coroutine, got {kind:?}"
721                    );
722                }
723            }
724        }
725        dk => bug_impl(Some(span), format_args!("{0:?} is not a body: {1:?}", def_id, dk),
    Location::caller())span_bug!(span, "{:?} is not a body: {:?}", def_id, dk),
726    };
727
728    let source_info = SourceInfo { span, scope: OUTERMOST_SOURCE_SCOPE };
729    let local_decls = IndexVec::from_iter(
730        [output].iter().chain(&inputs).map(|ty| LocalDecl::with_source_info(*ty, source_info)),
731    );
732    let mut cfg = CFG { basic_blocks: IndexVec::new() };
733    let mut source_scopes = IndexVec::new();
734
735    cfg.start_new_block();
736    source_scopes.push(SourceScopeData {
737        span,
738        parent_scope: None,
739        inlined: None,
740        inlined_parent_scope: None,
741        local_data: ClearCrossCrate::Set(SourceScopeLocalData { lint_root: hir_id }),
742    });
743
744    cfg.terminate(START_BLOCK, source_info, TerminatorKind::Unreachable);
745
746    Body::new(
747        MirSource::item(def_id.to_def_id()),
748        cfg.basic_blocks,
749        source_scopes,
750        local_decls,
751        IndexVec::new(),
752        inputs.len(),
753        ::alloc::vec::Vec::new()vec![],
754        span,
755        coroutine,
756        Some(guar),
757    )
758}
759
760impl<'a, 'tcx> Builder<'a, 'tcx> {
761    fn new(
762        thir: &'a Thir<'tcx>,
763        infcx: InferCtxt<'tcx>,
764        def: LocalDefId,
765        hir_id: HirId,
766        span: Span,
767        arg_count: usize,
768        return_ty: Ty<'tcx>,
769        return_span: Span,
770        coroutine: Option<Box<CoroutineInfo<'tcx>>>,
771    ) -> Builder<'a, 'tcx> {
772        let tcx = infcx.tcx;
773        // Some functions always have overflow checks enabled,
774        // however, they may not get codegen'd, depending on
775        // the settings for the crate they are codegened in.
776        let mut check_overflow = {
    {
            'done:
                {
                for i in tcx.hir_attrs(hir_id) {
                    #[allow(unused_imports)]
                    use ::rustc_attr_ir::AttributeKind::*;
                    let i: &::rustc_attr_ir::Attribute = i;
                    match i {
                        ::rustc_attr_ir::Attribute::Parsed(RustcInheritOverflowChecks)
                            => {
                            break 'done Some(());
                        }
                        ::rustc_attr_ir::Attribute::Unparsed(..) =>
                            {}
                            #[deny(unreachable_patterns)]
                            _ => {}
                    }
                }
                None
            }
        }.is_some()
}find_attr!(tcx.hir_attrs(hir_id), RustcInheritOverflowChecks);
777        // Respect -C overflow-checks.
778        check_overflow |= tcx.sess.overflow_checks();
779        // Constants always need overflow checks.
780        check_overflow |= #[allow(non_exhaustive_omitted_patterns)] match tcx.hir_body_owner_kind(def) {
    hir::BodyOwnerKind::Const { .. } | hir::BodyOwnerKind::Static(_) => true,
    _ => false,
}matches!(
781            tcx.hir_body_owner_kind(def),
782            hir::BodyOwnerKind::Const { .. } | hir::BodyOwnerKind::Static(_)
783        );
784
785        let lint_level = LintLevel::Explicit(hir_id);
786        let param_env = tcx.param_env(def);
787        let mut builder = Builder {
788            thir,
789            tcx,
790            infcx,
791            region_scope_tree: tcx.region_scope_tree(def),
792            param_env,
793            def_id: def,
794            hir_id,
795            check_overflow,
796            cfg: CFG { basic_blocks: IndexVec::new() },
797            fn_span: span,
798            arg_count,
799            coroutine,
800            scopes: scope::Scopes::new(),
801            block_context: BlockContext::new(),
802            source_scopes: IndexVec::new(),
803            source_scope: OUTERMOST_SOURCE_SCOPE,
804            guard_context: ::alloc::vec::Vec::new()vec![],
805            fixed_temps: Default::default(),
806            fixed_temps_scope: None,
807            local_decls: IndexVec::from_elem_n(LocalDecl::new(return_ty, return_span), 1),
808            canonical_user_type_annotations: IndexVec::new(),
809            upvars: CaptureMap::new(),
810            var_indices: Default::default(),
811            unit_temp: None,
812            var_debug_info: ::alloc::vec::Vec::new()vec![],
813            lint_level_roots_cache: GrowableBitSet::new_empty(),
814            coverage_info: coverageinfo::CoverageInfoBuilder::new_if_enabled(tcx, def),
815        };
816
817        {
    match (&builder.cfg.start_new_block(), &START_BLOCK) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_eq!(builder.cfg.start_new_block(), START_BLOCK);
818        {
    match (&builder.new_source_scope(span, lint_level),
            &OUTERMOST_SOURCE_SCOPE) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_eq!(builder.new_source_scope(span, lint_level), OUTERMOST_SOURCE_SCOPE);
819        builder.source_scopes[OUTERMOST_SOURCE_SCOPE].parent_scope = None;
820
821        builder
822    }
823
824    #[allow(dead_code)]
825    fn dump_for_debugging(&self) {
826        let mut body = Body::new(
827            MirSource::item(self.def_id.to_def_id()),
828            self.cfg.basic_blocks.clone(),
829            self.source_scopes.clone(),
830            self.local_decls.clone(),
831            self.canonical_user_type_annotations.clone(),
832            self.arg_count.clone(),
833            self.var_debug_info.clone(),
834            self.fn_span.clone(),
835            self.coroutine.clone(),
836            None,
837        );
838        body.coverage_early_info = self.coverage_info.as_ref().map(|b| b.as_done());
839
840        let writer = pretty::MirWriter::new(self.tcx);
841        writer.write_mir_fn(&body, &mut std::io::stdout()).unwrap();
842    }
843
844    fn finish(self) -> Body<'tcx> {
845        let mut body = Body::new(
846            MirSource::item(self.def_id.to_def_id()),
847            self.cfg.basic_blocks,
848            self.source_scopes,
849            self.local_decls,
850            self.canonical_user_type_annotations,
851            self.arg_count,
852            self.var_debug_info,
853            self.fn_span,
854            self.coroutine,
855            None,
856        );
857        body.coverage_early_info = self.coverage_info.map(|b| b.into_done());
858
859        let writer = pretty::MirWriter::new(self.tcx);
860        for (index, block) in body.basic_blocks.iter().enumerate() {
861            if block.terminator.is_none() {
862                writer.write_mir_fn(&body, &mut std::io::stdout()).unwrap();
863                bug_impl(Some(self.fn_span),
    format_args!("no terminator on block {0:?}", index), Location::caller());span_bug!(self.fn_span, "no terminator on block {:?}", index);
864            }
865        }
866
867        body
868    }
869
870    fn insert_upvar_arg(&mut self) {
871        let Some(closure_arg) = self.local_decls.get(ty::CAPTURE_STRUCT_LOCAL) else { return };
872
873        let mut closure_ty = closure_arg.ty;
874        let mut closure_env_projs = ::alloc::vec::Vec::new()vec![];
875        if let ty::Ref(_, ty, _) = closure_ty.kind() {
876            closure_env_projs.push(ProjectionElem::Deref);
877            closure_ty = *ty;
878        }
879
880        let upvar_args = match closure_ty.kind() {
881            ty::Closure(_, args) => ty::UpvarArgs::Closure(args),
882            ty::Coroutine(_, args) => ty::UpvarArgs::Coroutine(args),
883            ty::CoroutineClosure(_, args) => ty::UpvarArgs::CoroutineClosure(args),
884            _ => return,
885        };
886
887        // In analyze_closure() in upvar.rs we gathered a list of upvars used by an
888        // indexed closure and we stored in a map called closure_min_captures in TypeckResults
889        // with the closure's DefId. Here, we run through that vec of UpvarIds for
890        // the given closure and use the necessary information to create upvar
891        // debuginfo and to fill `self.upvars`.
892        let capture_tys = upvar_args.upvar_tys();
893
894        let tcx = self.tcx;
895        let mut upvar_owner = None;
896        self.upvars = tcx
897            .closure_captures(self.def_id)
898            .iter()
899            .zip_eq(capture_tys)
900            .enumerate()
901            .map(|(i, (captured_place, ty))| {
902                let name = captured_place.to_symbol();
903
904                let capture = captured_place.info.capture_kind;
905                let var_id = match captured_place.place.base {
906                    HirPlaceBase::Upvar(upvar_id) => upvar_id.var_path.hir_id,
907                    _ => bug_impl(None, format_args!("Expected an upvar"), Location::caller())bug!("Expected an upvar"),
908                };
909                let upvar_base = upvar_owner.get_or_insert(var_id.owner);
910                {
    match (&*upvar_base, &var_id.owner) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_eq!(*upvar_base, var_id.owner);
911                let var_id = var_id.local_id;
912
913                let mutability = captured_place.mutability;
914
915                let mut projs = closure_env_projs.clone();
916                projs.push(ProjectionElem::Field(FieldIdx::new(i), ty));
917                match capture {
918                    ty::UpvarCapture::ByValue | ty::UpvarCapture::ByUse => {}
919                    ty::UpvarCapture::ByRef(..) => {
920                        projs.push(ProjectionElem::Deref);
921                    }
922                };
923
924                let use_place = Place {
925                    local: ty::CAPTURE_STRUCT_LOCAL,
926                    projection: tcx.mk_place_elems(&projs),
927                };
928                self.var_debug_info.push(VarDebugInfo {
929                    name,
930                    source_info: SourceInfo::outermost(captured_place.var_ident.span),
931                    value: VarDebugInfoContents::Place(use_place),
932                    composite: None,
933                    argument_index: None,
934                });
935
936                let capture = Capture { captured_place, use_place, mutability };
937                (var_id, capture)
938            })
939            .collect();
940    }
941
942    fn args_and_body(
943        &mut self,
944        mut block: BasicBlock,
945        arguments: &IndexSlice<ParamId, Param<'tcx>>,
946        argument_scope: region::Scope,
947        expr_id: ExprId,
948    ) -> BlockAnd<()> {
949        let expr_span = self.thir[expr_id].span;
950        // Allocate locals for the function arguments
951        for (argument_index, param) in arguments.iter().enumerate() {
952            let source_info =
953                SourceInfo::outermost(param.pat.as_ref().map_or(self.fn_span, |pat| pat.span));
954            let arg_local =
955                self.local_decls.push(LocalDecl::with_source_info(param.ty, source_info));
956
957            // If this is a simple binding pattern, give debuginfo a nice name.
958            if let Some(ref pat) = param.pat
959                && let Some(name) = pat.simple_ident()
960            {
961                self.var_debug_info.push(VarDebugInfo {
962                    name,
963                    source_info,
964                    value: VarDebugInfoContents::Place(arg_local.into()),
965                    composite: None,
966                    argument_index: Some(argument_index as u16 + 1),
967                });
968            }
969        }
970
971        self.insert_upvar_arg();
972
973        let mut scope = None;
974        // Bind the argument patterns
975        for (index, param) in arguments.iter().enumerate() {
976            // Function arguments always get the first Local indices after the return place
977            let local = Local::arg(index);
978            let place = Place::from(local);
979
980            // Make sure we drop (parts of) the argument even when not matched on.
981            self.schedule_drop_value(
982                param.pat.as_ref().map_or(expr_span, |pat| pat.span),
983                argument_scope,
984                local,
985            );
986
987            let Some(ref pat) = param.pat else {
988                continue;
989            };
990            let original_source_scope = self.source_scope;
991            let span = pat.span;
992            if let Some(arg_hir_id) = param.hir_id {
993                self.set_correct_source_scope_for_arg(arg_hir_id, original_source_scope, span);
994            }
995            match pat.kind {
996                // Don't introduce extra copies for simple bindings
997                PatKind::Binding {
998                    var,
999                    mode: BindingMode(ByRef::No, mutability),
1000                    subpattern: None,
1001                    ..
1002                } => {
1003                    self.local_decls[local].mutability = mutability;
1004                    self.local_decls[local].source_info.scope = self.source_scope;
1005                    **self.local_decls[local].local_info.as_mut().unwrap_crate_local() =
1006                        if let Some(kind) = param.self_kind {
1007                            LocalInfo::User(BindingForm::ImplicitSelf(kind))
1008                        } else {
1009                            let binding_mode = BindingMode(ByRef::No, mutability);
1010                            LocalInfo::User(BindingForm::Var(VarBindingForm {
1011                                binding_mode,
1012                                opt_ty_info: param.ty_span,
1013                                opt_match_place: Some((None, span)),
1014                                pat_span: span,
1015                                introductions: ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [VarBindingIntroduction { span, is_shorthand: false }]))vec![VarBindingIntroduction {
1016                                    span,
1017                                    is_shorthand: false,
1018                                }],
1019                            }))
1020                        };
1021                    self.var_indices.insert(var, LocalsForNode::One(local));
1022                }
1023                _ => {
1024                    scope = self.declare_bindings(
1025                        scope,
1026                        expr_span,
1027                        &pat,
1028                        None,
1029                        Some((Some(&place), span)),
1030                    );
1031                    let place_builder = PlaceBuilder::from(local);
1032                    block = self.place_into_pattern(block, pat, place_builder, false).into_block();
1033                }
1034            }
1035            self.source_scope = original_source_scope;
1036        }
1037
1038        // Enter the argument pattern bindings source scope, if it exists.
1039        if let Some(source_scope) = scope {
1040            self.source_scope = source_scope;
1041        }
1042
1043        if self.tcx.intrinsic(self.def_id).is_some_and(|i| i.must_be_overridden)
1044            || self.tcx.is_sdylib_interface_build()
1045        {
1046            let source_info = self.source_info(rustc_span::DUMMY_SP);
1047            self.cfg.terminate(block, source_info, TerminatorKind::Unreachable);
1048            self.cfg.start_new_block().unit()
1049        } else {
1050            // Ensure we don't silently codegen functions with fake bodies.
1051            match self.tcx.hir_node(self.hir_id) {
1052                hir::Node::Item(hir::Item {
1053                    kind: hir::ItemKind::Fn { has_body: false, .. },
1054                    ..
1055                }) => {
1056                    self.tcx.dcx().span_delayed_bug(
1057                        expr_span,
1058                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("fn item without body has reached MIR building: {0:?}",
                self.def_id))
    })format!("fn item without body has reached MIR building: {:?}", self.def_id),
1059                    );
1060                }
1061                _ => {}
1062            }
1063            self.expr_into_dest(Place::return_place(), block, expr_id)
1064        }
1065    }
1066
1067    fn set_correct_source_scope_for_arg(
1068        &mut self,
1069        arg_hir_id: HirId,
1070        original_source_scope: SourceScope,
1071        pattern_span: Span,
1072    ) {
1073        let parent_id = self.source_scopes[original_source_scope]
1074            .local_data
1075            .as_ref()
1076            .unwrap_crate_local()
1077            .lint_root;
1078        self.maybe_new_source_scope(pattern_span, arg_hir_id, parent_id);
1079    }
1080
1081    fn get_unit_temp(&mut self) -> Place<'tcx> {
1082        match self.unit_temp {
1083            Some(tmp) => tmp,
1084            None => {
1085                let ty = self.tcx.types.unit;
1086                let fn_span = self.fn_span;
1087                let tmp = self.temp(ty, fn_span);
1088                self.unit_temp = Some(tmp);
1089                tmp
1090            }
1091        }
1092    }
1093}
1094
1095fn parse_float_into_constval(num: Symbol, float_ty: ty::FloatTy, neg: bool) -> Option<ConstValue> {
1096    parse_float_into_scalar(num, float_ty, neg).map(|s| ConstValue::Scalar(s.into()))
1097}
1098
1099pub(crate) fn parse_float_into_scalar(
1100    num: Symbol,
1101    float_ty: ty::FloatTy,
1102    neg: bool,
1103) -> Option<ScalarInt> {
1104    let num = num.as_str();
1105    match float_ty {
1106        // FIXME(f16_f128): When available, compare to the library parser as with `f32` and `f64`
1107        ty::FloatTy::F16 => {
1108            let mut f = num.parse::<Half>().ok()?;
1109            if neg {
1110                f = -f;
1111            }
1112            Some(ScalarInt::from(f))
1113        }
1114        ty::FloatTy::F32 => {
1115            let Ok(rust_f) = num.parse::<f32>() else { return None };
1116            let mut f = num
1117                .parse::<Single>()
1118                .unwrap_or_else(|e| {
    ::core::panicking::panic_fmt(format_args!("apfloat::ieee::Single failed to parse `{0}`: {1:?}",
            num, e));
}panic!("apfloat::ieee::Single failed to parse `{num}`: {e:?}"));
1119
1120            if !(u128::from(rust_f.to_bits()) == f.to_bits()) {
    {
        ::core::panicking::panic_fmt(format_args!("apfloat::ieee::Single gave different result for `{0}`: {1}({2:#x}) vs Rust\'s {3}({4:#x})",
                rust_f, f, f.to_bits(),
                Single::from_bits(rust_f.to_bits().into()),
                rust_f.to_bits()));
    }
};assert!(
1121                u128::from(rust_f.to_bits()) == f.to_bits(),
1122                "apfloat::ieee::Single gave different result for `{}`: \
1123                 {}({:#x}) vs Rust's {}({:#x})",
1124                rust_f,
1125                f,
1126                f.to_bits(),
1127                Single::from_bits(rust_f.to_bits().into()),
1128                rust_f.to_bits()
1129            );
1130
1131            if neg {
1132                f = -f;
1133            }
1134
1135            Some(ScalarInt::from(f))
1136        }
1137        ty::FloatTy::F64 => {
1138            let Ok(rust_f) = num.parse::<f64>() else { return None };
1139            let mut f = num
1140                .parse::<Double>()
1141                .unwrap_or_else(|e| {
    ::core::panicking::panic_fmt(format_args!("apfloat::ieee::Double failed to parse `{0}`: {1:?}",
            num, e));
}panic!("apfloat::ieee::Double failed to parse `{num}`: {e:?}"));
1142
1143            if !(u128::from(rust_f.to_bits()) == f.to_bits()) {
    {
        ::core::panicking::panic_fmt(format_args!("apfloat::ieee::Double gave different result for `{0}`: {1}({2:#x}) vs Rust\'s {3}({4:#x})",
                rust_f, f, f.to_bits(),
                Double::from_bits(rust_f.to_bits().into()),
                rust_f.to_bits()));
    }
};assert!(
1144                u128::from(rust_f.to_bits()) == f.to_bits(),
1145                "apfloat::ieee::Double gave different result for `{}`: \
1146                 {}({:#x}) vs Rust's {}({:#x})",
1147                rust_f,
1148                f,
1149                f.to_bits(),
1150                Double::from_bits(rust_f.to_bits().into()),
1151                rust_f.to_bits()
1152            );
1153
1154            if neg {
1155                f = -f;
1156            }
1157
1158            Some(ScalarInt::from(f))
1159        }
1160        // FIXME(f16_f128): When available, compare to the library parser as with `f32` and `f64`
1161        ty::FloatTy::F128 => {
1162            let mut f = num.parse::<Quad>().ok()?;
1163            if neg {
1164                f = -f;
1165            }
1166            Some(ScalarInt::from(f))
1167        }
1168    }
1169}
1170
1171///////////////////////////////////////////////////////////////////////////
1172// Builder methods are broken up into modules, depending on what kind
1173// of thing is being lowered. Note that they use the `unpack` macro
1174// above extensively.
1175
1176mod block;
1177mod cfg;
1178mod coverageinfo;
1179mod custom;
1180mod expr;
1181mod matches;
1182mod misc;
1183mod scope;