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