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