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.
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.
16 use rustc::hir::def_id::DefId;
17 use rustc::middle::region::CodeExtent;
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};
31 use syntax::symbol::keywords;
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);
42 // Figure out what primary body this item has.
43 let body_id = match tcx.hir.get(id) {
44 hir::map::NodeItem(item) => {
46 hir::ItemConst(_, body) |
47 hir::ItemStatic(_, _, body) |
48 hir::ItemFn(.., body) => body,
52 hir::map::NodeTraitItem(item) => {
54 hir::TraitItemKind::Const(_, Some(body)) |
55 hir::TraitItemKind::Method(_,
56 hir::TraitMethod::Provided(body)) => body,
60 hir::map::NodeImplItem(item) => {
62 hir::ImplItemKind::Const(_, body) |
63 hir::ImplItemKind::Method(_, body) => body,
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.
75 hir::ExprClosure(_, _, body, _) => body,
76 _ => hir::BodyId { node_id: expr.id }
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),
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();
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.
102 Some((closure_self_ty(tcx, id, body_id), None))
107 let body = tcx.hir.body(body_id);
108 let explicit_arguments =
112 .map(|(index, arg)| {
113 (fn_sig.inputs()[index], Some(&*arg.pat))
116 let arguments = implicit_argument.into_iter().chain(explicit_arguments);
117 build::construct_fn(cx, id, arguments, abi, fn_sig.output(), body)
119 build::construct_const(cx, body_id)
122 // Convert the Mir to global types.
123 let mut globalizer = GlobalizeMir {
127 globalizer.visit_mir(&mut mir);
129 mem::transmute::<Mir, Mir<'tcx>>(mir)
132 mir_util::dump_mir(tcx, None, "mir_map", &0, src, &mir);
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>,
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) {
152 "found type `{:?}` with inference types/regions in MIR",
157 fn visit_substs(&mut self, substs: &mut &'tcx Substs<'tcx>) {
158 if let Some(lifted) = self.tcx.lift(substs) {
162 "found substs `{:?}` with inference types/regions in MIR",
168 fn create_constructor_shim<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
169 ctor_id: ast::NodeId,
170 v: &'tcx hir::VariantData)
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| {
178 shim::build_adt_ctor(&infcx, ctor_id, fields, span);
180 // Convert the Mir to global types.
181 let tcx = infcx.tcx.global_tcx();
182 let mut globalizer = GlobalizeMir {
186 globalizer.visit_mir(&mut mir);
188 mem::transmute::<Mir, Mir<'tcx>>(mir)
191 mir_util::dump_mir(tcx, None, "mir_map", &0, src, &mir);
196 span_bug!(span, "attempting to create MIR for non-tuple variant {:?}", v);
200 ///////////////////////////////////////////////////////////////////////////
201 // BuildMir -- walks a crate, looking for fn items and methods to build MIR from
203 fn closure_self_ty<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
204 closure_expr_id: ast::NodeId,
205 body_id: hir::BodyId)
207 let closure_ty = tcx.body_tables(body_id).node_id_to_type(closure_expr_id);
209 let closure_def_id = tcx.hir.local_def_id(closure_expr_id);
210 let region = ty::ReFree(ty::FreeRegion {
211 scope: closure_def_id,
212 bound_region: ty::BoundRegion::BrEnv,
214 let region = tcx.mk_region(region);
216 match tcx.closure_kind(closure_def_id) {
217 ty::ClosureKind::Fn =>
219 ty::TypeAndMut { ty: closure_ty,
220 mutbl: hir::MutImmutable }),
221 ty::ClosureKind::FnMut =>
223 ty::TypeAndMut { ty: closure_ty,
224 mutbl: hir::MutMutable }),
225 ty::ClosureKind::FnOnce =>
230 struct Builder<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
231 hir: Cx<'a, 'gcx, 'tcx>,
237 /// the current set of scopes, updated as we traverse;
238 /// see the `scope` module for more details
239 scopes: Vec<scope::Scope<'tcx>>,
241 /// the current set of breakables; see the `scope` module for more
243 breakable_scopes: Vec<scope::BreakableScope<'tcx>>,
245 /// the vector of all scopes that we have created thus far;
246 /// we track this for debuginfo later
247 visibility_scopes: IndexVec<VisibilityScope, VisibilityScopeData>,
248 visibility_scope: VisibilityScope,
250 /// Maps node ids of variable bindings to the `Local`s created for them.
251 var_indices: NodeMap<Local>,
252 local_decls: IndexVec<Local, LocalDecl<'tcx>>,
253 unit_temp: Option<Lvalue<'tcx>>,
255 /// cached block with the RESUME terminator; this is created
256 /// when first set of cleanups are built.
257 cached_resume_block: Option<BasicBlock>,
258 /// cached block with the RETURN terminator
259 cached_return_block: Option<BasicBlock>,
263 basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
266 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
267 pub struct ScopeId(u32);
269 impl Idx for ScopeId {
270 fn new(index: usize) -> ScopeId {
271 assert!(index < (u32::MAX as usize));
272 ScopeId(index as u32)
275 fn index(self) -> usize {
280 ///////////////////////////////////////////////////////////////////////////
281 /// The `BlockAnd` "monad" packages up the new basic block along with a
282 /// produced value (sometimes just unit, of course). The `unpack!`
283 /// macro (and methods below) makes working with `BlockAnd` much more
286 #[must_use] // if you don't use one of these results, you're leaving a dangling edge
287 struct BlockAnd<T>(BasicBlock, T);
289 trait BlockAndExtension {
290 fn and<T>(self, v: T) -> BlockAnd<T>;
291 fn unit(self) -> BlockAnd<()>;
294 impl BlockAndExtension for BasicBlock {
295 fn and<T>(self, v: T) -> BlockAnd<T> {
299 fn unit(self) -> BlockAnd<()> {
304 /// Update a block pointer and return the value.
305 /// Use it like `let x = unpack!(block = self.foo(block, foo))`.
306 macro_rules! unpack {
307 ($x:ident = $c:expr) => {
309 let BlockAnd(b, v) = $c;
317 let BlockAnd(b, ()) = $c;
323 ///////////////////////////////////////////////////////////////////////////
324 /// the main entry point for building MIR for a function
326 fn construct_fn<'a, 'gcx, 'tcx, A>(hir: Cx<'a, 'gcx, 'tcx>,
331 body: &'gcx hir::Body)
333 where A: Iterator<Item=(Ty<'gcx>, Option<&'gcx hir::Pat>)>
335 let arguments: Vec<_> = arguments.collect();
338 let span = tcx.hir.span(fn_id);
339 let mut builder = Builder::new(hir.clone(), span, arguments.len(), return_ty);
341 let call_site_extent = CodeExtent::CallSiteScope(body.id());
342 let arg_extent = CodeExtent::ParameterScope(body.id());
343 let mut block = START_BLOCK;
344 unpack!(block = builder.in_scope(call_site_extent, block, |builder| {
345 unpack!(block = builder.in_scope(arg_extent, block, |builder| {
346 builder.args_and_body(block, &arguments, arg_extent, &body.value)
348 // Attribute epilogue to function's closing brace
349 let fn_end = Span { lo: span.hi, ..span };
350 let source_info = builder.source_info(fn_end);
351 let return_block = builder.return_block();
352 builder.cfg.terminate(block, source_info,
353 TerminatorKind::Goto { target: return_block });
354 builder.cfg.terminate(return_block, source_info,
355 TerminatorKind::Return);
358 assert_eq!(block, builder.return_block());
360 let mut spread_arg = None;
361 if abi == Abi::RustCall {
362 // RustCall pseudo-ABI untuples the last argument.
363 spread_arg = Some(Local::new(arguments.len()));
366 // Gather the upvars of a closure, if any.
367 let upvar_decls: Vec<_> = tcx.with_freevars(fn_id, |freevars| {
368 freevars.iter().map(|fv| {
369 let var_id = tcx.hir.as_local_node_id(fv.def.def_id()).unwrap();
370 let by_ref = hir.tables().upvar_capture(ty::UpvarId {
372 closure_expr_id: fn_id
373 }).map_or(false, |capture| match capture {
374 ty::UpvarCapture::ByValue => false,
375 ty::UpvarCapture::ByRef(..) => true
377 let mut decl = UpvarDecl {
378 debug_name: keywords::Invalid.name(),
381 if let Some(hir::map::NodeLocal(pat)) = tcx.hir.find(var_id) {
382 if let hir::PatKind::Binding(_, _, ref ident, _) = pat.node {
383 decl.debug_name = ident.node;
390 let mut mir = builder.finish(upvar_decls, return_ty);
391 mir.spread_arg = spread_arg;
395 pub fn construct_const<'a, 'gcx, 'tcx>(hir: Cx<'a, 'gcx, 'tcx>,
396 body_id: hir::BodyId)
399 let ast_expr = &tcx.hir.body(body_id).value;
400 let ty = hir.tables().expr_ty_adjusted(ast_expr);
401 let owner_id = tcx.hir.body_owner(body_id);
402 let span = tcx.hir.span(owner_id);
403 let mut builder = Builder::new(hir.clone(), span, 0, ty);
405 let mut block = START_BLOCK;
406 let expr = builder.hir.mirror(ast_expr);
407 unpack!(block = builder.into_expr(&Lvalue::Local(RETURN_POINTER), block, expr));
409 let source_info = builder.source_info(span);
410 builder.cfg.terminate(block, source_info, TerminatorKind::Return);
412 // Constants can't `return` so a return block should not be created.
413 assert_eq!(builder.cached_return_block, None);
415 builder.finish(vec![], ty)
418 pub fn construct_error<'a, 'gcx, 'tcx>(hir: Cx<'a, 'gcx, 'tcx>,
419 body_id: hir::BodyId)
421 let span = hir.tcx().hir.span(hir.tcx().hir.body_owner(body_id));
422 let ty = hir.tcx().types.err;
423 let mut builder = Builder::new(hir, span, 0, ty);
424 let source_info = builder.source_info(span);
425 builder.cfg.terminate(START_BLOCK, source_info, TerminatorKind::Unreachable);
426 builder.finish(vec![], ty)
429 impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> {
430 fn new(hir: Cx<'a, 'gcx, 'tcx>,
434 -> Builder<'a, 'gcx, 'tcx> {
435 let mut builder = Builder {
437 cfg: CFG { basic_blocks: IndexVec::new() },
439 arg_count: arg_count,
441 visibility_scopes: IndexVec::new(),
442 visibility_scope: ARGUMENT_VISIBILITY_SCOPE,
443 breakable_scopes: vec![],
444 local_decls: IndexVec::from_elem_n(LocalDecl::new_return_pointer(return_ty,
446 var_indices: NodeMap(),
448 cached_resume_block: None,
449 cached_return_block: None
452 assert_eq!(builder.cfg.start_new_block(), START_BLOCK);
453 assert_eq!(builder.new_visibility_scope(span), ARGUMENT_VISIBILITY_SCOPE);
454 builder.visibility_scopes[ARGUMENT_VISIBILITY_SCOPE].parent_scope = None;
460 upvar_decls: Vec<UpvarDecl>,
463 for (index, block) in self.cfg.basic_blocks.iter().enumerate() {
464 if block.terminator.is_none() {
465 span_bug!(self.fn_span, "no terminator on block {:?}", index);
469 Mir::new(self.cfg.basic_blocks,
470 self.visibility_scopes,
480 fn args_and_body(&mut self,
481 mut block: BasicBlock,
482 arguments: &[(Ty<'gcx>, Option<&'gcx hir::Pat>)],
483 argument_extent: CodeExtent,
484 ast_body: &'gcx hir::Expr)
487 // Allocate locals for the function arguments
488 for &(ty, pattern) in arguments.iter() {
489 // If this is a simple binding pattern, give the local a nice name for debuginfo.
491 if let Some(pat) = pattern {
492 if let hir::PatKind::Binding(_, _, ref ident, _) = pat.node {
493 name = Some(ident.node);
497 self.local_decls.push(LocalDecl {
498 mutability: Mutability::Not,
500 source_info: SourceInfo {
501 scope: ARGUMENT_VISIBILITY_SCOPE,
502 span: pattern.map_or(self.fn_span, |pat| pat.span)
505 is_user_variable: false,
509 let mut scope = None;
510 // Bind the argument patterns
511 for (index, &(ty, pattern)) in arguments.iter().enumerate() {
512 // Function arguments always get the first Local indices after the return pointer
513 let lvalue = Lvalue::Local(Local::new(index + 1));
515 if let Some(pattern) = pattern {
516 let pattern = Pattern::from_hir(self.hir.tcx(), self.hir.tables(), pattern);
517 scope = self.declare_bindings(scope, ast_body.span, &pattern);
518 unpack!(block = self.lvalue_into_pattern(block, pattern, &lvalue));
521 // Make sure we drop (parts of) the argument even when not matched on.
522 self.schedule_drop(pattern.as_ref().map_or(ast_body.span, |pat| pat.span),
523 argument_extent, &lvalue, ty);
527 // Enter the argument pattern bindings visibility scope, if it exists.
528 if let Some(visibility_scope) = scope {
529 self.visibility_scope = visibility_scope;
532 let body = self.hir.mirror(ast_body);
533 self.into(&Lvalue::Local(RETURN_POINTER), block, body)
536 fn get_unit_temp(&mut self) -> Lvalue<'tcx> {
537 match self.unit_temp {
538 Some(ref tmp) => tmp.clone(),
540 let ty = self.hir.unit_ty();
541 let fn_span = self.fn_span;
542 let tmp = self.temp(ty, fn_span);
543 self.unit_temp = Some(tmp.clone());
549 fn return_block(&mut self) -> BasicBlock {
550 match self.cached_return_block {
553 let rb = self.cfg.start_new_block();
554 self.cached_return_block = Some(rb);
561 ///////////////////////////////////////////////////////////////////////////
562 // Builder methods are broken up into modules, depending on what kind
563 // of thing is being translated. Note that they use the `unpack` macro
564 // above extensively.