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