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::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};
30 use syntax::symbol::keywords;
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);
41 // Figure out what primary body this item has.
42 let body_id = match tcx.hir.get(id) {
43 hir::map::NodeItem(item) => {
45 hir::ItemConst(_, body) |
46 hir::ItemStatic(_, _, body) |
47 hir::ItemFn(.., body) => body,
51 hir::map::NodeTraitItem(item) => {
53 hir::TraitItemKind::Const(_, Some(body)) |
54 hir::TraitItemKind::Method(_,
55 hir::TraitMethod::Provided(body)) => body,
59 hir::map::NodeImplItem(item) => {
61 hir::ImplItemKind::Const(_, body) |
62 hir::ImplItemKind::Method(_, body) => body,
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.
74 hir::ExprClosure(_, _, body, _) => body,
75 _ => hir::BodyId { node_id: expr.id }
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),
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();
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.
101 Some((closure_self_ty(tcx, id, body_id), None))
106 let body = tcx.hir.body(body_id);
107 let explicit_arguments =
111 .map(|(index, arg)| {
112 (fn_sig.inputs()[index], Some(&*arg.pat))
115 let arguments = implicit_argument.into_iter().chain(explicit_arguments);
116 build::construct_fn(cx, id, arguments, abi, fn_sig.output(), body)
118 build::construct_const(cx, body_id)
121 // Convert the Mir to global types.
122 let mut globalizer = GlobalizeMir {
126 globalizer.visit_mir(&mut mir);
128 mem::transmute::<Mir, Mir<'tcx>>(mir)
131 mir_util::dump_mir(tcx, None, "mir_map", &0, src, &mir);
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>,
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) {
151 "found type `{:?}` with inference types/regions in MIR",
156 fn visit_substs(&mut self, substs: &mut &'tcx Substs<'tcx>) {
157 if let Some(lifted) = self.tcx.lift(substs) {
161 "found substs `{:?}` with inference types/regions in MIR",
167 fn create_constructor_shim<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
168 ctor_id: ast::NodeId,
169 v: &'tcx hir::VariantData)
172 let span = tcx.hir.span(ctor_id);
173 if let hir::VariantData::Tuple(ref fields, ctor_id) = *v {
174 tcx.infer_ctxt(()).enter(|infcx| {
176 shim::build_adt_ctor(&infcx, ctor_id, fields, span);
178 // Convert the Mir to global types.
179 let tcx = infcx.tcx.global_tcx();
180 let mut globalizer = GlobalizeMir {
184 globalizer.visit_mir(&mut mir);
186 mem::transmute::<Mir, Mir<'tcx>>(mir)
189 mir_util::dump_mir(tcx, None, "mir_map", &0, src, &mir);
194 span_bug!(span, "attempting to create MIR for non-tuple variant {:?}", v);
198 ///////////////////////////////////////////////////////////////////////////
199 // BuildMir -- walks a crate, looking for fn items and methods to build MIR from
201 fn closure_self_ty<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
202 closure_expr_id: ast::NodeId,
203 body_id: hir::BodyId)
205 let closure_ty = tcx.body_tables(body_id).node_id_to_type(closure_expr_id);
207 let closure_def_id = tcx.hir.local_def_id(closure_expr_id);
208 let region = ty::ReFree(ty::FreeRegion {
209 scope: closure_def_id,
210 bound_region: ty::BoundRegion::BrEnv,
212 let region = tcx.mk_region(region);
214 match tcx.closure_kind(closure_def_id) {
215 ty::ClosureKind::Fn =>
217 ty::TypeAndMut { ty: closure_ty,
218 mutbl: hir::MutImmutable }),
219 ty::ClosureKind::FnMut =>
221 ty::TypeAndMut { ty: closure_ty,
222 mutbl: hir::MutMutable }),
223 ty::ClosureKind::FnOnce =>
228 struct Builder<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
229 hir: Cx<'a, 'gcx, 'tcx>,
235 /// the current set of scopes, updated as we traverse;
236 /// see the `scope` module for more details
237 scopes: Vec<scope::Scope<'tcx>>,
239 /// the current set of breakables; see the `scope` module for more
241 breakable_scopes: Vec<scope::BreakableScope<'tcx>>,
243 /// the vector of all scopes that we have created thus far;
244 /// we track this for debuginfo later
245 visibility_scopes: IndexVec<VisibilityScope, VisibilityScopeData>,
246 visibility_scope: VisibilityScope,
248 /// Maps node ids of variable bindings to the `Local`s created for them.
249 var_indices: NodeMap<Local>,
250 local_decls: IndexVec<Local, LocalDecl<'tcx>>,
251 unit_temp: Option<Lvalue<'tcx>>,
253 /// cached block with the RESUME terminator; this is created
254 /// when first set of cleanups are built.
255 cached_resume_block: Option<BasicBlock>,
256 /// cached block with the RETURN terminator
257 cached_return_block: Option<BasicBlock>,
261 basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
264 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
265 pub struct ScopeId(u32);
267 impl Idx for ScopeId {
268 fn new(index: usize) -> ScopeId {
269 assert!(index < (u32::MAX as usize));
270 ScopeId(index as u32)
273 fn index(self) -> usize {
278 ///////////////////////////////////////////////////////////////////////////
279 /// The `BlockAnd` "monad" packages up the new basic block along with a
280 /// produced value (sometimes just unit, of course). The `unpack!`
281 /// macro (and methods below) makes working with `BlockAnd` much more
284 #[must_use] // if you don't use one of these results, you're leaving a dangling edge
285 struct BlockAnd<T>(BasicBlock, T);
287 trait BlockAndExtension {
288 fn and<T>(self, v: T) -> BlockAnd<T>;
289 fn unit(self) -> BlockAnd<()>;
292 impl BlockAndExtension for BasicBlock {
293 fn and<T>(self, v: T) -> BlockAnd<T> {
297 fn unit(self) -> BlockAnd<()> {
302 /// Update a block pointer and return the value.
303 /// Use it like `let x = unpack!(block = self.foo(block, foo))`.
304 macro_rules! unpack {
305 ($x:ident = $c:expr) => {
307 let BlockAnd(b, v) = $c;
315 let BlockAnd(b, ()) = $c;
321 ///////////////////////////////////////////////////////////////////////////
322 /// the main entry point for building MIR for a function
324 fn construct_fn<'a, 'gcx, 'tcx, A>(hir: Cx<'a, 'gcx, 'tcx>,
329 body: &'gcx hir::Body)
331 where A: Iterator<Item=(Ty<'gcx>, Option<&'gcx hir::Pat>)>
333 let arguments: Vec<_> = arguments.collect();
336 let span = tcx.hir.span(fn_id);
337 let mut builder = Builder::new(hir.clone(), span, arguments.len(), return_ty);
339 let call_site_extent = CodeExtent::CallSiteScope(body.id());
340 let arg_extent = CodeExtent::ParameterScope(body.id());
341 let mut block = START_BLOCK;
342 unpack!(block = builder.in_scope(call_site_extent, block, |builder| {
343 unpack!(block = builder.in_scope(arg_extent, block, |builder| {
344 builder.args_and_body(block, &arguments, arg_extent, &body.value)
346 // Attribute epilogue to function's closing brace
347 let fn_end = Span { lo: span.hi, ..span };
348 let source_info = builder.source_info(fn_end);
349 let return_block = builder.return_block();
350 builder.cfg.terminate(block, source_info,
351 TerminatorKind::Goto { target: return_block });
352 builder.cfg.terminate(return_block, source_info,
353 TerminatorKind::Return);
356 assert_eq!(block, builder.return_block());
358 let mut spread_arg = None;
359 if abi == Abi::RustCall {
360 // RustCall pseudo-ABI untuples the last argument.
361 spread_arg = Some(Local::new(arguments.len()));
364 // Gather the upvars of a closure, if any.
365 let upvar_decls: Vec<_> = tcx.with_freevars(fn_id, |freevars| {
366 freevars.iter().map(|fv| {
367 let var_id = tcx.hir.as_local_node_id(fv.def.def_id()).unwrap();
368 let by_ref = hir.tables().upvar_capture(ty::UpvarId {
370 closure_expr_id: fn_id
371 }).map_or(false, |capture| match capture {
372 ty::UpvarCapture::ByValue => false,
373 ty::UpvarCapture::ByRef(..) => true
375 let mut decl = UpvarDecl {
376 debug_name: keywords::Invalid.name(),
379 if let Some(hir::map::NodeLocal(pat)) = tcx.hir.find(var_id) {
380 if let hir::PatKind::Binding(_, _, ref ident, _) = pat.node {
381 decl.debug_name = ident.node;
388 let mut mir = builder.finish(upvar_decls, return_ty);
389 mir.spread_arg = spread_arg;
393 fn construct_const<'a, 'gcx, 'tcx>(hir: Cx<'a, 'gcx, 'tcx>,
394 body_id: hir::BodyId)
397 let ast_expr = &tcx.hir.body(body_id).value;
398 let ty = hir.tables().expr_ty_adjusted(ast_expr);
399 let owner_id = tcx.hir.body_owner(body_id);
400 let span = tcx.hir.span(owner_id);
401 let mut builder = Builder::new(hir.clone(), span, 0, ty);
403 let mut block = START_BLOCK;
404 let expr = builder.hir.mirror(ast_expr);
405 unpack!(block = builder.into_expr(&Lvalue::Local(RETURN_POINTER), block, expr));
407 let source_info = builder.source_info(span);
408 builder.cfg.terminate(block, source_info, TerminatorKind::Return);
410 // Constants can't `return` so a return block should not be created.
411 assert_eq!(builder.cached_return_block, None);
413 builder.finish(vec![], ty)
416 fn construct_error<'a, 'gcx, 'tcx>(hir: Cx<'a, 'gcx, 'tcx>,
417 body_id: hir::BodyId)
419 let span = hir.tcx().hir.span(hir.tcx().hir.body_owner(body_id));
420 let ty = hir.tcx().types.err;
421 let mut builder = Builder::new(hir, span, 0, ty);
422 let source_info = builder.source_info(span);
423 builder.cfg.terminate(START_BLOCK, source_info, TerminatorKind::Unreachable);
424 builder.finish(vec![], ty)
427 impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> {
428 fn new(hir: Cx<'a, 'gcx, 'tcx>,
432 -> Builder<'a, 'gcx, 'tcx> {
433 let mut builder = Builder {
435 cfg: CFG { basic_blocks: IndexVec::new() },
437 arg_count: arg_count,
439 visibility_scopes: IndexVec::new(),
440 visibility_scope: ARGUMENT_VISIBILITY_SCOPE,
441 breakable_scopes: vec![],
442 local_decls: IndexVec::from_elem_n(LocalDecl::new_return_pointer(return_ty,
444 var_indices: NodeMap(),
446 cached_resume_block: None,
447 cached_return_block: None
450 assert_eq!(builder.cfg.start_new_block(), START_BLOCK);
451 assert_eq!(builder.new_visibility_scope(span), ARGUMENT_VISIBILITY_SCOPE);
452 builder.visibility_scopes[ARGUMENT_VISIBILITY_SCOPE].parent_scope = None;
458 upvar_decls: Vec<UpvarDecl>,
461 for (index, block) in self.cfg.basic_blocks.iter().enumerate() {
462 if block.terminator.is_none() {
463 span_bug!(self.fn_span, "no terminator on block {:?}", index);
467 Mir::new(self.cfg.basic_blocks,
468 self.visibility_scopes,
478 fn args_and_body(&mut self,
479 mut block: BasicBlock,
480 arguments: &[(Ty<'gcx>, Option<&'gcx hir::Pat>)],
481 argument_extent: CodeExtent,
482 ast_body: &'gcx hir::Expr)
485 // Allocate locals for the function arguments
486 for &(ty, pattern) in arguments.iter() {
487 // If this is a simple binding pattern, give the local a nice name for debuginfo.
489 if let Some(pat) = pattern {
490 if let hir::PatKind::Binding(_, _, ref ident, _) = pat.node {
491 name = Some(ident.node);
495 self.local_decls.push(LocalDecl {
496 mutability: Mutability::Not,
498 source_info: SourceInfo {
499 scope: ARGUMENT_VISIBILITY_SCOPE,
500 span: pattern.map_or(self.fn_span, |pat| pat.span)
503 is_user_variable: false,
507 let mut scope = None;
508 // Bind the argument patterns
509 for (index, &(ty, pattern)) in arguments.iter().enumerate() {
510 // Function arguments always get the first Local indices after the return pointer
511 let lvalue = Lvalue::Local(Local::new(index + 1));
513 if let Some(pattern) = pattern {
514 let pattern = Pattern::from_hir(self.hir.tcx(), self.hir.tables(), pattern);
515 scope = self.declare_bindings(scope, ast_body.span, &pattern);
516 unpack!(block = self.lvalue_into_pattern(block, pattern, &lvalue));
519 // Make sure we drop (parts of) the argument even when not matched on.
520 self.schedule_drop(pattern.as_ref().map_or(ast_body.span, |pat| pat.span),
521 argument_extent, &lvalue, ty);
525 // Enter the argument pattern bindings visibility scope, if it exists.
526 if let Some(visibility_scope) = scope {
527 self.visibility_scope = visibility_scope;
530 let body = self.hir.mirror(ast_body);
531 self.into(&Lvalue::Local(RETURN_POINTER), block, body)
534 fn get_unit_temp(&mut self) -> Lvalue<'tcx> {
535 match self.unit_temp {
536 Some(ref tmp) => tmp.clone(),
538 let ty = self.hir.unit_ty();
539 let fn_span = self.fn_span;
540 let tmp = self.temp(ty, fn_span);
541 self.unit_temp = Some(tmp.clone());
547 fn return_block(&mut self) -> BasicBlock {
548 match self.cached_return_block {
551 let rb = self.cfg.start_new_block();
552 self.cached_return_block = Some(rb);
559 ///////////////////////////////////////////////////////////////////////////
560 // Builder methods are broken up into modules, depending on what kind
561 // of thing is being translated. Note that they use the `unpack` macro
562 // above extensively.