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