]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/build/mod.rs
Mir: fixup nits in previous commit (f536143)
[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;
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_back::PanicStrategy;
24 use rustc_const_eval::pattern::{BindingMode, PatternKind};
25 use rustc_data_structures::indexed_vec::{IndexVec, Idx};
26 use shim;
27 use std::mem;
28 use std::u32;
29 use syntax::abi::Abi;
30 use syntax::ast;
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::NodeItem(item) => {
46             match item.node {
47                 hir::ItemConst(_, body) |
48                 hir::ItemStatic(_, _, body) |
49                 hir::ItemFn(.., body) => body,
50                 _ => unsupported()
51             }
52         }
53         hir::map::NodeTraitItem(item) => {
54             match item.node {
55                 hir::TraitItemKind::Const(_, Some(body)) |
56                 hir::TraitItemKind::Method(_,
57                     hir::TraitMethod::Provided(body)) => body,
58                 _ => unsupported()
59             }
60         }
61         hir::map::NodeImplItem(item) => {
62             match item.node {
63                 hir::ImplItemKind::Const(_, body) |
64                 hir::ImplItemKind::Method(_, body) => body,
65                 _ => unsupported()
66             }
67         }
68         hir::map::NodeExpr(expr) => {
69             // FIXME(eddyb) Closures should have separate
70             // function definition IDs and expression IDs.
71             // Type-checking should not let closures get
72             // this far in a constant position.
73             // Assume that everything other than closures
74             // is a constant "initializer" expression.
75             match expr.node {
76                 hir::ExprClosure(_, _, body, _, _) => body,
77                 _ => hir::BodyId { node_id: expr.id },
78             }
79         }
80         hir::map::NodeVariant(variant) =>
81             return create_constructor_shim(tcx, id, &variant.node.data),
82         hir::map::NodeStructCtor(ctor) =>
83             return create_constructor_shim(tcx, id, ctor),
84         _ => unsupported(),
85     };
86
87     tcx.infer_ctxt().enter(|infcx| {
88         let cx = Cx::new(&infcx, id);
89         let mut mir = if cx.tables().tainted_by_errors {
90             build::construct_error(cx, body_id)
91         } else if let hir::BodyOwnerKind::Fn = cx.body_owner_kind {
92             // fetch the fully liberated fn signature (that is, all bound
93             // types/lifetimes replaced)
94             let fn_hir_id = tcx.hir.node_to_hir_id(id);
95             let fn_sig = cx.tables().liberated_fn_sigs()[fn_hir_id].clone();
96
97             let ty = tcx.type_of(tcx.hir.local_def_id(id));
98             let mut abi = fn_sig.abi;
99             let implicit_argument = match ty.sty {
100                 ty::TyClosure(..) => {
101                     // HACK(eddyb) Avoid having RustCall on closures,
102                     // as it adds unnecessary (and wrong) auto-tupling.
103                     abi = Abi::Rust;
104                     Some((liberated_closure_env_ty(tcx, id, body_id), None))
105                 }
106                 ty::TyGenerator(..) => {
107                     let gen_ty = tcx.body_tables(body_id).node_id_to_type(fn_hir_id);
108                     Some((gen_ty, 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
119             let body = tcx.hir.body(body_id);
120             let explicit_arguments =
121                 body.arguments
122                     .iter()
123                     .enumerate()
124                     .map(|(index, arg)| {
125                         (fn_sig.inputs()[index], Some(&*arg.pat))
126                     });
127
128             let arguments = implicit_argument.into_iter().chain(explicit_arguments);
129
130             let (yield_ty, return_ty) = if body.is_generator {
131                 let gen_sig = match ty.sty {
132                     ty::TyGenerator(gen_def_id, gen_substs, ..) =>
133                         gen_substs.generator_sig(gen_def_id, tcx),
134                     _ =>
135                         span_bug!(tcx.hir.span(id), "generator w/o generator type: {:?}", ty),
136                 };
137                 (Some(gen_sig.yield_ty), gen_sig.return_ty)
138             } else {
139                 (None, fn_sig.output())
140             };
141
142             build::construct_fn(cx, id, arguments, safety, abi,
143                                 return_ty, yield_ty, body)
144         } else {
145             build::construct_const(cx, body_id)
146         };
147
148         // Convert the Mir to global types.
149         let mut globalizer = GlobalizeMir {
150             tcx,
151             span: mir.span
152         };
153         globalizer.visit_mir(&mut mir);
154         let mir = unsafe {
155             mem::transmute::<Mir, Mir<'tcx>>(mir)
156         };
157
158         mir_util::dump_mir(tcx, None, "mir_map", &0,
159                            MirSource::item(def_id), &mir, |_, _| Ok(()) );
160
161         mir
162     })
163 }
164
165 /// A pass to lift all the types and substitutions in a Mir
166 /// to the global tcx. Sadly, we don't have a "folder" that
167 /// can change 'tcx so we have to transmute afterwards.
168 struct GlobalizeMir<'a, 'gcx: 'a> {
169     tcx: TyCtxt<'a, 'gcx, 'gcx>,
170     span: Span
171 }
172
173 impl<'a, 'gcx: 'tcx, 'tcx> MutVisitor<'tcx> for GlobalizeMir<'a, 'gcx> {
174     fn visit_ty(&mut self, ty: &mut Ty<'tcx>, _: TyContext) {
175         if let Some(lifted) = self.tcx.lift(ty) {
176             *ty = lifted;
177         } else {
178             span_bug!(self.span,
179                       "found type `{:?}` with inference types/regions in MIR",
180                       ty);
181         }
182     }
183
184     fn visit_region(&mut self, region: &mut ty::Region<'tcx>, _: Location) {
185         if let Some(lifted) = self.tcx.lift(region) {
186             *region = lifted;
187         } else {
188             span_bug!(self.span,
189                       "found region `{:?}` with inference types/regions in MIR",
190                       region);
191         }
192     }
193
194     fn visit_const(&mut self, constant: &mut &'tcx ty::Const<'tcx>, _: Location) {
195         if let Some(lifted) = self.tcx.lift(constant) {
196             *constant = lifted;
197         } else {
198             span_bug!(self.span,
199                       "found constant `{:?}` with inference types/regions in MIR",
200                       constant);
201         }
202     }
203
204     fn visit_substs(&mut self, substs: &mut &'tcx Substs<'tcx>, _: Location) {
205         if let Some(lifted) = self.tcx.lift(substs) {
206             *substs = lifted;
207         } else {
208             span_bug!(self.span,
209                       "found substs `{:?}` with inference types/regions in MIR",
210                       substs);
211         }
212     }
213 }
214
215 fn create_constructor_shim<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
216                                      ctor_id: ast::NodeId,
217                                      v: &'tcx hir::VariantData)
218                                      -> Mir<'tcx>
219 {
220     let span = tcx.hir.span(ctor_id);
221     if let hir::VariantData::Tuple(ref fields, ctor_id) = *v {
222         tcx.infer_ctxt().enter(|infcx| {
223             let mut mir = shim::build_adt_ctor(&infcx, ctor_id, fields, span);
224
225             // Convert the Mir to global types.
226             let tcx = infcx.tcx.global_tcx();
227             let mut globalizer = GlobalizeMir {
228                 tcx,
229                 span: mir.span
230             };
231             globalizer.visit_mir(&mut mir);
232             let mir = unsafe {
233                 mem::transmute::<Mir, Mir<'tcx>>(mir)
234             };
235
236             mir_util::dump_mir(tcx, None, "mir_map", &0,
237                                MirSource::item(tcx.hir.local_def_id(ctor_id)),
238                                &mir, |_, _| Ok(()) );
239
240             mir
241         })
242     } else {
243         span_bug!(span, "attempting to create MIR for non-tuple variant {:?}", v);
244     }
245 }
246
247 ///////////////////////////////////////////////////////////////////////////
248 // BuildMir -- walks a crate, looking for fn items and methods to build MIR from
249
250 fn liberated_closure_env_ty<'a, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>,
251                                             closure_expr_id: ast::NodeId,
252                                             body_id: hir::BodyId)
253                                             -> Ty<'tcx> {
254     let closure_expr_hir_id = tcx.hir.node_to_hir_id(closure_expr_id);
255     let closure_ty = tcx.body_tables(body_id).node_id_to_type(closure_expr_hir_id);
256
257     let (closure_def_id, closure_substs) = match closure_ty.sty {
258         ty::TyClosure(closure_def_id, closure_substs) => (closure_def_id, closure_substs),
259         _ => bug!("closure expr does not have closure type: {:?}", closure_ty)
260     };
261
262     let closure_env_ty = tcx.closure_env_ty(closure_def_id, closure_substs).unwrap();
263     tcx.liberate_late_bound_regions(closure_def_id, &closure_env_ty)
264 }
265
266 struct Builder<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
267     hir: Cx<'a, 'gcx, 'tcx>,
268     cfg: CFG<'tcx>,
269
270     fn_span: Span,
271     arg_count: usize,
272
273     /// the current set of scopes, updated as we traverse;
274     /// see the `scope` module for more details
275     scopes: Vec<scope::Scope<'tcx>>,
276
277     /// The current unsafe block in scope, even if it is hidden by
278     /// a PushUnsafeBlock
279     unpushed_unsafe: Safety,
280
281     /// The number of `push_unsafe_block` levels in scope
282     push_unsafe_count: usize,
283
284     /// the current set of breakables; see the `scope` module for more
285     /// details
286     breakable_scopes: Vec<scope::BreakableScope<'tcx>>,
287
288     /// the vector of all scopes that we have created thus far;
289     /// we track this for debuginfo later
290     visibility_scopes: IndexVec<VisibilityScope, VisibilityScopeData>,
291     visibility_scope_info: IndexVec<VisibilityScope, VisibilityScopeInfo>,
292     visibility_scope: VisibilityScope,
293
294     /// Maps node ids of variable bindings to the `Local`s created for them.
295     var_indices: NodeMap<Local>,
296     local_decls: IndexVec<Local, LocalDecl<'tcx>>,
297     unit_temp: Option<Place<'tcx>>,
298
299     /// cached block with the RESUME terminator; this is created
300     /// when first set of cleanups are built.
301     cached_resume_block: Option<BasicBlock>,
302     /// cached block with the RETURN terminator
303     cached_return_block: Option<BasicBlock>,
304     /// cached block with the UNREACHABLE terminator
305     cached_unreachable_block: Option<BasicBlock>,
306 }
307
308 struct CFG<'tcx> {
309     basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
310 }
311
312 newtype_index!(ScopeId);
313
314 ///////////////////////////////////////////////////////////////////////////
315 /// The `BlockAnd` "monad" packages up the new basic block along with a
316 /// produced value (sometimes just unit, of course). The `unpack!`
317 /// macro (and methods below) makes working with `BlockAnd` much more
318 /// convenient.
319
320 #[must_use] // if you don't use one of these results, you're leaving a dangling edge
321 struct BlockAnd<T>(BasicBlock, T);
322
323 trait BlockAndExtension {
324     fn and<T>(self, v: T) -> BlockAnd<T>;
325     fn unit(self) -> BlockAnd<()>;
326 }
327
328 impl BlockAndExtension for BasicBlock {
329     fn and<T>(self, v: T) -> BlockAnd<T> {
330         BlockAnd(self, v)
331     }
332
333     fn unit(self) -> BlockAnd<()> {
334         BlockAnd(self, ())
335     }
336 }
337
338 /// Update a block pointer and return the value.
339 /// Use it like `let x = unpack!(block = self.foo(block, foo))`.
340 macro_rules! unpack {
341     ($x:ident = $c:expr) => {
342         {
343             let BlockAnd(b, v) = $c;
344             $x = b;
345             v
346         }
347     };
348
349     ($c:expr) => {
350         {
351             let BlockAnd(b, ()) = $c;
352             b
353         }
354     };
355 }
356
357 fn should_abort_on_panic<'a, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>,
358                                          fn_id: ast::NodeId,
359                                          abi: Abi)
360                                          -> bool {
361
362     // Not callable from C, so we can safely unwind through these
363     if abi == Abi::Rust || abi == Abi::RustCall { return false; }
364
365     // We never unwind, so it's not relevant to stop an unwind
366     if tcx.sess.panic_strategy() != PanicStrategy::Unwind { return false; }
367
368     // We cannot add landing pads, so don't add one
369     if tcx.sess.no_landing_pads() { return false; }
370
371     // This is a special case: some functions have a C abi but are meant to
372     // unwind anyway. Don't stop them.
373     if tcx.has_attr(tcx.hir.local_def_id(fn_id), "unwind") { return false; }
374
375     return true;
376 }
377
378 ///////////////////////////////////////////////////////////////////////////
379 /// the main entry point for building MIR for a function
380
381 fn construct_fn<'a, 'gcx, 'tcx, A>(hir: Cx<'a, 'gcx, 'tcx>,
382                                    fn_id: ast::NodeId,
383                                    arguments: A,
384                                    safety: Safety,
385                                    abi: Abi,
386                                    return_ty: Ty<'gcx>,
387                                    yield_ty: Option<Ty<'gcx>>,
388                                    body: &'gcx hir::Body)
389                                    -> Mir<'tcx>
390     where A: Iterator<Item=(Ty<'gcx>, Option<&'gcx hir::Pat>)>
391 {
392     let arguments: Vec<_> = arguments.collect();
393
394     let tcx = hir.tcx();
395     let span = tcx.hir.span(fn_id);
396     let mut builder = Builder::new(hir.clone(),
397         span,
398         arguments.len(),
399         safety,
400         return_ty);
401
402     let call_site_scope = region::Scope::CallSite(body.value.hir_id.local_id);
403     let arg_scope = region::Scope::Arguments(body.value.hir_id.local_id);
404     let mut block = START_BLOCK;
405     let source_info = builder.source_info(span);
406     let call_site_s = (call_site_scope, source_info);
407     unpack!(block = builder.in_scope(call_site_s, LintLevel::Inherited, block, |builder| {
408         if should_abort_on_panic(tcx, fn_id, abi) {
409             builder.schedule_abort();
410         }
411
412         let arg_scope_s = (arg_scope, source_info);
413         unpack!(block = builder.in_scope(arg_scope_s, LintLevel::Inherited, block, |builder| {
414             builder.args_and_body(block, &arguments, arg_scope, &body.value)
415         }));
416         // Attribute epilogue to function's closing brace
417         let fn_end = span.with_lo(span.hi());
418         let source_info = builder.source_info(fn_end);
419         let return_block = builder.return_block();
420         builder.cfg.terminate(block, source_info,
421                               TerminatorKind::Goto { target: return_block });
422         builder.cfg.terminate(return_block, source_info,
423                               TerminatorKind::Return);
424         // Attribute any unreachable codepaths to the function's closing brace
425         if let Some(unreachable_block) = builder.cached_unreachable_block {
426             builder.cfg.terminate(unreachable_block, source_info,
427                                   TerminatorKind::Unreachable);
428         }
429         return_block.unit()
430     }));
431     assert_eq!(block, builder.return_block());
432
433     let mut spread_arg = None;
434     if abi == Abi::RustCall {
435         // RustCall pseudo-ABI untuples the last argument.
436         spread_arg = Some(Local::new(arguments.len()));
437     }
438
439     // Gather the upvars of a closure, if any.
440     let upvar_decls: Vec<_> = tcx.with_freevars(fn_id, |freevars| {
441         freevars.iter().map(|fv| {
442             let var_id = fv.var_id();
443             let var_hir_id = tcx.hir.node_to_hir_id(var_id);
444             let closure_expr_id = tcx.hir.local_def_id(fn_id);
445             let capture = hir.tables().upvar_capture(ty::UpvarId {
446                 var_id: var_hir_id,
447                 closure_expr_id: LocalDefId::from_def_id(closure_expr_id),
448             });
449             let by_ref = match capture {
450                 ty::UpvarCapture::ByValue => false,
451                 ty::UpvarCapture::ByRef(..) => true
452             };
453             let mut decl = UpvarDecl {
454                 debug_name: keywords::Invalid.name(),
455                 by_ref,
456                 mutability: Mutability::Not,
457             };
458             if let Some(hir::map::NodeBinding(pat)) = tcx.hir.find(var_id) {
459                 if let hir::PatKind::Binding(_, _, ref ident, _) = pat.node {
460                     decl.debug_name = ident.node;
461
462                     let bm = *hir.tables.pat_binding_modes()
463                                         .get(pat.hir_id)
464                                         .expect("missing binding mode");
465                     if bm == ty::BindByValue(hir::MutMutable) {
466                         decl.mutability = Mutability::Mut;
467                     } else {
468                         decl.mutability = Mutability::Not;
469                     }
470                 }
471             }
472             decl
473         }).collect()
474     });
475
476     let mut mir = builder.finish(upvar_decls, yield_ty);
477     mir.spread_arg = spread_arg;
478     mir
479 }
480
481 fn construct_const<'a, 'gcx, 'tcx>(hir: Cx<'a, 'gcx, 'tcx>,
482                                    body_id: hir::BodyId)
483                                    -> Mir<'tcx> {
484     let tcx = hir.tcx();
485     let ast_expr = &tcx.hir.body(body_id).value;
486     let ty = hir.tables().expr_ty_adjusted(ast_expr);
487     let owner_id = tcx.hir.body_owner(body_id);
488     let span = tcx.hir.span(owner_id);
489     let mut builder = Builder::new(hir.clone(), span, 0, Safety::Safe, ty);
490
491     let mut block = START_BLOCK;
492     let expr = builder.hir.mirror(ast_expr);
493     unpack!(block = builder.into_expr(&Place::Local(RETURN_PLACE), block, expr));
494
495     let source_info = builder.source_info(span);
496     builder.cfg.terminate(block, source_info, TerminatorKind::Return);
497
498     // Constants can't `return` so a return block should not be created.
499     assert_eq!(builder.cached_return_block, None);
500
501     builder.finish(vec![], None)
502 }
503
504 fn construct_error<'a, 'gcx, 'tcx>(hir: Cx<'a, 'gcx, 'tcx>,
505                                    body_id: hir::BodyId)
506                                    -> Mir<'tcx> {
507     let owner_id = hir.tcx().hir.body_owner(body_id);
508     let span = hir.tcx().hir.span(owner_id);
509     let ty = hir.tcx().types.err;
510     let mut builder = Builder::new(hir, span, 0, Safety::Safe, ty);
511     let source_info = builder.source_info(span);
512     builder.cfg.terminate(START_BLOCK, source_info, TerminatorKind::Unreachable);
513     builder.finish(vec![], None)
514 }
515
516 impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> {
517     fn new(hir: Cx<'a, 'gcx, 'tcx>,
518            span: Span,
519            arg_count: usize,
520            safety: Safety,
521            return_ty: Ty<'tcx>)
522            -> Builder<'a, 'gcx, 'tcx> {
523         let lint_level = LintLevel::Explicit(hir.root_lint_level);
524         let mut builder = Builder {
525             hir,
526             cfg: CFG { basic_blocks: IndexVec::new() },
527             fn_span: span,
528             arg_count,
529             scopes: vec![],
530             visibility_scopes: IndexVec::new(),
531             visibility_scope: ARGUMENT_VISIBILITY_SCOPE,
532             visibility_scope_info: IndexVec::new(),
533             push_unsafe_count: 0,
534             unpushed_unsafe: safety,
535             breakable_scopes: vec![],
536             local_decls: IndexVec::from_elem_n(LocalDecl::new_return_place(return_ty,
537                                                                              span), 1),
538             var_indices: NodeMap(),
539             unit_temp: None,
540             cached_resume_block: None,
541             cached_return_block: None,
542             cached_unreachable_block: None,
543         };
544
545         assert_eq!(builder.cfg.start_new_block(), START_BLOCK);
546         assert_eq!(
547             builder.new_visibility_scope(span, lint_level, Some(safety)),
548             ARGUMENT_VISIBILITY_SCOPE);
549         builder.visibility_scopes[ARGUMENT_VISIBILITY_SCOPE].parent_scope = None;
550
551         builder
552     }
553
554     fn finish(self,
555               upvar_decls: Vec<UpvarDecl>,
556               yield_ty: Option<Ty<'tcx>>)
557               -> Mir<'tcx> {
558         for (index, block) in self.cfg.basic_blocks.iter().enumerate() {
559             if block.terminator.is_none() {
560                 span_bug!(self.fn_span, "no terminator on block {:?}", index);
561             }
562         }
563
564         Mir::new(self.cfg.basic_blocks,
565                  self.visibility_scopes,
566                  ClearCrossCrate::Set(self.visibility_scope_info),
567                  IndexVec::new(),
568                  yield_ty,
569                  self.local_decls,
570                  self.arg_count,
571                  upvar_decls,
572                  self.fn_span
573         )
574     }
575
576     fn args_and_body(&mut self,
577                      mut block: BasicBlock,
578                      arguments: &[(Ty<'gcx>, Option<&'gcx hir::Pat>)],
579                      argument_scope: region::Scope,
580                      ast_body: &'gcx hir::Expr)
581                      -> BlockAnd<()>
582     {
583         // Allocate locals for the function arguments
584         for &(ty, pattern) in arguments.iter() {
585             // If this is a simple binding pattern, give the local a nice name for debuginfo.
586             let mut name = None;
587             if let Some(pat) = pattern {
588                 if let hir::PatKind::Binding(_, _, ref ident, _) = pat.node {
589                     name = Some(ident.node);
590                 }
591             }
592
593             self.local_decls.push(LocalDecl {
594                 mutability: Mutability::Mut,
595                 ty,
596                 source_info: SourceInfo {
597                     scope: ARGUMENT_VISIBILITY_SCOPE,
598                     span: pattern.map_or(self.fn_span, |pat| pat.span)
599                 },
600                 lexical_scope: ARGUMENT_VISIBILITY_SCOPE,
601                 name,
602                 internal: false,
603                 is_user_variable: false,
604             });
605         }
606
607         let mut scope = None;
608         // Bind the argument patterns
609         for (index, &(ty, pattern)) in arguments.iter().enumerate() {
610             // Function arguments always get the first Local indices after the return place
611             let local = Local::new(index + 1);
612             let place = Place::Local(local);
613
614             if let Some(pattern) = pattern {
615                 let pattern = self.hir.pattern_from_hir(pattern);
616
617                 match *pattern.kind {
618                     // Don't introduce extra copies for simple bindings
619                     PatternKind::Binding { mutability, var, mode: BindingMode::ByValue, .. } => {
620                         self.local_decls[local].mutability = mutability;
621                         self.var_indices.insert(var, local);
622                     }
623                     _ => {
624                         scope = self.declare_bindings(scope, ast_body.span,
625                                                       LintLevel::Inherited, &pattern);
626                         unpack!(block = self.place_into_pattern(block, pattern, &place));
627                     }
628                 }
629             }
630
631             // Make sure we drop (parts of) the argument even when not matched on.
632             self.schedule_drop(pattern.as_ref().map_or(ast_body.span, |pat| pat.span),
633                                argument_scope, &place, ty);
634
635         }
636
637         // Enter the argument pattern bindings visibility scope, if it exists.
638         if let Some(visibility_scope) = scope {
639             self.visibility_scope = visibility_scope;
640         }
641
642         let body = self.hir.mirror(ast_body);
643         self.into(&Place::Local(RETURN_PLACE), block, body)
644     }
645
646     fn get_unit_temp(&mut self) -> Place<'tcx> {
647         match self.unit_temp {
648             Some(ref tmp) => tmp.clone(),
649             None => {
650                 let ty = self.hir.unit_ty();
651                 let fn_span = self.fn_span;
652                 let tmp = self.temp(ty, fn_span);
653                 self.unit_temp = Some(tmp.clone());
654                 tmp
655             }
656         }
657     }
658
659     fn return_block(&mut self) -> BasicBlock {
660         match self.cached_return_block {
661             Some(rb) => rb,
662             None => {
663                 let rb = self.cfg.start_new_block();
664                 self.cached_return_block = Some(rb);
665                 rb
666             }
667         }
668     }
669
670     fn unreachable_block(&mut self) -> BasicBlock {
671         match self.cached_unreachable_block {
672             Some(ub) => ub,
673             None => {
674                 let ub = self.cfg.start_new_block();
675                 self.cached_unreachable_block = Some(ub);
676                 ub
677             }
678         }
679     }
680 }
681
682 ///////////////////////////////////////////////////////////////////////////
683 // Builder methods are broken up into modules, depending on what kind
684 // of thing is being translated. Note that they use the `unpack` macro
685 // above extensively.
686
687 mod block;
688 mod cfg;
689 mod expr;
690 mod into;
691 mod matches;
692 mod misc;
693 mod scope;