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, CodeExtentData};
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 = ty::ParameterEnvironment::for_item(tcx, 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 region = ty::ReFree(ty::FreeRegion {
210 scope: Some(tcx.item_extent(body_id.node_id)),
211 bound_region: ty::BoundRegion::BrEnv,
213 let region = tcx.mk_region(region);
215 match tcx.closure_kind(tcx.hir.local_def_id(closure_expr_id)) {
216 ty::ClosureKind::Fn =>
218 ty::TypeAndMut { ty: closure_ty,
219 mutbl: hir::MutImmutable }),
220 ty::ClosureKind::FnMut =>
222 ty::TypeAndMut { ty: closure_ty,
223 mutbl: hir::MutMutable }),
224 ty::ClosureKind::FnOnce =>
229 struct Builder<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
230 hir: Cx<'a, 'gcx, 'tcx>,
236 /// the current set of scopes, updated as we traverse;
237 /// see the `scope` module for more details
238 scopes: Vec<scope::Scope<'tcx>>,
240 /// the current set of breakables; see the `scope` module for more
242 breakable_scopes: Vec<scope::BreakableScope<'tcx>>,
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,
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>>,
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>,
262 basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
265 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
266 pub struct ScopeId(u32);
268 impl Idx for ScopeId {
269 fn new(index: usize) -> ScopeId {
270 assert!(index < (u32::MAX as usize));
271 ScopeId(index as u32)
274 fn index(self) -> usize {
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
285 #[must_use] // if you don't use one of these results, you're leaving a dangling edge
286 struct BlockAnd<T>(BasicBlock, T);
288 trait BlockAndExtension {
289 fn and<T>(self, v: T) -> BlockAnd<T>;
290 fn unit(self) -> BlockAnd<()>;
293 impl BlockAndExtension for BasicBlock {
294 fn and<T>(self, v: T) -> BlockAnd<T> {
298 fn unit(self) -> BlockAnd<()> {
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) => {
308 let BlockAnd(b, v) = $c;
316 let BlockAnd(b, ()) = $c;
322 ///////////////////////////////////////////////////////////////////////////
323 /// the main entry point for building MIR for a function
325 fn construct_fn<'a, 'gcx, 'tcx, A>(hir: Cx<'a, 'gcx, 'tcx>,
330 body: &'gcx hir::Body)
332 where A: Iterator<Item=(Ty<'gcx>, Option<&'gcx hir::Pat>)>
334 let arguments: Vec<_> = arguments.collect();
337 let span = tcx.hir.span(fn_id);
338 let mut builder = Builder::new(hir.clone(), span, arguments.len(), return_ty);
340 let call_site_extent =
341 tcx.intern_code_extent(
342 CodeExtentData::CallSiteScope { fn_id: fn_id, body_id: body.value.id });
344 tcx.intern_code_extent(
345 CodeExtentData::ParameterScope { fn_id: fn_id, body_id: body.value.id });
346 let mut block = START_BLOCK;
347 unpack!(block = builder.in_scope(call_site_extent, block, |builder| {
348 unpack!(block = builder.in_scope(arg_extent, block, |builder| {
349 builder.args_and_body(block, &arguments, arg_extent, &body.value)
351 // Attribute epilogue to function's closing brace
352 let fn_end = Span { lo: span.hi, ..span };
353 let source_info = builder.source_info(fn_end);
354 let return_block = builder.return_block();
355 builder.cfg.terminate(block, source_info,
356 TerminatorKind::Goto { target: return_block });
357 builder.cfg.terminate(return_block, source_info,
358 TerminatorKind::Return);
361 assert_eq!(block, builder.return_block());
363 let mut spread_arg = None;
364 if abi == Abi::RustCall {
365 // RustCall pseudo-ABI untuples the last argument.
366 spread_arg = Some(Local::new(arguments.len()));
369 // Gather the upvars of a closure, if any.
370 let upvar_decls: Vec<_> = tcx.with_freevars(fn_id, |freevars| {
371 freevars.iter().map(|fv| {
372 let var_id = tcx.hir.as_local_node_id(fv.def.def_id()).unwrap();
373 let by_ref = hir.tables().upvar_capture(ty::UpvarId {
375 closure_expr_id: fn_id
376 }).map_or(false, |capture| match capture {
377 ty::UpvarCapture::ByValue => false,
378 ty::UpvarCapture::ByRef(..) => true
380 let mut decl = UpvarDecl {
381 debug_name: keywords::Invalid.name(),
384 if let Some(hir::map::NodeLocal(pat)) = tcx.hir.find(var_id) {
385 if let hir::PatKind::Binding(_, _, ref ident, _) = pat.node {
386 decl.debug_name = ident.node;
393 let mut mir = builder.finish(upvar_decls, return_ty);
394 mir.spread_arg = spread_arg;
398 pub fn construct_const<'a, 'gcx, 'tcx>(hir: Cx<'a, 'gcx, 'tcx>,
399 body_id: hir::BodyId)
402 let ast_expr = &tcx.hir.body(body_id).value;
403 let ty = hir.tables().expr_ty_adjusted(ast_expr);
404 let owner_id = tcx.hir.body_owner(body_id);
405 let span = tcx.hir.span(owner_id);
406 let mut builder = Builder::new(hir.clone(), span, 0, ty);
408 let extent = hir.region_maps.temporary_scope(tcx, ast_expr.id)
409 .unwrap_or(tcx.item_extent(owner_id));
410 let mut block = START_BLOCK;
411 let _ = builder.in_scope(extent, block, |builder| {
412 let expr = builder.hir.mirror(ast_expr);
413 unpack!(block = builder.into(&Lvalue::Local(RETURN_POINTER), block, expr));
415 let source_info = builder.source_info(span);
416 let return_block = builder.return_block();
417 builder.cfg.terminate(block, source_info,
418 TerminatorKind::Goto { target: return_block });
419 builder.cfg.terminate(return_block, source_info,
420 TerminatorKind::Return);
425 builder.finish(vec![], ty)
428 pub fn construct_error<'a, 'gcx, 'tcx>(hir: Cx<'a, 'gcx, 'tcx>,
429 body_id: hir::BodyId)
431 let span = hir.tcx().hir.span(hir.tcx().hir.body_owner(body_id));
432 let ty = hir.tcx().types.err;
433 let mut builder = Builder::new(hir, span, 0, ty);
434 let source_info = builder.source_info(span);
435 builder.cfg.terminate(START_BLOCK, source_info, TerminatorKind::Unreachable);
436 builder.finish(vec![], ty)
439 impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> {
440 fn new(hir: Cx<'a, 'gcx, 'tcx>,
444 -> Builder<'a, 'gcx, 'tcx> {
445 let mut builder = Builder {
447 cfg: CFG { basic_blocks: IndexVec::new() },
449 arg_count: arg_count,
451 visibility_scopes: IndexVec::new(),
452 visibility_scope: ARGUMENT_VISIBILITY_SCOPE,
453 breakable_scopes: vec![],
454 local_decls: IndexVec::from_elem_n(LocalDecl::new_return_pointer(return_ty,
456 var_indices: NodeMap(),
458 cached_resume_block: None,
459 cached_return_block: None
462 assert_eq!(builder.cfg.start_new_block(), START_BLOCK);
463 assert_eq!(builder.new_visibility_scope(span), ARGUMENT_VISIBILITY_SCOPE);
464 builder.visibility_scopes[ARGUMENT_VISIBILITY_SCOPE].parent_scope = None;
470 upvar_decls: Vec<UpvarDecl>,
473 for (index, block) in self.cfg.basic_blocks.iter().enumerate() {
474 if block.terminator.is_none() {
475 span_bug!(self.fn_span, "no terminator on block {:?}", index);
479 Mir::new(self.cfg.basic_blocks,
480 self.visibility_scopes,
490 fn args_and_body(&mut self,
491 mut block: BasicBlock,
492 arguments: &[(Ty<'gcx>, Option<&'gcx hir::Pat>)],
493 argument_extent: CodeExtent<'tcx>,
494 ast_body: &'gcx hir::Expr)
497 // Allocate locals for the function arguments
498 for &(ty, pattern) in arguments.iter() {
499 // If this is a simple binding pattern, give the local a nice name for debuginfo.
501 if let Some(pat) = pattern {
502 if let hir::PatKind::Binding(_, _, ref ident, _) = pat.node {
503 name = Some(ident.node);
507 self.local_decls.push(LocalDecl {
508 mutability: Mutability::Not,
510 source_info: SourceInfo {
511 scope: ARGUMENT_VISIBILITY_SCOPE,
512 span: pattern.map_or(self.fn_span, |pat| pat.span)
515 is_user_variable: false,
519 let mut scope = None;
520 // Bind the argument patterns
521 for (index, &(ty, pattern)) in arguments.iter().enumerate() {
522 // Function arguments always get the first Local indices after the return pointer
523 let lvalue = Lvalue::Local(Local::new(index + 1));
525 if let Some(pattern) = pattern {
526 let pattern = Pattern::from_hir(self.hir.tcx(), self.hir.tables(), pattern);
527 scope = self.declare_bindings(scope, ast_body.span, &pattern);
528 unpack!(block = self.lvalue_into_pattern(block, pattern, &lvalue));
531 // Make sure we drop (parts of) the argument even when not matched on.
532 self.schedule_drop(pattern.as_ref().map_or(ast_body.span, |pat| pat.span),
533 argument_extent, &lvalue, ty);
537 // Enter the argument pattern bindings visibility scope, if it exists.
538 if let Some(visibility_scope) = scope {
539 self.visibility_scope = visibility_scope;
542 let body = self.hir.mirror(ast_body);
543 self.into(&Lvalue::Local(RETURN_POINTER), block, body)
546 fn get_unit_temp(&mut self) -> Lvalue<'tcx> {
547 match self.unit_temp {
548 Some(ref tmp) => tmp.clone(),
550 let ty = self.hir.unit_ty();
551 let fn_span = self.fn_span;
552 let tmp = self.temp(ty, fn_span);
553 self.unit_temp = Some(tmp.clone());
559 fn return_block(&mut self) -> BasicBlock {
560 match self.cached_return_block {
563 let rb = self.cfg.start_new_block();
564 self.cached_return_block = Some(rb);
571 ///////////////////////////////////////////////////////////////////////////
572 // Builder methods are broken up into modules, depending on what kind
573 // of thing is being translated. Note that they use the `unpack` macro
574 // above extensively.