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