]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/build/mod.rs
Auto merge of #51729 - matthewjasper:move-errors, r=nikomatsakis
[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 hair::cx::Cx;
14 use hair::{LintLevel, BindingMode, PatternKind};
15 use rustc::hir;
16 use rustc::hir::def_id::{DefId, LocalDefId};
17 use rustc::middle::region;
18 use rustc::mir::*;
19 use rustc::mir::visit::{MutVisitor, TyContext};
20 use rustc::ty::{self, Ty, TyCtxt};
21 use rustc::ty::subst::Substs;
22 use rustc::util::nodemap::NodeMap;
23 use rustc_target::spec::PanicStrategy;
24 use rustc_data_structures::indexed_vec::{IndexVec, Idx};
25 use shim;
26 use std::mem;
27 use std::u32;
28 use rustc_target::spec::abi::Abi;
29 use syntax::ast;
30 use syntax::attr::{self, UnwindAttr};
31 use syntax::symbol::keywords;
32 use syntax_pos::Span;
33 use transform::MirSource;
34 use util as mir_util;
35
36 /// Construct the MIR for a given def-id.
37 pub fn mir_build<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> Mir<'tcx> {
38     let id = tcx.hir.as_local_node_id(def_id).unwrap();
39     let unsupported = || {
40         span_bug!(tcx.hir.span(id), "can't build MIR for {:?}", def_id);
41     };
42
43     // Figure out what primary body this item has.
44     let body_id = match tcx.hir.get(id) {
45         hir::map::NodeVariant(variant) =>
46             return create_constructor_shim(tcx, id, &variant.node.data),
47         hir::map::NodeStructCtor(ctor) =>
48             return create_constructor_shim(tcx, id, ctor),
49
50         _ => match tcx.hir.maybe_body_owned_by(id) {
51             Some(body) => body,
52             None => unsupported(),
53         },
54     };
55
56     tcx.infer_ctxt().enter(|infcx| {
57         let cx = Cx::new(&infcx, id);
58         let mut mir = if cx.tables().tainted_by_errors {
59             build::construct_error(cx, body_id)
60         } else if let hir::BodyOwnerKind::Fn = cx.body_owner_kind {
61             // fetch the fully liberated fn signature (that is, all bound
62             // types/lifetimes replaced)
63             let fn_hir_id = tcx.hir.node_to_hir_id(id);
64             let fn_sig = cx.tables().liberated_fn_sigs()[fn_hir_id].clone();
65
66             let ty = tcx.type_of(tcx.hir.local_def_id(id));
67             let mut abi = fn_sig.abi;
68             let implicit_argument = match ty.sty {
69                 ty::TyClosure(..) => {
70                     // HACK(eddyb) Avoid having RustCall on closures,
71                     // as it adds unnecessary (and wrong) auto-tupling.
72                     abi = Abi::Rust;
73                     Some(ArgInfo(liberated_closure_env_ty(tcx, id, body_id), None, None, None))
74                 }
75                 ty::TyGenerator(..) => {
76                     let gen_ty = tcx.body_tables(body_id).node_id_to_type(fn_hir_id);
77                     Some(ArgInfo(gen_ty, None, None, None))
78                 }
79                 _ => None,
80             };
81
82             // FIXME: safety in closures
83             let safety = match fn_sig.unsafety {
84                 hir::Unsafety::Normal => Safety::Safe,
85                 hir::Unsafety::Unsafe => Safety::FnUnsafe,
86             };
87
88             let body = tcx.hir.body(body_id);
89             let explicit_arguments =
90                 body.arguments
91                     .iter()
92                     .enumerate()
93                     .map(|(index, arg)| {
94                         let owner_id = tcx.hir.body_owner(body_id);
95                         let opt_ty_info;
96                         let self_arg;
97                         if let Some(ref fn_decl) = tcx.hir.fn_decl(owner_id) {
98                             let ty_hir_id = fn_decl.inputs[index].hir_id;
99                             let ty_span = tcx.hir.span(tcx.hir.hir_to_node_id(ty_hir_id));
100                             opt_ty_info = Some(ty_span);
101                             self_arg = if index == 0 && fn_decl.has_implicit_self {
102                                 Some(ImplicitSelfBinding)
103                             } else {
104                                 None
105                             };
106                         } else {
107                             opt_ty_info = None;
108                             self_arg = None;
109                         }
110                         ArgInfo(fn_sig.inputs()[index], opt_ty_info, Some(&*arg.pat), self_arg)
111                     });
112
113             let arguments = implicit_argument.into_iter().chain(explicit_arguments);
114
115             let (yield_ty, return_ty) = if body.is_generator {
116                 let gen_sig = match ty.sty {
117                     ty::TyGenerator(gen_def_id, gen_substs, ..) =>
118                         gen_substs.sig(gen_def_id, tcx),
119                     _ =>
120                         span_bug!(tcx.hir.span(id), "generator w/o generator type: {:?}", ty),
121                 };
122                 (Some(gen_sig.yield_ty), gen_sig.return_ty)
123             } else {
124                 (None, fn_sig.output())
125             };
126
127             build::construct_fn(cx, id, arguments, safety, abi,
128                                 return_ty, yield_ty, body)
129         } else {
130             build::construct_const(cx, body_id)
131         };
132
133         // Convert the Mir to global types.
134         let mut globalizer = GlobalizeMir {
135             tcx,
136             span: mir.span
137         };
138         globalizer.visit_mir(&mut mir);
139         let mir = unsafe {
140             mem::transmute::<Mir, Mir<'tcx>>(mir)
141         };
142
143         mir_util::dump_mir(tcx, None, "mir_map", &0,
144                            MirSource::item(def_id), &mir, |_, _| Ok(()) );
145
146         mir
147     })
148 }
149
150 /// A pass to lift all the types and substitutions in a Mir
151 /// to the global tcx. Sadly, we don't have a "folder" that
152 /// can change 'tcx so we have to transmute afterwards.
153 struct GlobalizeMir<'a, 'gcx: 'a> {
154     tcx: TyCtxt<'a, 'gcx, 'gcx>,
155     span: Span
156 }
157
158 impl<'a, 'gcx: 'tcx, 'tcx> MutVisitor<'tcx> for GlobalizeMir<'a, 'gcx> {
159     fn visit_ty(&mut self, ty: &mut Ty<'tcx>, _: TyContext) {
160         if let Some(lifted) = self.tcx.lift(ty) {
161             *ty = lifted;
162         } else {
163             span_bug!(self.span,
164                       "found type `{:?}` with inference types/regions in MIR",
165                       ty);
166         }
167     }
168
169     fn visit_region(&mut self, region: &mut ty::Region<'tcx>, _: Location) {
170         if let Some(lifted) = self.tcx.lift(region) {
171             *region = lifted;
172         } else {
173             span_bug!(self.span,
174                       "found region `{:?}` with inference types/regions in MIR",
175                       region);
176         }
177     }
178
179     fn visit_const(&mut self, constant: &mut &'tcx ty::Const<'tcx>, _: Location) {
180         if let Some(lifted) = self.tcx.lift(constant) {
181             *constant = lifted;
182         } else {
183             span_bug!(self.span,
184                       "found constant `{:?}` with inference types/regions in MIR",
185                       constant);
186         }
187     }
188
189     fn visit_substs(&mut self, substs: &mut &'tcx Substs<'tcx>, _: Location) {
190         if let Some(lifted) = self.tcx.lift(substs) {
191             *substs = lifted;
192         } else {
193             span_bug!(self.span,
194                       "found substs `{:?}` with inference types/regions in MIR",
195                       substs);
196         }
197     }
198 }
199
200 fn create_constructor_shim<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
201                                      ctor_id: ast::NodeId,
202                                      v: &'tcx hir::VariantData)
203                                      -> Mir<'tcx>
204 {
205     let span = tcx.hir.span(ctor_id);
206     if let hir::VariantData::Tuple(ref fields, ctor_id) = *v {
207         tcx.infer_ctxt().enter(|infcx| {
208             let mut mir = shim::build_adt_ctor(&infcx, ctor_id, fields, span);
209
210             // Convert the Mir to global types.
211             let tcx = infcx.tcx.global_tcx();
212             let mut globalizer = GlobalizeMir {
213                 tcx,
214                 span: mir.span
215             };
216             globalizer.visit_mir(&mut mir);
217             let mir = unsafe {
218                 mem::transmute::<Mir, Mir<'tcx>>(mir)
219             };
220
221             mir_util::dump_mir(tcx, None, "mir_map", &0,
222                                MirSource::item(tcx.hir.local_def_id(ctor_id)),
223                                &mir, |_, _| Ok(()) );
224
225             mir
226         })
227     } else {
228         span_bug!(span, "attempting to create MIR for non-tuple variant {:?}", v);
229     }
230 }
231
232 ///////////////////////////////////////////////////////////////////////////
233 // BuildMir -- walks a crate, looking for fn items and methods to build MIR from
234
235 fn liberated_closure_env_ty<'a, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>,
236                                             closure_expr_id: ast::NodeId,
237                                             body_id: hir::BodyId)
238                                             -> Ty<'tcx> {
239     let closure_expr_hir_id = tcx.hir.node_to_hir_id(closure_expr_id);
240     let closure_ty = tcx.body_tables(body_id).node_id_to_type(closure_expr_hir_id);
241
242     let (closure_def_id, closure_substs) = match closure_ty.sty {
243         ty::TyClosure(closure_def_id, closure_substs) => (closure_def_id, closure_substs),
244         _ => bug!("closure expr does not have closure type: {:?}", closure_ty)
245     };
246
247     let closure_env_ty = tcx.closure_env_ty(closure_def_id, closure_substs).unwrap();
248     tcx.liberate_late_bound_regions(closure_def_id, &closure_env_ty)
249 }
250
251 struct Builder<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
252     hir: Cx<'a, 'gcx, 'tcx>,
253     cfg: CFG<'tcx>,
254
255     fn_span: Span,
256     arg_count: usize,
257
258     /// the current set of scopes, updated as we traverse;
259     /// see the `scope` module for more details
260     scopes: Vec<scope::Scope<'tcx>>,
261
262     /// The current unsafe block in scope, even if it is hidden by
263     /// a PushUnsafeBlock
264     unpushed_unsafe: Safety,
265
266     /// The number of `push_unsafe_block` levels in scope
267     push_unsafe_count: usize,
268
269     /// the current set of breakables; see the `scope` module for more
270     /// details
271     breakable_scopes: Vec<scope::BreakableScope<'tcx>>,
272
273     /// the vector of all scopes that we have created thus far;
274     /// we track this for debuginfo later
275     source_scopes: IndexVec<SourceScope, SourceScopeData>,
276     source_scope_local_data: IndexVec<SourceScope, SourceScopeLocalData>,
277     source_scope: SourceScope,
278
279     /// the guard-context: each time we build the guard expression for
280     /// a match arm, we push onto this stack, and then pop when we
281     /// finish building it.
282     guard_context: Vec<GuardFrame>,
283
284     /// Maps node ids of variable bindings to the `Local`s created for them.
285     /// (A match binding can have two locals; the 2nd is for the arm's guard.)
286     var_indices: NodeMap<LocalsForNode>,
287     local_decls: IndexVec<Local, LocalDecl<'tcx>>,
288     unit_temp: Option<Place<'tcx>>,
289
290     /// cached block with the RESUME terminator; this is created
291     /// when first set of cleanups are built.
292     cached_resume_block: Option<BasicBlock>,
293     /// cached block with the RETURN terminator
294     cached_return_block: Option<BasicBlock>,
295     /// cached block with the UNREACHABLE terminator
296     cached_unreachable_block: Option<BasicBlock>,
297 }
298
299 impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> {
300     fn is_bound_var_in_guard(&self, id: ast::NodeId) -> bool {
301         self.guard_context.iter().any(|frame| frame.locals.iter().any(|local| local.id == id))
302     }
303
304     fn var_local_id(&self, id: ast::NodeId, for_guard: ForGuard) -> Local {
305         self.var_indices[&id].local_id(for_guard)
306     }
307 }
308
309 #[derive(Debug)]
310 enum LocalsForNode {
311     One(Local),
312     Three { val_for_guard: Local, ref_for_guard: Local, for_arm_body: Local },
313 }
314
315 #[derive(Debug)]
316 struct GuardFrameLocal {
317     id: ast::NodeId,
318 }
319
320 impl GuardFrameLocal {
321     fn new(id: ast::NodeId, _binding_mode: BindingMode) -> Self {
322         GuardFrameLocal {
323             id: id,
324         }
325     }
326 }
327
328 #[derive(Debug)]
329 struct GuardFrame {
330     /// These are the id's of names that are bound by patterns of the
331     /// arm of *this* guard.
332     ///
333     /// (Frames higher up the stack will have the id's bound in arms
334     /// further out, such as in a case like:
335     ///
336     /// match E1 {
337     ///      P1(id1) if (... (match E2 { P2(id2) if ... => B2 })) => B1,
338     /// }
339     ///
340     /// here, when building for FIXME
341     locals: Vec<GuardFrameLocal>,
342 }
343
344 /// ForGuard indicates whether we are talking about:
345 ///   1. the temp for a local binding used solely within guard expressions,
346 ///   2. the temp that holds reference to (1.), which is actually what the
347 ///      guard expressions see, or
348 ///   3. the temp for use outside of guard expressions.
349 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
350 enum ForGuard {
351     ValWithinGuard,
352     RefWithinGuard,
353     OutsideGuard,
354 }
355
356 impl LocalsForNode {
357     fn local_id(&self, for_guard: ForGuard) -> Local {
358         match (self, for_guard) {
359             (&LocalsForNode::One(local_id), ForGuard::OutsideGuard) |
360             (&LocalsForNode::Three { val_for_guard: local_id, .. }, ForGuard::ValWithinGuard) |
361             (&LocalsForNode::Three { ref_for_guard: local_id, .. }, ForGuard::RefWithinGuard) |
362             (&LocalsForNode::Three { for_arm_body: local_id, .. }, ForGuard::OutsideGuard) =>
363                 local_id,
364
365             (&LocalsForNode::One(_), ForGuard::ValWithinGuard) |
366             (&LocalsForNode::One(_), ForGuard::RefWithinGuard) =>
367                 bug!("anything with one local should never be within a guard."),
368         }
369     }
370 }
371
372 struct CFG<'tcx> {
373     basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
374 }
375
376 newtype_index!(ScopeId);
377
378 ///////////////////////////////////////////////////////////////////////////
379 /// The `BlockAnd` "monad" packages up the new basic block along with a
380 /// produced value (sometimes just unit, of course). The `unpack!`
381 /// macro (and methods below) makes working with `BlockAnd` much more
382 /// convenient.
383
384 #[must_use = "if you don't use one of these results, you're leaving a dangling edge"]
385 struct BlockAnd<T>(BasicBlock, T);
386
387 trait BlockAndExtension {
388     fn and<T>(self, v: T) -> BlockAnd<T>;
389     fn unit(self) -> BlockAnd<()>;
390 }
391
392 impl BlockAndExtension for BasicBlock {
393     fn and<T>(self, v: T) -> BlockAnd<T> {
394         BlockAnd(self, v)
395     }
396
397     fn unit(self) -> BlockAnd<()> {
398         BlockAnd(self, ())
399     }
400 }
401
402 /// Update a block pointer and return the value.
403 /// Use it like `let x = unpack!(block = self.foo(block, foo))`.
404 macro_rules! unpack {
405     ($x:ident = $c:expr) => {
406         {
407             let BlockAnd(b, v) = $c;
408             $x = b;
409             v
410         }
411     };
412
413     ($c:expr) => {
414         {
415             let BlockAnd(b, ()) = $c;
416             b
417         }
418     };
419 }
420
421 fn should_abort_on_panic<'a, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>,
422                                          fn_def_id: DefId,
423                                          abi: Abi)
424                                          -> bool {
425     // Not callable from C, so we can safely unwind through these
426     if abi == Abi::Rust || abi == Abi::RustCall { return false; }
427
428     // We never unwind, so it's not relevant to stop an unwind
429     if tcx.sess.panic_strategy() != PanicStrategy::Unwind { return false; }
430
431     // We cannot add landing pads, so don't add one
432     if tcx.sess.no_landing_pads() { return false; }
433
434     // This is a special case: some functions have a C abi but are meant to
435     // unwind anyway. Don't stop them.
436     let attrs = &tcx.get_attrs(fn_def_id);
437     match attr::find_unwind_attr(Some(tcx.sess.diagnostic()), attrs) {
438         None => {
439             // FIXME(rust-lang/rust#48251) -- Had to disable
440             // abort-on-panic for backwards compatibility reasons.
441             false
442         }
443
444         Some(UnwindAttr::Allowed) => false,
445         Some(UnwindAttr::Aborts) => true,
446     }
447 }
448
449 ///////////////////////////////////////////////////////////////////////////
450 /// the main entry point for building MIR for a function
451
452 struct ImplicitSelfBinding;
453
454 struct ArgInfo<'gcx>(Ty<'gcx>,
455                      Option<Span>,
456                      Option<&'gcx hir::Pat>,
457                      Option<ImplicitSelfBinding>);
458
459 fn construct_fn<'a, 'gcx, 'tcx, A>(hir: Cx<'a, 'gcx, 'tcx>,
460                                    fn_id: ast::NodeId,
461                                    arguments: A,
462                                    safety: Safety,
463                                    abi: Abi,
464                                    return_ty: Ty<'gcx>,
465                                    yield_ty: Option<Ty<'gcx>>,
466                                    body: &'gcx hir::Body)
467                                    -> Mir<'tcx>
468     where A: Iterator<Item=ArgInfo<'gcx>>
469 {
470     let arguments: Vec<_> = arguments.collect();
471
472     let tcx = hir.tcx();
473     let span = tcx.hir.span(fn_id);
474     let mut builder = Builder::new(hir.clone(),
475         span,
476         arguments.len(),
477         safety,
478         return_ty);
479
480     let fn_def_id = tcx.hir.local_def_id(fn_id);
481     let call_site_scope = region::Scope::CallSite(body.value.hir_id.local_id);
482     let arg_scope = region::Scope::Arguments(body.value.hir_id.local_id);
483     let mut block = START_BLOCK;
484     let source_info = builder.source_info(span);
485     let call_site_s = (call_site_scope, source_info);
486     unpack!(block = builder.in_scope(call_site_s, LintLevel::Inherited, block, |builder| {
487         if should_abort_on_panic(tcx, fn_def_id, abi) {
488             builder.schedule_abort();
489         }
490
491         let arg_scope_s = (arg_scope, source_info);
492         unpack!(block = builder.in_scope(arg_scope_s, LintLevel::Inherited, block, |builder| {
493             builder.args_and_body(block, &arguments, arg_scope, &body.value)
494         }));
495         // Attribute epilogue to function's closing brace
496         let fn_end = span.shrink_to_hi();
497         let source_info = builder.source_info(fn_end);
498         let return_block = builder.return_block();
499         builder.cfg.terminate(block, source_info,
500                               TerminatorKind::Goto { target: return_block });
501         builder.cfg.terminate(return_block, source_info,
502                               TerminatorKind::Return);
503         // Attribute any unreachable codepaths to the function's closing brace
504         if let Some(unreachable_block) = builder.cached_unreachable_block {
505             builder.cfg.terminate(unreachable_block, source_info,
506                                   TerminatorKind::Unreachable);
507         }
508         return_block.unit()
509     }));
510     assert_eq!(block, builder.return_block());
511
512     let mut spread_arg = None;
513     if abi == Abi::RustCall {
514         // RustCall pseudo-ABI untuples the last argument.
515         spread_arg = Some(Local::new(arguments.len()));
516     }
517     let closure_expr_id = tcx.hir.local_def_id(fn_id);
518     info!("fn_id {:?} has attrs {:?}", closure_expr_id,
519           tcx.get_attrs(closure_expr_id));
520
521     // Gather the upvars of a closure, if any.
522     let upvar_decls: Vec<_> = tcx.with_freevars(fn_id, |freevars| {
523         freevars.iter().map(|fv| {
524             let var_id = fv.var_id();
525             let var_hir_id = tcx.hir.node_to_hir_id(var_id);
526             let closure_expr_id = tcx.hir.local_def_id(fn_id);
527             let capture = hir.tables().upvar_capture(ty::UpvarId {
528                 var_id: var_hir_id,
529                 closure_expr_id: LocalDefId::from_def_id(closure_expr_id),
530             });
531             let by_ref = match capture {
532                 ty::UpvarCapture::ByValue => false,
533                 ty::UpvarCapture::ByRef(..) => true
534             };
535             let mut decl = UpvarDecl {
536                 debug_name: keywords::Invalid.name(),
537                 by_ref,
538                 mutability: Mutability::Not,
539             };
540             if let Some(hir::map::NodeBinding(pat)) = tcx.hir.find(var_id) {
541                 if let hir::PatKind::Binding(_, _, ident, _) = pat.node {
542                     decl.debug_name = ident.name;
543
544                     let bm = *hir.tables.pat_binding_modes()
545                                         .get(pat.hir_id)
546                                         .expect("missing binding mode");
547                     if bm == ty::BindByValue(hir::MutMutable) {
548                         decl.mutability = Mutability::Mut;
549                     } else {
550                         decl.mutability = Mutability::Not;
551                     }
552                 }
553             }
554             decl
555         }).collect()
556     });
557
558     let mut mir = builder.finish(upvar_decls, yield_ty);
559     mir.spread_arg = spread_arg;
560     mir
561 }
562
563 fn construct_const<'a, 'gcx, 'tcx>(hir: Cx<'a, 'gcx, 'tcx>,
564                                    body_id: hir::BodyId)
565                                    -> Mir<'tcx> {
566     let tcx = hir.tcx();
567     let ast_expr = &tcx.hir.body(body_id).value;
568     let ty = hir.tables().expr_ty_adjusted(ast_expr);
569     let owner_id = tcx.hir.body_owner(body_id);
570     let span = tcx.hir.span(owner_id);
571     let mut builder = Builder::new(hir.clone(), span, 0, Safety::Safe, ty);
572
573     let mut block = START_BLOCK;
574     let expr = builder.hir.mirror(ast_expr);
575     unpack!(block = builder.into_expr(&Place::Local(RETURN_PLACE), block, expr));
576
577     let source_info = builder.source_info(span);
578     builder.cfg.terminate(block, source_info, TerminatorKind::Return);
579
580     // Constants can't `return` so a return block should not be created.
581     assert_eq!(builder.cached_return_block, None);
582
583     // Constants may be match expressions in which case an unreachable block may
584     // be created, so terminate it properly.
585     if let Some(unreachable_block) = builder.cached_unreachable_block {
586         builder.cfg.terminate(unreachable_block, source_info,
587                               TerminatorKind::Unreachable);
588     }
589
590     builder.finish(vec![], None)
591 }
592
593 fn construct_error<'a, 'gcx, 'tcx>(hir: Cx<'a, 'gcx, 'tcx>,
594                                    body_id: hir::BodyId)
595                                    -> Mir<'tcx> {
596     let owner_id = hir.tcx().hir.body_owner(body_id);
597     let span = hir.tcx().hir.span(owner_id);
598     let ty = hir.tcx().types.err;
599     let mut builder = Builder::new(hir, span, 0, Safety::Safe, ty);
600     let source_info = builder.source_info(span);
601     builder.cfg.terminate(START_BLOCK, source_info, TerminatorKind::Unreachable);
602     builder.finish(vec![], None)
603 }
604
605 impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> {
606     fn new(hir: Cx<'a, 'gcx, 'tcx>,
607            span: Span,
608            arg_count: usize,
609            safety: Safety,
610            return_ty: Ty<'tcx>)
611            -> Builder<'a, 'gcx, 'tcx> {
612         let lint_level = LintLevel::Explicit(hir.root_lint_level);
613         let mut builder = Builder {
614             hir,
615             cfg: CFG { basic_blocks: IndexVec::new() },
616             fn_span: span,
617             arg_count,
618             scopes: vec![],
619             source_scopes: IndexVec::new(),
620             source_scope: OUTERMOST_SOURCE_SCOPE,
621             source_scope_local_data: IndexVec::new(),
622             guard_context: vec![],
623             push_unsafe_count: 0,
624             unpushed_unsafe: safety,
625             breakable_scopes: vec![],
626             local_decls: IndexVec::from_elem_n(LocalDecl::new_return_place(return_ty,
627                                                                              span), 1),
628             var_indices: NodeMap(),
629             unit_temp: None,
630             cached_resume_block: None,
631             cached_return_block: None,
632             cached_unreachable_block: None,
633         };
634
635         assert_eq!(builder.cfg.start_new_block(), START_BLOCK);
636         assert_eq!(
637             builder.new_source_scope(span, lint_level, Some(safety)),
638             OUTERMOST_SOURCE_SCOPE);
639         builder.source_scopes[OUTERMOST_SOURCE_SCOPE].parent_scope = None;
640
641         builder
642     }
643
644     fn finish(self,
645               upvar_decls: Vec<UpvarDecl>,
646               yield_ty: Option<Ty<'tcx>>)
647               -> Mir<'tcx> {
648         for (index, block) in self.cfg.basic_blocks.iter().enumerate() {
649             if block.terminator.is_none() {
650                 span_bug!(self.fn_span, "no terminator on block {:?}", index);
651             }
652         }
653
654         Mir::new(self.cfg.basic_blocks,
655                  self.source_scopes,
656                  ClearCrossCrate::Set(self.source_scope_local_data),
657                  IndexVec::new(),
658                  yield_ty,
659                  self.local_decls,
660                  self.arg_count,
661                  upvar_decls,
662                  self.fn_span
663         )
664     }
665
666     fn args_and_body(&mut self,
667                      mut block: BasicBlock,
668                      arguments: &[ArgInfo<'gcx>],
669                      argument_scope: region::Scope,
670                      ast_body: &'gcx hir::Expr)
671                      -> BlockAnd<()>
672     {
673         // Allocate locals for the function arguments
674         for &ArgInfo(ty, _, pattern, _) in arguments.iter() {
675             // If this is a simple binding pattern, give the local a nice name for debuginfo.
676             let mut name = None;
677             if let Some(pat) = pattern {
678                 if let hir::PatKind::Binding(_, _, ident, _) = pat.node {
679                     name = Some(ident.name);
680                 }
681             }
682
683             let source_info = SourceInfo {
684                 scope: OUTERMOST_SOURCE_SCOPE,
685                 span: pattern.map_or(self.fn_span, |pat| pat.span)
686             };
687             self.local_decls.push(LocalDecl {
688                 mutability: Mutability::Mut,
689                 ty,
690                 source_info,
691                 visibility_scope: source_info.scope,
692                 name,
693                 internal: false,
694                 is_user_variable: None,
695             });
696         }
697
698         let mut scope = None;
699         // Bind the argument patterns
700         for (index, arg_info) in arguments.iter().enumerate() {
701             // Function arguments always get the first Local indices after the return place
702             let local = Local::new(index + 1);
703             let place = Place::Local(local);
704             let &ArgInfo(ty, opt_ty_info, pattern, ref self_binding) = arg_info;
705
706             if let Some(pattern) = pattern {
707                 let pattern = self.hir.pattern_from_hir(pattern);
708                 let span = pattern.span;
709
710                 match *pattern.kind {
711                     // Don't introduce extra copies for simple bindings
712                     PatternKind::Binding { mutability, var, mode: BindingMode::ByValue, .. } => {
713                         self.local_decls[local].mutability = mutability;
714                         self.local_decls[local].is_user_variable =
715                             if let Some(ImplicitSelfBinding) = self_binding {
716                                 Some(ClearCrossCrate::Set(BindingForm::ImplicitSelf))
717                             } else {
718                                 let binding_mode = ty::BindingMode::BindByValue(mutability.into());
719                                 Some(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
720                                     binding_mode,
721                                     opt_ty_info,
722                                     opt_match_place: Some((Some(place.clone()), span)),
723                                 })))
724                             };
725                         self.var_indices.insert(var, LocalsForNode::One(local));
726                     }
727                     _ => {
728                         scope = self.declare_bindings(scope, ast_body.span,
729                                                       LintLevel::Inherited, &pattern,
730                                                       matches::ArmHasGuard(false),
731                                                       Some((Some(&place), span)));
732                         unpack!(block = self.place_into_pattern(block, pattern, &place, false));
733                     }
734                 }
735             }
736
737             // Make sure we drop (parts of) the argument even when not matched on.
738             self.schedule_drop(pattern.as_ref().map_or(ast_body.span, |pat| pat.span),
739                                argument_scope, &place, ty);
740
741         }
742
743         // Enter the argument pattern bindings source scope, if it exists.
744         if let Some(source_scope) = scope {
745             self.source_scope = source_scope;
746         }
747
748         let body = self.hir.mirror(ast_body);
749         self.into(&Place::Local(RETURN_PLACE), block, body)
750     }
751
752     fn get_unit_temp(&mut self) -> Place<'tcx> {
753         match self.unit_temp {
754             Some(ref tmp) => tmp.clone(),
755             None => {
756                 let ty = self.hir.unit_ty();
757                 let fn_span = self.fn_span;
758                 let tmp = self.temp(ty, fn_span);
759                 self.unit_temp = Some(tmp.clone());
760                 tmp
761             }
762         }
763     }
764
765     fn return_block(&mut self) -> BasicBlock {
766         match self.cached_return_block {
767             Some(rb) => rb,
768             None => {
769                 let rb = self.cfg.start_new_block();
770                 self.cached_return_block = Some(rb);
771                 rb
772             }
773         }
774     }
775
776     fn unreachable_block(&mut self) -> BasicBlock {
777         match self.cached_unreachable_block {
778             Some(ub) => ub,
779             None => {
780                 let ub = self.cfg.start_new_block();
781                 self.cached_unreachable_block = Some(ub);
782                 ub
783             }
784         }
785     }
786 }
787
788 ///////////////////////////////////////////////////////////////////////////
789 // Builder methods are broken up into modules, depending on what kind
790 // of thing is being lowered. Note that they use the `unpack` macro
791 // above extensively.
792
793 mod block;
794 mod cfg;
795 mod expr;
796 mod into;
797 mod matches;
798 mod misc;
799 mod scope;