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