]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/build/mod.rs
e9cf3115ddab1cd20da46efa45d9bb532b33ee74
[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::Pattern;
15 use rustc::hir;
16 use rustc::hir::def_id::DefId;
17 use rustc::middle::region::CodeExtent;
18 use rustc::mir::*;
19 use rustc::mir::transform::MirSource;
20 use rustc::mir::visit::MutVisitor;
21 use rustc::ty::{self, Ty, TyCtxt};
22 use rustc::ty::subst::Substs;
23 use rustc::util::nodemap::NodeMap;
24 use rustc_data_structures::indexed_vec::{IndexVec, Idx};
25 use shim;
26 use std::mem;
27 use std::u32;
28 use syntax::abi::Abi;
29 use syntax::ast;
30 use syntax::symbol::keywords;
31 use syntax_pos::Span;
32 use util as mir_util;
33
34 /// Construct the MIR for a given def-id.
35 pub fn mir_build<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> Mir<'tcx> {
36     let id = tcx.hir.as_local_node_id(def_id).unwrap();
37     let unsupported = || {
38         span_bug!(tcx.hir.span(id), "can't build MIR for {:?}", def_id);
39     };
40
41     // Figure out what primary body this item has.
42     let body_id = match tcx.hir.get(id) {
43         hir::map::NodeItem(item) => {
44             match item.node {
45                 hir::ItemConst(_, body) |
46                 hir::ItemStatic(_, _, body) |
47                 hir::ItemFn(.., body) => body,
48                 _ => unsupported()
49             }
50         }
51         hir::map::NodeTraitItem(item) => {
52             match item.node {
53                 hir::TraitItemKind::Const(_, Some(body)) |
54                 hir::TraitItemKind::Method(_,
55                     hir::TraitMethod::Provided(body)) => body,
56                 _ => unsupported()
57             }
58         }
59         hir::map::NodeImplItem(item) => {
60             match item.node {
61                 hir::ImplItemKind::Const(_, body) |
62                 hir::ImplItemKind::Method(_, body) => body,
63                 _ => unsupported()
64             }
65         }
66         hir::map::NodeExpr(expr) => {
67             // FIXME(eddyb) Closures should have separate
68             // function definition IDs and expression IDs.
69             // Type-checking should not let closures get
70             // this far in a constant position.
71             // Assume that everything other than closures
72             // is a constant "initializer" expression.
73             match expr.node {
74                 hir::ExprClosure(_, _, body, _) => body,
75                 _ => hir::BodyId { node_id: expr.id }
76             }
77         }
78         hir::map::NodeVariant(variant) =>
79             return create_constructor_shim(tcx, id, &variant.node.data),
80         hir::map::NodeStructCtor(ctor) =>
81             return create_constructor_shim(tcx, id, ctor),
82         _ => unsupported()
83     };
84
85     let src = MirSource::from_node(tcx, id);
86     tcx.infer_ctxt(body_id).enter(|infcx| {
87         let cx = Cx::new(&infcx, src);
88         let mut mir = if cx.tables().tainted_by_errors {
89             build::construct_error(cx, body_id)
90         } else if let MirSource::Fn(id) = src {
91             // fetch the fully liberated fn signature (that is, all bound
92             // types/lifetimes replaced)
93             let fn_sig = cx.tables().liberated_fn_sigs[&id].clone();
94
95             let ty = tcx.type_of(tcx.hir.local_def_id(id));
96             let mut abi = fn_sig.abi;
97             let implicit_argument = if let ty::TyClosure(..) = ty.sty {
98                 // HACK(eddyb) Avoid having RustCall on closures,
99                 // as it adds unnecessary (and wrong) auto-tupling.
100                 abi = Abi::Rust;
101                 Some((closure_self_ty(tcx, id, body_id), None))
102             } else {
103                 None
104             };
105
106             let body = tcx.hir.body(body_id);
107             let explicit_arguments =
108                 body.arguments
109                     .iter()
110                     .enumerate()
111                     .map(|(index, arg)| {
112                         (fn_sig.inputs()[index], Some(&*arg.pat))
113                     });
114
115             let arguments = implicit_argument.into_iter().chain(explicit_arguments);
116             build::construct_fn(cx, id, arguments, abi, fn_sig.output(), body)
117         } else {
118             build::construct_const(cx, body_id)
119         };
120
121         // Convert the Mir to global types.
122         let mut globalizer = GlobalizeMir {
123             tcx: tcx,
124             span: mir.span
125         };
126         globalizer.visit_mir(&mut mir);
127         let mir = unsafe {
128             mem::transmute::<Mir, Mir<'tcx>>(mir)
129         };
130
131         mir_util::dump_mir(tcx, None, "mir_map", &0, src, &mir);
132
133         mir
134     })
135 }
136
137 /// A pass to lift all the types and substitutions in a Mir
138 /// to the global tcx. Sadly, we don't have a "folder" that
139 /// can change 'tcx so we have to transmute afterwards.
140 struct GlobalizeMir<'a, 'gcx: 'a> {
141     tcx: TyCtxt<'a, 'gcx, 'gcx>,
142     span: Span
143 }
144
145 impl<'a, 'gcx: 'tcx, 'tcx> MutVisitor<'tcx> for GlobalizeMir<'a, 'gcx> {
146     fn visit_ty(&mut self, ty: &mut Ty<'tcx>) {
147         if let Some(lifted) = self.tcx.lift(ty) {
148             *ty = lifted;
149         } else {
150             span_bug!(self.span,
151                       "found type `{:?}` with inference types/regions in MIR",
152                       ty);
153         }
154     }
155
156     fn visit_substs(&mut self, substs: &mut &'tcx Substs<'tcx>) {
157         if let Some(lifted) = self.tcx.lift(substs) {
158             *substs = lifted;
159         } else {
160             span_bug!(self.span,
161                       "found substs `{:?}` with inference types/regions in MIR",
162                       substs);
163         }
164     }
165 }
166
167 fn create_constructor_shim<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
168                                      ctor_id: ast::NodeId,
169                                      v: &'tcx hir::VariantData)
170                                      -> Mir<'tcx>
171 {
172     let span = tcx.hir.span(ctor_id);
173     if let hir::VariantData::Tuple(ref fields, ctor_id) = *v {
174         let pe = tcx.param_env(tcx.hir.local_def_id(ctor_id));
175         tcx.infer_ctxt(pe).enter(|infcx| {
176             let (mut mir, src) =
177                 shim::build_adt_ctor(&infcx, ctor_id, fields, span);
178
179             // Convert the Mir to global types.
180             let tcx = infcx.tcx.global_tcx();
181             let mut globalizer = GlobalizeMir {
182                 tcx: tcx,
183                 span: mir.span
184             };
185             globalizer.visit_mir(&mut mir);
186             let mir = unsafe {
187                 mem::transmute::<Mir, Mir<'tcx>>(mir)
188             };
189
190             mir_util::dump_mir(tcx, None, "mir_map", &0, src, &mir);
191
192             mir
193         })
194     } else {
195         span_bug!(span, "attempting to create MIR for non-tuple variant {:?}", v);
196     }
197 }
198
199 ///////////////////////////////////////////////////////////////////////////
200 // BuildMir -- walks a crate, looking for fn items and methods to build MIR from
201
202 fn closure_self_ty<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
203                              closure_expr_id: ast::NodeId,
204                              body_id: hir::BodyId)
205                              -> Ty<'tcx> {
206     let closure_ty = tcx.body_tables(body_id).node_id_to_type(closure_expr_id);
207
208     let closure_def_id = tcx.hir.local_def_id(closure_expr_id);
209     let region = ty::ReFree(ty::FreeRegion {
210         scope: closure_def_id,
211         bound_region: ty::BoundRegion::BrEnv,
212     });
213     let region = tcx.mk_region(region);
214
215     match tcx.closure_kind(closure_def_id) {
216         ty::ClosureKind::Fn =>
217             tcx.mk_ref(region,
218                        ty::TypeAndMut { ty: closure_ty,
219                                         mutbl: hir::MutImmutable }),
220         ty::ClosureKind::FnMut =>
221             tcx.mk_ref(region,
222                        ty::TypeAndMut { ty: closure_ty,
223                                         mutbl: hir::MutMutable }),
224         ty::ClosureKind::FnOnce =>
225             closure_ty
226     }
227 }
228
229 struct Builder<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
230     hir: Cx<'a, 'gcx, 'tcx>,
231     cfg: CFG<'tcx>,
232
233     fn_span: Span,
234     arg_count: usize,
235
236     /// the current set of scopes, updated as we traverse;
237     /// see the `scope` module for more details
238     scopes: Vec<scope::Scope<'tcx>>,
239
240     /// the current set of breakables; see the `scope` module for more
241     /// details
242     breakable_scopes: Vec<scope::BreakableScope<'tcx>>,
243
244     /// the vector of all scopes that we have created thus far;
245     /// we track this for debuginfo later
246     visibility_scopes: IndexVec<VisibilityScope, VisibilityScopeData>,
247     visibility_scope: VisibilityScope,
248
249     /// Maps node ids of variable bindings to the `Local`s created for them.
250     var_indices: NodeMap<Local>,
251     local_decls: IndexVec<Local, LocalDecl<'tcx>>,
252     unit_temp: Option<Lvalue<'tcx>>,
253
254     /// cached block with the RESUME terminator; this is created
255     /// when first set of cleanups are built.
256     cached_resume_block: Option<BasicBlock>,
257     /// cached block with the RETURN terminator
258     cached_return_block: Option<BasicBlock>,
259 }
260
261 struct CFG<'tcx> {
262     basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
263 }
264
265 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
266 pub struct ScopeId(u32);
267
268 impl Idx for ScopeId {
269     fn new(index: usize) -> ScopeId {
270         assert!(index < (u32::MAX as usize));
271         ScopeId(index as u32)
272     }
273
274     fn index(self) -> usize {
275         self.0 as usize
276     }
277 }
278
279 ///////////////////////////////////////////////////////////////////////////
280 /// The `BlockAnd` "monad" packages up the new basic block along with a
281 /// produced value (sometimes just unit, of course). The `unpack!`
282 /// macro (and methods below) makes working with `BlockAnd` much more
283 /// convenient.
284
285 #[must_use] // if you don't use one of these results, you're leaving a dangling edge
286 struct BlockAnd<T>(BasicBlock, T);
287
288 trait BlockAndExtension {
289     fn and<T>(self, v: T) -> BlockAnd<T>;
290     fn unit(self) -> BlockAnd<()>;
291 }
292
293 impl BlockAndExtension for BasicBlock {
294     fn and<T>(self, v: T) -> BlockAnd<T> {
295         BlockAnd(self, v)
296     }
297
298     fn unit(self) -> BlockAnd<()> {
299         BlockAnd(self, ())
300     }
301 }
302
303 /// Update a block pointer and return the value.
304 /// Use it like `let x = unpack!(block = self.foo(block, foo))`.
305 macro_rules! unpack {
306     ($x:ident = $c:expr) => {
307         {
308             let BlockAnd(b, v) = $c;
309             $x = b;
310             v
311         }
312     };
313
314     ($c:expr) => {
315         {
316             let BlockAnd(b, ()) = $c;
317             b
318         }
319     };
320 }
321
322 ///////////////////////////////////////////////////////////////////////////
323 /// the main entry point for building MIR for a function
324
325 fn construct_fn<'a, 'gcx, 'tcx, A>(hir: Cx<'a, 'gcx, 'tcx>,
326                                    fn_id: ast::NodeId,
327                                    arguments: A,
328                                    abi: Abi,
329                                    return_ty: Ty<'gcx>,
330                                    body: &'gcx hir::Body)
331                                    -> Mir<'tcx>
332     where A: Iterator<Item=(Ty<'gcx>, Option<&'gcx hir::Pat>)>
333 {
334     let arguments: Vec<_> = arguments.collect();
335
336     let tcx = hir.tcx();
337     let span = tcx.hir.span(fn_id);
338     let mut builder = Builder::new(hir.clone(), span, arguments.len(), return_ty);
339
340     let call_site_extent = CodeExtent::CallSiteScope(body.id());
341     let arg_extent = CodeExtent::ParameterScope(body.id());
342     let mut block = START_BLOCK;
343     unpack!(block = builder.in_scope(call_site_extent, block, |builder| {
344         unpack!(block = builder.in_scope(arg_extent, block, |builder| {
345             builder.args_and_body(block, &arguments, arg_extent, &body.value)
346         }));
347         // Attribute epilogue to function's closing brace
348         let fn_end = Span { lo: span.hi, ..span };
349         let source_info = builder.source_info(fn_end);
350         let return_block = builder.return_block();
351         builder.cfg.terminate(block, source_info,
352                               TerminatorKind::Goto { target: return_block });
353         builder.cfg.terminate(return_block, source_info,
354                               TerminatorKind::Return);
355         return_block.unit()
356     }));
357     assert_eq!(block, builder.return_block());
358
359     let mut spread_arg = None;
360     if abi == Abi::RustCall {
361         // RustCall pseudo-ABI untuples the last argument.
362         spread_arg = Some(Local::new(arguments.len()));
363     }
364
365     // Gather the upvars of a closure, if any.
366     let upvar_decls: Vec<_> = tcx.with_freevars(fn_id, |freevars| {
367         freevars.iter().map(|fv| {
368             let var_id = tcx.hir.as_local_node_id(fv.def.def_id()).unwrap();
369             let by_ref = hir.tables().upvar_capture(ty::UpvarId {
370                 var_id: var_id,
371                 closure_expr_id: fn_id
372             }).map_or(false, |capture| match capture {
373                 ty::UpvarCapture::ByValue => false,
374                 ty::UpvarCapture::ByRef(..) => true
375             });
376             let mut decl = UpvarDecl {
377                 debug_name: keywords::Invalid.name(),
378                 by_ref: by_ref
379             };
380             if let Some(hir::map::NodeLocal(pat)) = tcx.hir.find(var_id) {
381                 if let hir::PatKind::Binding(_, _, ref ident, _) = pat.node {
382                     decl.debug_name = ident.node;
383                 }
384             }
385             decl
386         }).collect()
387     });
388
389     let mut mir = builder.finish(upvar_decls, return_ty);
390     mir.spread_arg = spread_arg;
391     mir
392 }
393
394 fn construct_const<'a, 'gcx, 'tcx>(hir: Cx<'a, 'gcx, 'tcx>,
395                                    body_id: hir::BodyId)
396                                    -> Mir<'tcx> {
397     let tcx = hir.tcx();
398     let ast_expr = &tcx.hir.body(body_id).value;
399     let ty = hir.tables().expr_ty_adjusted(ast_expr);
400     let owner_id = tcx.hir.body_owner(body_id);
401     let span = tcx.hir.span(owner_id);
402     let mut builder = Builder::new(hir.clone(), span, 0, ty);
403
404     let mut block = START_BLOCK;
405     let expr = builder.hir.mirror(ast_expr);
406     unpack!(block = builder.into_expr(&Lvalue::Local(RETURN_POINTER), block, expr));
407
408     let source_info = builder.source_info(span);
409     builder.cfg.terminate(block, source_info, TerminatorKind::Return);
410
411     // Constants can't `return` so a return block should not be created.
412     assert_eq!(builder.cached_return_block, None);
413
414     builder.finish(vec![], ty)
415 }
416
417 fn construct_error<'a, 'gcx, 'tcx>(hir: Cx<'a, 'gcx, 'tcx>,
418                                        body_id: hir::BodyId)
419                                        -> Mir<'tcx> {
420     let span = hir.tcx().hir.span(hir.tcx().hir.body_owner(body_id));
421     let ty = hir.tcx().types.err;
422     let mut builder = Builder::new(hir, span, 0, ty);
423     let source_info = builder.source_info(span);
424     builder.cfg.terminate(START_BLOCK, source_info, TerminatorKind::Unreachable);
425     builder.finish(vec![], ty)
426 }
427
428 impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> {
429     fn new(hir: Cx<'a, 'gcx, 'tcx>,
430            span: Span,
431            arg_count: usize,
432            return_ty: Ty<'tcx>)
433            -> Builder<'a, 'gcx, 'tcx> {
434         let mut builder = Builder {
435             hir: hir,
436             cfg: CFG { basic_blocks: IndexVec::new() },
437             fn_span: span,
438             arg_count: arg_count,
439             scopes: vec![],
440             visibility_scopes: IndexVec::new(),
441             visibility_scope: ARGUMENT_VISIBILITY_SCOPE,
442             breakable_scopes: vec![],
443             local_decls: IndexVec::from_elem_n(LocalDecl::new_return_pointer(return_ty,
444                                                                              span), 1),
445             var_indices: NodeMap(),
446             unit_temp: None,
447             cached_resume_block: None,
448             cached_return_block: None
449         };
450
451         assert_eq!(builder.cfg.start_new_block(), START_BLOCK);
452         assert_eq!(builder.new_visibility_scope(span), ARGUMENT_VISIBILITY_SCOPE);
453         builder.visibility_scopes[ARGUMENT_VISIBILITY_SCOPE].parent_scope = None;
454
455         builder
456     }
457
458     fn finish(self,
459               upvar_decls: Vec<UpvarDecl>,
460               return_ty: Ty<'tcx>)
461               -> Mir<'tcx> {
462         for (index, block) in self.cfg.basic_blocks.iter().enumerate() {
463             if block.terminator.is_none() {
464                 span_bug!(self.fn_span, "no terminator on block {:?}", index);
465             }
466         }
467
468         Mir::new(self.cfg.basic_blocks,
469                  self.visibility_scopes,
470                  IndexVec::new(),
471                  return_ty,
472                  self.local_decls,
473                  self.arg_count,
474                  upvar_decls,
475                  self.fn_span
476         )
477     }
478
479     fn args_and_body(&mut self,
480                      mut block: BasicBlock,
481                      arguments: &[(Ty<'gcx>, Option<&'gcx hir::Pat>)],
482                      argument_extent: CodeExtent,
483                      ast_body: &'gcx hir::Expr)
484                      -> BlockAnd<()>
485     {
486         // Allocate locals for the function arguments
487         for &(ty, pattern) in arguments.iter() {
488             // If this is a simple binding pattern, give the local a nice name for debuginfo.
489             let mut name = None;
490             if let Some(pat) = pattern {
491                 if let hir::PatKind::Binding(_, _, ref ident, _) = pat.node {
492                     name = Some(ident.node);
493                 }
494             }
495
496             self.local_decls.push(LocalDecl {
497                 mutability: Mutability::Not,
498                 ty: ty,
499                 source_info: SourceInfo {
500                     scope: ARGUMENT_VISIBILITY_SCOPE,
501                     span: pattern.map_or(self.fn_span, |pat| pat.span)
502                 },
503                 name: name,
504                 is_user_variable: false,
505             });
506         }
507
508         let mut scope = None;
509         // Bind the argument patterns
510         for (index, &(ty, pattern)) in arguments.iter().enumerate() {
511             // Function arguments always get the first Local indices after the return pointer
512             let lvalue = Lvalue::Local(Local::new(index + 1));
513
514             if let Some(pattern) = pattern {
515                 let pattern = Pattern::from_hir(self.hir.tcx(), self.hir.tables(), pattern);
516                 scope = self.declare_bindings(scope, ast_body.span, &pattern);
517                 unpack!(block = self.lvalue_into_pattern(block, pattern, &lvalue));
518             }
519
520             // Make sure we drop (parts of) the argument even when not matched on.
521             self.schedule_drop(pattern.as_ref().map_or(ast_body.span, |pat| pat.span),
522                                argument_extent, &lvalue, ty);
523
524         }
525
526         // Enter the argument pattern bindings visibility scope, if it exists.
527         if let Some(visibility_scope) = scope {
528             self.visibility_scope = visibility_scope;
529         }
530
531         let body = self.hir.mirror(ast_body);
532         self.into(&Lvalue::Local(RETURN_POINTER), block, body)
533     }
534
535     fn get_unit_temp(&mut self) -> Lvalue<'tcx> {
536         match self.unit_temp {
537             Some(ref tmp) => tmp.clone(),
538             None => {
539                 let ty = self.hir.unit_ty();
540                 let fn_span = self.fn_span;
541                 let tmp = self.temp(ty, fn_span);
542                 self.unit_temp = Some(tmp.clone());
543                 tmp
544             }
545         }
546     }
547
548     fn return_block(&mut self) -> BasicBlock {
549         match self.cached_return_block {
550             Some(rb) => rb,
551             None => {
552                 let rb = self.cfg.start_new_block();
553                 self.cached_return_block = Some(rb);
554                 rb
555             }
556         }
557     }
558 }
559
560 ///////////////////////////////////////////////////////////////////////////
561 // Builder methods are broken up into modules, depending on what kind
562 // of thing is being translated. Note that they use the `unpack` macro
563 // above extensively.
564
565 mod block;
566 mod cfg;
567 mod expr;
568 mod into;
569 mod matches;
570 mod misc;
571 mod scope;