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