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