]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/build/mod.rs
rustc: uniformly compute ParameterEnvironment's "free outlive scope".
[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::traits::Reveal;
22 use rustc::ty::{self, Ty, TyCtxt};
23 use rustc::ty::subst::Substs;
24 use rustc::util::nodemap::NodeMap;
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 util as mir_util;
34
35 /// Construct the MIR for a given def-id.
36 pub fn mir_build<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> Mir<'tcx> {
37     let id = tcx.hir.as_local_node_id(def_id).unwrap();
38     let unsupported = || {
39         span_bug!(tcx.hir.span(id), "can't build MIR for {:?}", def_id);
40     };
41
42     // Figure out what primary body this item has.
43     let body_id = match tcx.hir.get(id) {
44         hir::map::NodeItem(item) => {
45             match item.node {
46                 hir::ItemConst(_, body) |
47                 hir::ItemStatic(_, _, body) |
48                 hir::ItemFn(.., body) => body,
49                 _ => unsupported()
50             }
51         }
52         hir::map::NodeTraitItem(item) => {
53             match item.node {
54                 hir::TraitItemKind::Const(_, Some(body)) |
55                 hir::TraitItemKind::Method(_,
56                     hir::TraitMethod::Provided(body)) => body,
57                 _ => unsupported()
58             }
59         }
60         hir::map::NodeImplItem(item) => {
61             match item.node {
62                 hir::ImplItemKind::Const(_, body) |
63                 hir::ImplItemKind::Method(_, body) => body,
64                 _ => unsupported()
65             }
66         }
67         hir::map::NodeExpr(expr) => {
68             // FIXME(eddyb) Closures should have separate
69             // function definition IDs and expression IDs.
70             // Type-checking should not let closures get
71             // this far in a constant position.
72             // Assume that everything other than closures
73             // is a constant "initializer" expression.
74             match expr.node {
75                 hir::ExprClosure(_, _, body, _) => body,
76                 _ => hir::BodyId { node_id: expr.id }
77             }
78         }
79         hir::map::NodeVariant(variant) =>
80             return create_constructor_shim(tcx, id, &variant.node.data),
81         hir::map::NodeStructCtor(ctor) =>
82             return create_constructor_shim(tcx, id, ctor),
83         _ => unsupported()
84     };
85
86     let src = MirSource::from_node(tcx, id);
87     tcx.infer_ctxt(body_id, Reveal::UserFacing).enter(|infcx| {
88         let cx = Cx::new(&infcx, src);
89         let mut mir = if cx.tables().tainted_by_errors {
90             build::construct_error(cx, body_id)
91         } else if let MirSource::Fn(id) = src {
92             // fetch the fully liberated fn signature (that is, all bound
93             // types/lifetimes replaced)
94             let fn_sig = cx.tables().liberated_fn_sigs[&id].clone();
95
96             let ty = tcx.type_of(tcx.hir.local_def_id(id));
97             let mut abi = fn_sig.abi;
98             let implicit_argument = if let ty::TyClosure(..) = ty.sty {
99                 // HACK(eddyb) Avoid having RustCall on closures,
100                 // as it adds unnecessary (and wrong) auto-tupling.
101                 abi = Abi::Rust;
102                 Some((closure_self_ty(tcx, id, body_id), None))
103             } else {
104                 None
105             };
106
107             let body = tcx.hir.body(body_id);
108             let explicit_arguments =
109                 body.arguments
110                     .iter()
111                     .enumerate()
112                     .map(|(index, arg)| {
113                         (fn_sig.inputs()[index], Some(&*arg.pat))
114                     });
115
116             let arguments = implicit_argument.into_iter().chain(explicit_arguments);
117             build::construct_fn(cx, id, arguments, abi, fn_sig.output(), body)
118         } else {
119             build::construct_const(cx, body_id)
120         };
121
122         // Convert the Mir to global types.
123         let mut globalizer = GlobalizeMir {
124             tcx: tcx,
125             span: mir.span
126         };
127         globalizer.visit_mir(&mut mir);
128         let mir = unsafe {
129             mem::transmute::<Mir, Mir<'tcx>>(mir)
130         };
131
132         mir_util::dump_mir(tcx, None, "mir_map", &0, src, &mir);
133
134         mir
135     })
136 }
137
138 /// A pass to lift all the types and substitutions in a Mir
139 /// to the global tcx. Sadly, we don't have a "folder" that
140 /// can change 'tcx so we have to transmute afterwards.
141 struct GlobalizeMir<'a, 'gcx: 'a> {
142     tcx: TyCtxt<'a, 'gcx, 'gcx>,
143     span: Span
144 }
145
146 impl<'a, 'gcx: 'tcx, 'tcx> MutVisitor<'tcx> for GlobalizeMir<'a, 'gcx> {
147     fn visit_ty(&mut self, ty: &mut Ty<'tcx>) {
148         if let Some(lifted) = self.tcx.lift(ty) {
149             *ty = lifted;
150         } else {
151             span_bug!(self.span,
152                       "found type `{:?}` with inference types/regions in MIR",
153                       ty);
154         }
155     }
156
157     fn visit_substs(&mut self, substs: &mut &'tcx Substs<'tcx>) {
158         if let Some(lifted) = self.tcx.lift(substs) {
159             *substs = lifted;
160         } else {
161             span_bug!(self.span,
162                       "found substs `{:?}` with inference types/regions in MIR",
163                       substs);
164         }
165     }
166 }
167
168 fn create_constructor_shim<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
169                                      ctor_id: ast::NodeId,
170                                      v: &'tcx hir::VariantData)
171                                      -> Mir<'tcx>
172 {
173     let span = tcx.hir.span(ctor_id);
174     if let hir::VariantData::Tuple(ref fields, ctor_id) = *v {
175         let pe = tcx.parameter_environment(tcx.hir.local_def_id(ctor_id));
176         tcx.infer_ctxt(pe, Reveal::UserFacing).enter(|infcx| {
177             let (mut mir, src) =
178                 shim::build_adt_ctor(&infcx, ctor_id, fields, span);
179
180             // Convert the Mir to global types.
181             let tcx = infcx.tcx.global_tcx();
182             let mut globalizer = GlobalizeMir {
183                 tcx: tcx,
184                 span: mir.span
185             };
186             globalizer.visit_mir(&mut mir);
187             let mir = unsafe {
188                 mem::transmute::<Mir, Mir<'tcx>>(mir)
189             };
190
191             mir_util::dump_mir(tcx, None, "mir_map", &0, src, &mir);
192
193             mir
194         })
195     } else {
196         span_bug!(span, "attempting to create MIR for non-tuple variant {:?}", v);
197     }
198 }
199
200 ///////////////////////////////////////////////////////////////////////////
201 // BuildMir -- walks a crate, looking for fn items and methods to build MIR from
202
203 fn closure_self_ty<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
204                              closure_expr_id: ast::NodeId,
205                              body_id: hir::BodyId)
206                              -> Ty<'tcx> {
207     let closure_ty = tcx.body_tables(body_id).node_id_to_type(closure_expr_id);
208
209     let region = ty::ReFree(ty::FreeRegion {
210         scope: Some(tcx.item_extent(body_id.node_id)),
211         bound_region: ty::BoundRegion::BrEnv,
212     });
213     let region = tcx.mk_region(region);
214
215     match tcx.closure_kind(tcx.hir.local_def_id(closure_expr_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 = tcx.call_site_extent(fn_id);
341     let arg_extent = tcx.parameter_extent(fn_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 pub 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 extent = hir.region_maps.temporary_scope(tcx, ast_expr.id)
405                                 .unwrap_or(tcx.item_extent(owner_id));
406     let mut block = START_BLOCK;
407     let _ = builder.in_scope(extent, block, |builder| {
408         let expr = builder.hir.mirror(ast_expr);
409         unpack!(block = builder.into(&Lvalue::Local(RETURN_POINTER), block, expr));
410
411         let source_info = builder.source_info(span);
412         let return_block = builder.return_block();
413         builder.cfg.terminate(block, source_info,
414                               TerminatorKind::Goto { target: return_block });
415         builder.cfg.terminate(return_block, source_info,
416                               TerminatorKind::Return);
417
418         return_block.unit()
419     });
420
421     builder.finish(vec![], ty)
422 }
423
424 pub fn construct_error<'a, 'gcx, 'tcx>(hir: Cx<'a, 'gcx, 'tcx>,
425                                        body_id: hir::BodyId)
426                                        -> Mir<'tcx> {
427     let span = hir.tcx().hir.span(hir.tcx().hir.body_owner(body_id));
428     let ty = hir.tcx().types.err;
429     let mut builder = Builder::new(hir, span, 0, ty);
430     let source_info = builder.source_info(span);
431     builder.cfg.terminate(START_BLOCK, source_info, TerminatorKind::Unreachable);
432     builder.finish(vec![], ty)
433 }
434
435 impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> {
436     fn new(hir: Cx<'a, 'gcx, 'tcx>,
437            span: Span,
438            arg_count: usize,
439            return_ty: Ty<'tcx>)
440            -> Builder<'a, 'gcx, 'tcx> {
441         let mut builder = Builder {
442             hir: hir,
443             cfg: CFG { basic_blocks: IndexVec::new() },
444             fn_span: span,
445             arg_count: arg_count,
446             scopes: vec![],
447             visibility_scopes: IndexVec::new(),
448             visibility_scope: ARGUMENT_VISIBILITY_SCOPE,
449             breakable_scopes: vec![],
450             local_decls: IndexVec::from_elem_n(LocalDecl::new_return_pointer(return_ty,
451                                                                              span), 1),
452             var_indices: NodeMap(),
453             unit_temp: None,
454             cached_resume_block: None,
455             cached_return_block: None
456         };
457
458         assert_eq!(builder.cfg.start_new_block(), START_BLOCK);
459         assert_eq!(builder.new_visibility_scope(span), ARGUMENT_VISIBILITY_SCOPE);
460         builder.visibility_scopes[ARGUMENT_VISIBILITY_SCOPE].parent_scope = None;
461
462         builder
463     }
464
465     fn finish(self,
466               upvar_decls: Vec<UpvarDecl>,
467               return_ty: Ty<'tcx>)
468               -> Mir<'tcx> {
469         for (index, block) in self.cfg.basic_blocks.iter().enumerate() {
470             if block.terminator.is_none() {
471                 span_bug!(self.fn_span, "no terminator on block {:?}", index);
472             }
473         }
474
475         Mir::new(self.cfg.basic_blocks,
476                  self.visibility_scopes,
477                  IndexVec::new(),
478                  return_ty,
479                  self.local_decls,
480                  self.arg_count,
481                  upvar_decls,
482                  self.fn_span
483         )
484     }
485
486     fn args_and_body(&mut self,
487                      mut block: BasicBlock,
488                      arguments: &[(Ty<'gcx>, Option<&'gcx hir::Pat>)],
489                      argument_extent: CodeExtent<'tcx>,
490                      ast_body: &'gcx hir::Expr)
491                      -> BlockAnd<()>
492     {
493         // Allocate locals for the function arguments
494         for &(ty, pattern) in arguments.iter() {
495             // If this is a simple binding pattern, give the local a nice name for debuginfo.
496             let mut name = None;
497             if let Some(pat) = pattern {
498                 if let hir::PatKind::Binding(_, _, ref ident, _) = pat.node {
499                     name = Some(ident.node);
500                 }
501             }
502
503             self.local_decls.push(LocalDecl {
504                 mutability: Mutability::Not,
505                 ty: ty,
506                 source_info: SourceInfo {
507                     scope: ARGUMENT_VISIBILITY_SCOPE,
508                     span: pattern.map_or(self.fn_span, |pat| pat.span)
509                 },
510                 name: name,
511                 is_user_variable: false,
512             });
513         }
514
515         let mut scope = None;
516         // Bind the argument patterns
517         for (index, &(ty, pattern)) in arguments.iter().enumerate() {
518             // Function arguments always get the first Local indices after the return pointer
519             let lvalue = Lvalue::Local(Local::new(index + 1));
520
521             if let Some(pattern) = pattern {
522                 let pattern = Pattern::from_hir(self.hir.tcx(), self.hir.tables(), pattern);
523                 scope = self.declare_bindings(scope, ast_body.span, &pattern);
524                 unpack!(block = self.lvalue_into_pattern(block, pattern, &lvalue));
525             }
526
527             // Make sure we drop (parts of) the argument even when not matched on.
528             self.schedule_drop(pattern.as_ref().map_or(ast_body.span, |pat| pat.span),
529                                argument_extent, &lvalue, ty);
530
531         }
532
533         // Enter the argument pattern bindings visibility scope, if it exists.
534         if let Some(visibility_scope) = scope {
535             self.visibility_scope = visibility_scope;
536         }
537
538         let body = self.hir.mirror(ast_body);
539         self.into(&Lvalue::Local(RETURN_POINTER), block, body)
540     }
541
542     fn get_unit_temp(&mut self) -> Lvalue<'tcx> {
543         match self.unit_temp {
544             Some(ref tmp) => tmp.clone(),
545             None => {
546                 let ty = self.hir.unit_ty();
547                 let fn_span = self.fn_span;
548                 let tmp = self.temp(ty, fn_span);
549                 self.unit_temp = Some(tmp.clone());
550                 tmp
551             }
552         }
553     }
554
555     fn return_block(&mut self) -> BasicBlock {
556         match self.cached_return_block {
557             Some(rb) => rb,
558             None => {
559                 let rb = self.cfg.start_new_block();
560                 self.cached_return_block = Some(rb);
561                 rb
562             }
563         }
564     }
565 }
566
567 ///////////////////////////////////////////////////////////////////////////
568 // Builder methods are broken up into modules, depending on what kind
569 // of thing is being translated. Note that they use the `unpack` macro
570 // above extensively.
571
572 mod block;
573 mod cfg;
574 mod expr;
575 mod into;
576 mod matches;
577 mod misc;
578 mod scope;