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