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