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