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, LocalDefId};
17 use rustc::middle::region;
19 use rustc::mir::visit::{MutVisitor, TyContext};
20 use rustc::ty::{self, Ty, TyCtxt};
21 use rustc::ty::subst::Substs;
22 use rustc::util::nodemap::NodeMap;
23 use rustc_back::PanicStrategy;
24 use rustc_const_eval::pattern::{BindingMode, PatternKind};
25 use rustc_data_structures::indexed_vec::{IndexVec, Idx};
31 use syntax::symbol::keywords;
33 use transform::MirSource;
36 /// Construct the MIR for a given def-id.
37 pub fn mir_build<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> Mir<'tcx> {
38 let id = tcx.hir.as_local_node_id(def_id).unwrap();
39 let unsupported = || {
40 span_bug!(tcx.hir.span(id), "can't build MIR for {:?}", def_id);
43 // Figure out what primary body this item has.
44 let body_id = match tcx.hir.get(id) {
45 hir::map::NodeItem(item) => {
47 hir::ItemConst(_, body) |
48 hir::ItemStatic(_, _, body) |
49 hir::ItemFn(.., body) => body,
53 hir::map::NodeTraitItem(item) => {
55 hir::TraitItemKind::Const(_, Some(body)) |
56 hir::TraitItemKind::Method(_,
57 hir::TraitMethod::Provided(body)) => body,
61 hir::map::NodeImplItem(item) => {
63 hir::ImplItemKind::Const(_, body) |
64 hir::ImplItemKind::Method(_, body) => body,
68 hir::map::NodeExpr(expr) => {
69 // FIXME(eddyb) Closures should have separate
70 // function definition IDs and expression IDs.
71 // Type-checking should not let closures get
72 // this far in a constant position.
73 // Assume that everything other than closures
74 // is a constant "initializer" expression.
76 hir::ExprClosure(_, _, body, _, _) => body,
77 _ => hir::BodyId { node_id: expr.id },
80 hir::map::NodeVariant(variant) =>
81 return create_constructor_shim(tcx, id, &variant.node.data),
82 hir::map::NodeStructCtor(ctor) =>
83 return create_constructor_shim(tcx, id, ctor),
87 tcx.infer_ctxt().enter(|infcx| {
88 let cx = Cx::new(&infcx, id);
89 let mut mir = if cx.tables().tainted_by_errors {
90 build::construct_error(cx, body_id)
91 } else if let hir::BodyOwnerKind::Fn = cx.body_owner_kind {
92 // fetch the fully liberated fn signature (that is, all bound
93 // types/lifetimes replaced)
94 let fn_hir_id = tcx.hir.node_to_hir_id(id);
95 let fn_sig = cx.tables().liberated_fn_sigs()[fn_hir_id].clone();
97 let ty = tcx.type_of(tcx.hir.local_def_id(id));
98 let mut abi = fn_sig.abi;
99 let implicit_argument = match ty.sty {
100 ty::TyClosure(..) => {
101 // HACK(eddyb) Avoid having RustCall on closures,
102 // as it adds unnecessary (and wrong) auto-tupling.
104 Some((liberated_closure_env_ty(tcx, id, body_id), None))
106 ty::TyGenerator(..) => {
107 let gen_ty = tcx.body_tables(body_id).node_id_to_type(fn_hir_id);
113 // FIXME: safety in closures
114 let safety = match fn_sig.unsafety {
115 hir::Unsafety::Normal => Safety::Safe,
116 hir::Unsafety::Unsafe => Safety::FnUnsafe,
119 let body = tcx.hir.body(body_id);
120 let explicit_arguments =
124 .map(|(index, arg)| {
125 (fn_sig.inputs()[index], Some(&*arg.pat))
128 let arguments = implicit_argument.into_iter().chain(explicit_arguments);
130 let (yield_ty, return_ty) = if body.is_generator {
131 let gen_sig = match ty.sty {
132 ty::TyGenerator(gen_def_id, gen_substs, ..) =>
133 gen_substs.generator_sig(gen_def_id, tcx),
135 span_bug!(tcx.hir.span(id), "generator w/o generator type: {:?}", ty),
137 (Some(gen_sig.yield_ty), gen_sig.return_ty)
139 (None, fn_sig.output())
142 build::construct_fn(cx, id, arguments, safety, abi,
143 return_ty, yield_ty, body)
145 build::construct_const(cx, body_id)
148 // Convert the Mir to global types.
149 let mut globalizer = GlobalizeMir {
153 globalizer.visit_mir(&mut mir);
155 mem::transmute::<Mir, Mir<'tcx>>(mir)
158 mir_util::dump_mir(tcx, None, "mir_map", &0,
159 MirSource::item(def_id), &mir, |_, _| Ok(()) );
165 /// A pass to lift all the types and substitutions in a Mir
166 /// to the global tcx. Sadly, we don't have a "folder" that
167 /// can change 'tcx so we have to transmute afterwards.
168 struct GlobalizeMir<'a, 'gcx: 'a> {
169 tcx: TyCtxt<'a, 'gcx, 'gcx>,
173 impl<'a, 'gcx: 'tcx, 'tcx> MutVisitor<'tcx> for GlobalizeMir<'a, 'gcx> {
174 fn visit_ty(&mut self, ty: &mut Ty<'tcx>, _: TyContext) {
175 if let Some(lifted) = self.tcx.lift(ty) {
179 "found type `{:?}` with inference types/regions in MIR",
184 fn visit_region(&mut self, region: &mut ty::Region<'tcx>, _: Location) {
185 if let Some(lifted) = self.tcx.lift(region) {
189 "found region `{:?}` with inference types/regions in MIR",
194 fn visit_const(&mut self, constant: &mut &'tcx ty::Const<'tcx>, _: Location) {
195 if let Some(lifted) = self.tcx.lift(constant) {
199 "found constant `{:?}` with inference types/regions in MIR",
204 fn visit_substs(&mut self, substs: &mut &'tcx Substs<'tcx>, _: Location) {
205 if let Some(lifted) = self.tcx.lift(substs) {
209 "found substs `{:?}` with inference types/regions in MIR",
215 fn create_constructor_shim<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
216 ctor_id: ast::NodeId,
217 v: &'tcx hir::VariantData)
220 let span = tcx.hir.span(ctor_id);
221 if let hir::VariantData::Tuple(ref fields, ctor_id) = *v {
222 tcx.infer_ctxt().enter(|infcx| {
223 let mut mir = shim::build_adt_ctor(&infcx, ctor_id, fields, span);
225 // Convert the Mir to global types.
226 let tcx = infcx.tcx.global_tcx();
227 let mut globalizer = GlobalizeMir {
231 globalizer.visit_mir(&mut mir);
233 mem::transmute::<Mir, Mir<'tcx>>(mir)
236 mir_util::dump_mir(tcx, None, "mir_map", &0,
237 MirSource::item(tcx.hir.local_def_id(ctor_id)),
238 &mir, |_, _| Ok(()) );
243 span_bug!(span, "attempting to create MIR for non-tuple variant {:?}", v);
247 ///////////////////////////////////////////////////////////////////////////
248 // BuildMir -- walks a crate, looking for fn items and methods to build MIR from
250 fn liberated_closure_env_ty<'a, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>,
251 closure_expr_id: ast::NodeId,
252 body_id: hir::BodyId)
254 let closure_expr_hir_id = tcx.hir.node_to_hir_id(closure_expr_id);
255 let closure_ty = tcx.body_tables(body_id).node_id_to_type(closure_expr_hir_id);
257 let (closure_def_id, closure_substs) = match closure_ty.sty {
258 ty::TyClosure(closure_def_id, closure_substs) => (closure_def_id, closure_substs),
259 _ => bug!("closure expr does not have closure type: {:?}", closure_ty)
262 let closure_env_ty = tcx.closure_env_ty(closure_def_id, closure_substs).unwrap();
263 tcx.liberate_late_bound_regions(closure_def_id, &closure_env_ty)
266 struct Builder<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
267 hir: Cx<'a, 'gcx, 'tcx>,
273 /// the current set of scopes, updated as we traverse;
274 /// see the `scope` module for more details
275 scopes: Vec<scope::Scope<'tcx>>,
277 /// The current unsafe block in scope, even if it is hidden by
278 /// a PushUnsafeBlock
279 unpushed_unsafe: Safety,
281 /// The number of `push_unsafe_block` levels in scope
282 push_unsafe_count: usize,
284 /// the current set of breakables; see the `scope` module for more
286 breakable_scopes: Vec<scope::BreakableScope<'tcx>>,
288 /// the vector of all scopes that we have created thus far;
289 /// we track this for debuginfo later
290 visibility_scopes: IndexVec<VisibilityScope, VisibilityScopeData>,
291 visibility_scope_info: IndexVec<VisibilityScope, VisibilityScopeInfo>,
292 visibility_scope: VisibilityScope,
294 /// Maps node ids of variable bindings to the `Local`s created for them.
295 var_indices: NodeMap<Local>,
296 local_decls: IndexVec<Local, LocalDecl<'tcx>>,
297 unit_temp: Option<Place<'tcx>>,
299 /// cached block with the RESUME terminator; this is created
300 /// when first set of cleanups are built.
301 cached_resume_block: Option<BasicBlock>,
302 /// cached block with the RETURN terminator
303 cached_return_block: Option<BasicBlock>,
304 /// cached block with the UNREACHABLE terminator
305 cached_unreachable_block: Option<BasicBlock>,
309 basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
312 newtype_index!(ScopeId);
314 ///////////////////////////////////////////////////////////////////////////
315 /// The `BlockAnd` "monad" packages up the new basic block along with a
316 /// produced value (sometimes just unit, of course). The `unpack!`
317 /// macro (and methods below) makes working with `BlockAnd` much more
320 #[must_use] // if you don't use one of these results, you're leaving a dangling edge
321 struct BlockAnd<T>(BasicBlock, T);
323 trait BlockAndExtension {
324 fn and<T>(self, v: T) -> BlockAnd<T>;
325 fn unit(self) -> BlockAnd<()>;
328 impl BlockAndExtension for BasicBlock {
329 fn and<T>(self, v: T) -> BlockAnd<T> {
333 fn unit(self) -> BlockAnd<()> {
338 /// Update a block pointer and return the value.
339 /// Use it like `let x = unpack!(block = self.foo(block, foo))`.
340 macro_rules! unpack {
341 ($x:ident = $c:expr) => {
343 let BlockAnd(b, v) = $c;
351 let BlockAnd(b, ()) = $c;
357 fn should_abort_on_panic<'a, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>,
362 // Not callable from C, so we can safely unwind through these
363 if abi == Abi::Rust || abi == Abi::RustCall { return false; }
365 // We never unwind, so it's not relevant to stop an unwind
366 if tcx.sess.panic_strategy() != PanicStrategy::Unwind { return false; }
368 // We cannot add landing pads, so don't add one
369 if tcx.sess.no_landing_pads() { return false; }
371 // This is a special case: some functions have a C abi but are meant to
372 // unwind anyway. Don't stop them.
373 if tcx.has_attr(tcx.hir.local_def_id(fn_id), "unwind") { return false; }
378 ///////////////////////////////////////////////////////////////////////////
379 /// the main entry point for building MIR for a function
381 fn construct_fn<'a, 'gcx, 'tcx, A>(hir: Cx<'a, 'gcx, 'tcx>,
387 yield_ty: Option<Ty<'gcx>>,
388 body: &'gcx hir::Body)
390 where A: Iterator<Item=(Ty<'gcx>, Option<&'gcx hir::Pat>)>
392 let arguments: Vec<_> = arguments.collect();
395 let span = tcx.hir.span(fn_id);
396 let mut builder = Builder::new(hir.clone(),
402 let call_site_scope = region::Scope::CallSite(body.value.hir_id.local_id);
403 let arg_scope = region::Scope::Arguments(body.value.hir_id.local_id);
404 let mut block = START_BLOCK;
405 let source_info = builder.source_info(span);
406 let call_site_s = (call_site_scope, source_info);
407 unpack!(block = builder.in_scope(call_site_s, LintLevel::Inherited, block, |builder| {
408 if should_abort_on_panic(tcx, fn_id, abi) {
409 builder.schedule_abort();
412 let arg_scope_s = (arg_scope, source_info);
413 unpack!(block = builder.in_scope(arg_scope_s, LintLevel::Inherited, block, |builder| {
414 builder.args_and_body(block, &arguments, arg_scope, &body.value)
416 // Attribute epilogue to function's closing brace
417 let fn_end = span.with_lo(span.hi());
418 let source_info = builder.source_info(fn_end);
419 let return_block = builder.return_block();
420 builder.cfg.terminate(block, source_info,
421 TerminatorKind::Goto { target: return_block });
422 builder.cfg.terminate(return_block, source_info,
423 TerminatorKind::Return);
424 // Attribute any unreachable codepaths to the function's closing brace
425 if let Some(unreachable_block) = builder.cached_unreachable_block {
426 builder.cfg.terminate(unreachable_block, source_info,
427 TerminatorKind::Unreachable);
431 assert_eq!(block, builder.return_block());
433 let mut spread_arg = None;
434 if abi == Abi::RustCall {
435 // RustCall pseudo-ABI untuples the last argument.
436 spread_arg = Some(Local::new(arguments.len()));
439 // Gather the upvars of a closure, if any.
440 let upvar_decls: Vec<_> = tcx.with_freevars(fn_id, |freevars| {
441 freevars.iter().map(|fv| {
442 let var_id = fv.var_id();
443 let var_hir_id = tcx.hir.node_to_hir_id(var_id);
444 let closure_expr_id = tcx.hir.local_def_id(fn_id);
445 let capture = hir.tables().upvar_capture(ty::UpvarId {
447 closure_expr_id: LocalDefId::from_def_id(closure_expr_id),
449 let by_ref = match capture {
450 ty::UpvarCapture::ByValue => false,
451 ty::UpvarCapture::ByRef(..) => true
453 let mut decl = UpvarDecl {
454 debug_name: keywords::Invalid.name(),
456 mutability: Mutability::Not,
458 if let Some(hir::map::NodeBinding(pat)) = tcx.hir.find(var_id) {
459 if let hir::PatKind::Binding(_, _, ref ident, _) = pat.node {
460 decl.debug_name = ident.node;
462 let bm = *hir.tables.pat_binding_modes()
464 .expect("missing binding mode");
465 if bm == ty::BindByValue(hir::MutMutable) {
466 decl.mutability = Mutability::Mut;
468 decl.mutability = Mutability::Not;
476 let mut mir = builder.finish(upvar_decls, yield_ty);
477 mir.spread_arg = spread_arg;
481 fn construct_const<'a, 'gcx, 'tcx>(hir: Cx<'a, 'gcx, 'tcx>,
482 body_id: hir::BodyId)
485 let ast_expr = &tcx.hir.body(body_id).value;
486 let ty = hir.tables().expr_ty_adjusted(ast_expr);
487 let owner_id = tcx.hir.body_owner(body_id);
488 let span = tcx.hir.span(owner_id);
489 let mut builder = Builder::new(hir.clone(), span, 0, Safety::Safe, ty);
491 let mut block = START_BLOCK;
492 let expr = builder.hir.mirror(ast_expr);
493 unpack!(block = builder.into_expr(&Place::Local(RETURN_PLACE), block, expr));
495 let source_info = builder.source_info(span);
496 builder.cfg.terminate(block, source_info, TerminatorKind::Return);
498 // Constants can't `return` so a return block should not be created.
499 assert_eq!(builder.cached_return_block, None);
501 builder.finish(vec![], None)
504 fn construct_error<'a, 'gcx, 'tcx>(hir: Cx<'a, 'gcx, 'tcx>,
505 body_id: hir::BodyId)
507 let owner_id = hir.tcx().hir.body_owner(body_id);
508 let span = hir.tcx().hir.span(owner_id);
509 let ty = hir.tcx().types.err;
510 let mut builder = Builder::new(hir, span, 0, Safety::Safe, ty);
511 let source_info = builder.source_info(span);
512 builder.cfg.terminate(START_BLOCK, source_info, TerminatorKind::Unreachable);
513 builder.finish(vec![], None)
516 impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> {
517 fn new(hir: Cx<'a, 'gcx, 'tcx>,
522 -> Builder<'a, 'gcx, 'tcx> {
523 let lint_level = LintLevel::Explicit(hir.root_lint_level);
524 let mut builder = Builder {
526 cfg: CFG { basic_blocks: IndexVec::new() },
530 visibility_scopes: IndexVec::new(),
531 visibility_scope: ARGUMENT_VISIBILITY_SCOPE,
532 visibility_scope_info: IndexVec::new(),
533 push_unsafe_count: 0,
534 unpushed_unsafe: safety,
535 breakable_scopes: vec![],
536 local_decls: IndexVec::from_elem_n(LocalDecl::new_return_place(return_ty,
538 var_indices: NodeMap(),
540 cached_resume_block: None,
541 cached_return_block: None,
542 cached_unreachable_block: None,
545 assert_eq!(builder.cfg.start_new_block(), START_BLOCK);
547 builder.new_visibility_scope(span, lint_level, Some(safety)),
548 ARGUMENT_VISIBILITY_SCOPE);
549 builder.visibility_scopes[ARGUMENT_VISIBILITY_SCOPE].parent_scope = None;
555 upvar_decls: Vec<UpvarDecl>,
556 yield_ty: Option<Ty<'tcx>>)
558 for (index, block) in self.cfg.basic_blocks.iter().enumerate() {
559 if block.terminator.is_none() {
560 span_bug!(self.fn_span, "no terminator on block {:?}", index);
564 Mir::new(self.cfg.basic_blocks,
565 self.visibility_scopes,
566 ClearCrossCrate::Set(self.visibility_scope_info),
576 fn args_and_body(&mut self,
577 mut block: BasicBlock,
578 arguments: &[(Ty<'gcx>, Option<&'gcx hir::Pat>)],
579 argument_scope: region::Scope,
580 ast_body: &'gcx hir::Expr)
583 // Allocate locals for the function arguments
584 for &(ty, pattern) in arguments.iter() {
585 // If this is a simple binding pattern, give the local a nice name for debuginfo.
587 if let Some(pat) = pattern {
588 if let hir::PatKind::Binding(_, _, ref ident, _) = pat.node {
589 name = Some(ident.node);
593 self.local_decls.push(LocalDecl {
594 mutability: Mutability::Mut,
596 source_info: SourceInfo {
597 scope: ARGUMENT_VISIBILITY_SCOPE,
598 span: pattern.map_or(self.fn_span, |pat| pat.span)
600 lexical_scope: ARGUMENT_VISIBILITY_SCOPE,
603 is_user_variable: false,
607 let mut scope = None;
608 // Bind the argument patterns
609 for (index, &(ty, pattern)) in arguments.iter().enumerate() {
610 // Function arguments always get the first Local indices after the return place
611 let local = Local::new(index + 1);
612 let place = Place::Local(local);
614 if let Some(pattern) = pattern {
615 let pattern = self.hir.pattern_from_hir(pattern);
617 match *pattern.kind {
618 // Don't introduce extra copies for simple bindings
619 PatternKind::Binding { mutability, var, mode: BindingMode::ByValue, .. } => {
620 self.local_decls[local].mutability = mutability;
621 self.var_indices.insert(var, local);
624 scope = self.declare_bindings(scope, ast_body.span,
625 LintLevel::Inherited, &pattern);
626 unpack!(block = self.place_into_pattern(block, pattern, &place));
631 // Make sure we drop (parts of) the argument even when not matched on.
632 self.schedule_drop(pattern.as_ref().map_or(ast_body.span, |pat| pat.span),
633 argument_scope, &place, ty);
637 // Enter the argument pattern bindings visibility scope, if it exists.
638 if let Some(visibility_scope) = scope {
639 self.visibility_scope = visibility_scope;
642 let body = self.hir.mirror(ast_body);
643 self.into(&Place::Local(RETURN_PLACE), block, body)
646 fn get_unit_temp(&mut self) -> Place<'tcx> {
647 match self.unit_temp {
648 Some(ref tmp) => tmp.clone(),
650 let ty = self.hir.unit_ty();
651 let fn_span = self.fn_span;
652 let tmp = self.temp(ty, fn_span);
653 self.unit_temp = Some(tmp.clone());
659 fn return_block(&mut self) -> BasicBlock {
660 match self.cached_return_block {
663 let rb = self.cfg.start_new_block();
664 self.cached_return_block = Some(rb);
670 fn unreachable_block(&mut self) -> BasicBlock {
671 match self.cached_unreachable_block {
674 let ub = self.cfg.start_new_block();
675 self.cached_unreachable_block = Some(ub);
682 ///////////////////////////////////////////////////////////////////////////
683 // Builder methods are broken up into modules, depending on what kind
684 // of thing is being translated. Note that they use the `unpack` macro
685 // above extensively.