2 use crate::build::scope::{CachedBlock, DropKind};
3 use crate::hair::cx::Cx;
4 use crate::hair::{LintLevel, BindingMode, PatternKind};
6 use crate::transform::MirSource;
7 use crate::util as mir_util;
10 use rustc::hir::def_id::DefId;
11 use rustc::middle::region;
13 use rustc::mir::visit::{MutVisitor, TyContext};
14 use rustc::ty::{self, Ty, TyCtxt};
15 use rustc::ty::subst::SubstsRef;
16 use rustc::util::nodemap::HirIdMap;
17 use rustc_target::spec::PanicStrategy;
18 use rustc_data_structures::indexed_vec::{IndexVec, Idx};
21 use rustc_target::spec::abi::Abi;
22 use syntax::attr::{self, UnwindAttr};
23 use syntax::symbol::keywords;
28 /// Construct the MIR for a given `DefId`.
29 pub fn mir_build<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> Mir<'tcx> {
30 let id = tcx.hir().as_local_hir_id(def_id).unwrap();
32 // Figure out what primary body this item has.
33 let (body_id, return_ty_span) = match tcx.hir().get_by_hir_id(id) {
34 Node::Ctor(ctor) => return create_constructor_shim(tcx, id, ctor),
36 Node::Expr(hir::Expr { node: hir::ExprKind::Closure(_, decl, body_id, _, _), .. })
37 | Node::Item(hir::Item { node: hir::ItemKind::Fn(decl, _, _, body_id), .. })
40 node: hir::ImplItemKind::Method(hir::MethodSig { decl, .. }, body_id),
46 node: hir::TraitItemKind::Method(
47 hir::MethodSig { decl, .. },
48 hir::TraitMethod::Provided(body_id),
53 (*body_id, decl.output.span())
55 Node::Item(hir::Item { node: hir::ItemKind::Static(ty, _, body_id), .. })
56 | Node::Item(hir::Item { node: hir::ItemKind::Const(ty, body_id), .. })
57 | Node::ImplItem(hir::ImplItem { node: hir::ImplItemKind::Const(ty, body_id), .. })
59 hir::TraitItem { node: hir::TraitItemKind::Const(ty, Some(body_id)), .. }
63 Node::AnonConst(hir::AnonConst { body, hir_id, .. }) => {
64 (*body, tcx.hir().span_by_hir_id(*hir_id))
67 _ => span_bug!(tcx.hir().span_by_hir_id(id), "can't build MIR for {:?}", def_id),
70 tcx.infer_ctxt().enter(|infcx| {
71 let cx = Cx::new(&infcx, id);
72 let mut mir = if cx.tables().tainted_by_errors {
73 build::construct_error(cx, body_id)
74 } else if cx.body_owner_kind.is_fn_or_closure() {
75 // fetch the fully liberated fn signature (that is, all bound
76 // types/lifetimes replaced)
77 let fn_sig = cx.tables().liberated_fn_sigs()[id].clone();
78 let fn_def_id = tcx.hir().local_def_id_from_hir_id(id);
80 let ty = tcx.type_of(fn_def_id);
81 let mut abi = fn_sig.abi;
82 let implicit_argument = match ty.sty {
84 // HACK(eddyb) Avoid having RustCall on closures,
85 // as it adds unnecessary (and wrong) auto-tupling.
87 Some(ArgInfo(liberated_closure_env_ty(tcx, id, body_id), None, None, None))
89 ty::Generator(..) => {
90 let gen_ty = tcx.body_tables(body_id).node_type(id);
91 Some(ArgInfo(gen_ty, None, None, None))
96 let safety = match fn_sig.unsafety {
97 hir::Unsafety::Normal => Safety::Safe,
98 hir::Unsafety::Unsafe => Safety::FnUnsafe,
101 let body = tcx.hir().body(body_id);
102 let explicit_arguments =
106 .map(|(index, arg)| {
107 let owner_id = tcx.hir().body_owner(body_id);
110 if let Some(ref fn_decl) = tcx.hir().fn_decl(owner_id) {
111 let ty_hir_id = fn_decl.inputs[index].hir_id;
112 let ty_span = tcx.hir().span_by_hir_id(ty_hir_id);
113 opt_ty_info = Some(ty_span);
114 self_arg = if index == 0 && fn_decl.implicit_self.has_implicit_self() {
115 match fn_decl.implicit_self {
116 hir::ImplicitSelfKind::Imm => Some(ImplicitSelfKind::Imm),
117 hir::ImplicitSelfKind::Mut => Some(ImplicitSelfKind::Mut),
118 hir::ImplicitSelfKind::ImmRef => Some(ImplicitSelfKind::ImmRef),
119 hir::ImplicitSelfKind::MutRef => Some(ImplicitSelfKind::MutRef),
129 ArgInfo(fn_sig.inputs()[index], opt_ty_info, Some(&*arg.pat), self_arg)
132 let arguments = implicit_argument.into_iter().chain(explicit_arguments);
134 let (yield_ty, return_ty) = if body.is_generator {
135 let gen_sig = match ty.sty {
136 ty::Generator(gen_def_id, gen_substs, ..) =>
137 gen_substs.sig(gen_def_id, tcx),
139 span_bug!(tcx.hir().span_by_hir_id(id),
140 "generator w/o generator type: {:?}", ty),
142 (Some(gen_sig.yield_ty), gen_sig.return_ty)
144 (None, fn_sig.output())
147 build::construct_fn(cx, id, arguments, safety, abi,
148 return_ty, yield_ty, return_ty_span, body)
150 build::construct_const(cx, body_id, return_ty_span)
153 // Convert the Mir to global types.
154 let mut globalizer = GlobalizeMir {
158 globalizer.visit_mir(&mut mir);
160 mem::transmute::<Mir<'_>, Mir<'tcx>>(mir)
163 mir_util::dump_mir(tcx, None, "mir_map", &0,
164 MirSource::item(def_id), &mir, |_, _| Ok(()) );
166 lints::check(tcx, &mir, def_id);
172 /// A pass to lift all the types and substitutions in a MIR
173 /// to the global tcx. Sadly, we don't have a "folder" that
174 /// can change `'tcx` so we have to transmute afterwards.
175 struct GlobalizeMir<'a, 'gcx: 'a> {
176 tcx: TyCtxt<'a, 'gcx, 'gcx>,
180 impl<'a, 'gcx: 'tcx, 'tcx> MutVisitor<'tcx> for GlobalizeMir<'a, 'gcx> {
181 fn visit_ty(&mut self, ty: &mut Ty<'tcx>, _: TyContext) {
182 if let Some(lifted) = self.tcx.lift(ty) {
186 "found type `{:?}` with inference types/regions in MIR",
191 fn visit_region(&mut self, region: &mut ty::Region<'tcx>, _: Location) {
192 if let Some(lifted) = self.tcx.lift(region) {
196 "found region `{:?}` with inference types/regions in MIR",
201 fn visit_const(&mut self, constant: &mut &'tcx ty::Const<'tcx>, _: Location) {
202 if let Some(lifted) = self.tcx.lift(constant) {
206 "found constant `{:?}` with inference types/regions in MIR",
211 fn visit_substs(&mut self, substs: &mut SubstsRef<'tcx>, _: Location) {
212 if let Some(lifted) = self.tcx.lift(substs) {
216 "found substs `{:?}` with inference types/regions in MIR",
222 fn create_constructor_shim<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
224 v: &'tcx hir::VariantData)
227 let span = tcx.hir().span_by_hir_id(ctor_id);
228 if let hir::VariantData::Tuple(ref fields, ctor_id) = *v {
229 tcx.infer_ctxt().enter(|infcx| {
230 let mut mir = shim::build_adt_ctor(&infcx, ctor_id, fields, span);
232 // Convert the Mir to global types.
233 let tcx = infcx.tcx.global_tcx();
234 let mut globalizer = GlobalizeMir {
238 globalizer.visit_mir(&mut mir);
240 mem::transmute::<Mir<'_>, Mir<'tcx>>(mir)
243 mir_util::dump_mir(tcx, None, "mir_map", &0,
244 MirSource::item(tcx.hir().local_def_id_from_hir_id(ctor_id)),
245 &mir, |_, _| Ok(()) );
250 span_bug!(span, "attempting to create MIR for non-tuple variant {:?}", v);
254 ///////////////////////////////////////////////////////////////////////////
255 // BuildMir -- walks a crate, looking for fn items and methods to build MIR from
257 fn liberated_closure_env_ty<'a, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>,
258 closure_expr_id: hir::HirId,
259 body_id: hir::BodyId)
261 let closure_ty = tcx.body_tables(body_id).node_type(closure_expr_id);
263 let (closure_def_id, closure_substs) = match closure_ty.sty {
264 ty::Closure(closure_def_id, closure_substs) => (closure_def_id, closure_substs),
265 _ => bug!("closure expr does not have closure type: {:?}", closure_ty)
268 let closure_env_ty = tcx.closure_env_ty(closure_def_id, closure_substs).unwrap();
269 tcx.liberate_late_bound_regions(closure_def_id, &closure_env_ty)
272 #[derive(Debug, PartialEq, Eq)]
273 pub enum BlockFrame {
274 /// Evaluation is currently within a statement.
276 /// Examples include:
278 /// 2. `let _ = EXPR;`
279 /// 3. `let x = EXPR;`
281 /// If true, then statement discards result from evaluating
282 /// the expression (such as examples 1 and 2 above).
283 ignores_expr_result: bool
286 /// Evaluation is currently within the tail expression of a block.
288 /// Example: `{ STMT_1; STMT_2; EXPR }`
290 /// If true, then the surrounding context of the block ignores
291 /// the result of evaluating the block's tail expression.
293 /// Example: `let _ = { STMT_1; EXPR };`
294 tail_result_is_ignored: bool
297 /// Generic mark meaning that the block occurred as a subexpression
298 /// where the result might be used.
300 /// Examples: `foo(EXPR)`, `match EXPR { ... }`
305 fn is_tail_expr(&self) -> bool {
307 BlockFrame::TailExpr { .. } => true,
309 BlockFrame::Statement { .. } |
310 BlockFrame::SubExpr => false,
313 fn is_statement(&self) -> bool {
315 BlockFrame::Statement { .. } => true,
317 BlockFrame::TailExpr { .. } |
318 BlockFrame::SubExpr => false,
324 struct BlockContext(Vec<BlockFrame>);
326 struct Builder<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
327 hir: Cx<'a, 'gcx, 'tcx>,
333 /// The current set of scopes, updated as we traverse;
334 /// see the `scope` module for more details.
335 scopes: Vec<scope::Scope<'tcx>>,
337 /// The block-context: each time we build the code within an hair::Block,
338 /// we push a frame here tracking whether we are building a statement or
339 /// if we are pushing the tail expression of the block. This is used to
340 /// embed information in generated temps about whether they were created
341 /// for a block tail expression or not.
343 /// It would be great if we could fold this into `self.scopes`
344 /// somehow, but right now I think that is very tightly tied to
345 /// the code generation in ways that we cannot (or should not)
346 /// start just throwing new entries onto that vector in order to
347 /// distinguish the context of EXPR1 from the context of EXPR2 in
348 /// `{ STMTS; EXPR1 } + EXPR2`.
349 block_context: BlockContext,
351 /// The current unsafe block in scope, even if it is hidden by
352 /// a `PushUnsafeBlock`.
353 unpushed_unsafe: Safety,
355 /// The number of `push_unsafe_block` levels in scope.
356 push_unsafe_count: usize,
358 /// The current set of breakables; see the `scope` module for more
360 breakable_scopes: Vec<scope::BreakableScope<'tcx>>,
362 /// The vector of all scopes that we have created thus far;
363 /// we track this for debuginfo later.
364 source_scopes: IndexVec<SourceScope, SourceScopeData>,
365 source_scope_local_data: IndexVec<SourceScope, SourceScopeLocalData>,
366 source_scope: SourceScope,
368 /// The guard-context: each time we build the guard expression for
369 /// a match arm, we push onto this stack, and then pop when we
370 /// finish building it.
371 guard_context: Vec<GuardFrame>,
373 /// Maps `HirId`s of variable bindings to the `Local`s created for them.
374 /// (A match binding can have two locals; the 2nd is for the arm's guard.)
375 var_indices: HirIdMap<LocalsForNode>,
376 local_decls: IndexVec<Local, LocalDecl<'tcx>>,
377 canonical_user_type_annotations: ty::CanonicalUserTypeAnnotations<'tcx>,
378 upvar_decls: Vec<UpvarDecl>,
379 unit_temp: Option<Place<'tcx>>,
381 /// Cached block with the `RESUME` terminator; this is created
382 /// when first set of cleanups are built.
383 cached_resume_block: Option<BasicBlock>,
384 /// Cached block with the `RETURN` terminator.
385 cached_return_block: Option<BasicBlock>,
386 /// Cached block with the `UNREACHABLE` terminator.
387 cached_unreachable_block: Option<BasicBlock>,
390 impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> {
391 fn is_bound_var_in_guard(&self, id: hir::HirId) -> bool {
392 self.guard_context.iter().any(|frame| frame.locals.iter().any(|local| local.id == id))
395 fn var_local_id(&self, id: hir::HirId, for_guard: ForGuard) -> Local {
396 self.var_indices[&id].local_id(for_guard)
401 fn new() -> Self { BlockContext(vec![]) }
402 fn push(&mut self, bf: BlockFrame) { self.0.push(bf); }
403 fn pop(&mut self) -> Option<BlockFrame> { self.0.pop() }
405 /// Traverses the frames on the `BlockContext`, searching for either
406 /// the first block-tail expression frame with no intervening
409 /// Notably, this skips over `SubExpr` frames; this method is
410 /// meant to be used in the context of understanding the
411 /// relationship of a temp (created within some complicated
412 /// expression) with its containing expression, and whether the
413 /// value of that *containing expression* (not the temp!) is
415 fn currently_in_block_tail(&self) -> Option<BlockTailInfo> {
416 for bf in self.0.iter().rev() {
418 BlockFrame::SubExpr => continue,
419 BlockFrame::Statement { .. } => break,
420 &BlockFrame::TailExpr { tail_result_is_ignored } =>
421 return Some(BlockTailInfo { tail_result_is_ignored })
428 /// Looks at the topmost frame on the BlockContext and reports
429 /// whether its one that would discard a block tail result.
431 /// Unlike `currently_within_ignored_tail_expression`, this does
432 /// *not* skip over `SubExpr` frames: here, we want to know
433 /// whether the block result itself is discarded.
434 fn currently_ignores_tail_results(&self) -> bool {
435 match self.0.last() {
436 // no context: conservatively assume result is read
439 // sub-expression: block result feeds into some computation
440 Some(BlockFrame::SubExpr) => false,
442 // otherwise: use accumulated is_ignored state.
443 Some(BlockFrame::TailExpr { tail_result_is_ignored: ignored }) |
444 Some(BlockFrame::Statement { ignores_expr_result: ignored }) => *ignored,
451 /// In the usual case, a `HirId` for an identifier maps to at most
452 /// one `Local` declaration.
455 /// The exceptional case is identifiers in a match arm's pattern
456 /// that are referenced in a guard of that match arm. For these,
457 /// we have `2` Locals.
459 /// * `for_arm_body` is the Local used in the arm body (which is
460 /// just like the `One` case above),
462 /// * `ref_for_guard` is the Local used in the arm's guard (which
463 /// is a reference to a temp that is an alias of
465 ForGuard { ref_for_guard: Local, for_arm_body: Local },
469 struct GuardFrameLocal {
473 impl GuardFrameLocal {
474 fn new(id: hir::HirId, _binding_mode: BindingMode) -> Self {
483 /// These are the id's of names that are bound by patterns of the
484 /// arm of *this* guard.
486 /// (Frames higher up the stack will have the id's bound in arms
487 /// further out, such as in a case like:
490 /// P1(id1) if (... (match E2 { P2(id2) if ... => B2 })) => B1,
493 /// here, when building for FIXME.
494 locals: Vec<GuardFrameLocal>,
497 /// `ForGuard` indicates whether we are talking about:
498 /// 1. The variable for use outside of guard expressions, or
499 /// 2. The temp that holds reference to (1.), which is actually what the
500 /// guard expressions see.
501 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
508 fn local_id(&self, for_guard: ForGuard) -> Local {
509 match (self, for_guard) {
510 (&LocalsForNode::One(local_id), ForGuard::OutsideGuard) |
511 (&LocalsForNode::ForGuard { ref_for_guard: local_id, .. }, ForGuard::RefWithinGuard) |
512 (&LocalsForNode::ForGuard { for_arm_body: local_id, .. }, ForGuard::OutsideGuard) =>
515 (&LocalsForNode::One(_), ForGuard::RefWithinGuard) =>
516 bug!("anything with one local should never be within a guard."),
522 basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
526 pub struct ScopeId { .. }
529 ///////////////////////////////////////////////////////////////////////////
530 /// The `BlockAnd` "monad" packages up the new basic block along with a
531 /// produced value (sometimes just unit, of course). The `unpack!`
532 /// macro (and methods below) makes working with `BlockAnd` much more
535 #[must_use = "if you don't use one of these results, you're leaving a dangling edge"]
536 struct BlockAnd<T>(BasicBlock, T);
538 trait BlockAndExtension {
539 fn and<T>(self, v: T) -> BlockAnd<T>;
540 fn unit(self) -> BlockAnd<()>;
543 impl BlockAndExtension for BasicBlock {
544 fn and<T>(self, v: T) -> BlockAnd<T> {
548 fn unit(self) -> BlockAnd<()> {
553 /// Update a block pointer and return the value.
554 /// Use it like `let x = unpack!(block = self.foo(block, foo))`.
555 macro_rules! unpack {
556 ($x:ident = $c:expr) => {
558 let BlockAnd(b, v) = $c;
566 let BlockAnd(b, ()) = $c;
572 fn should_abort_on_panic<'a, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>,
576 // Not callable from C, so we can safely unwind through these
577 if abi == Abi::Rust || abi == Abi::RustCall { return false; }
579 // Validate `#[unwind]` syntax regardless of platform-specific panic strategy
580 let attrs = &tcx.get_attrs(fn_def_id);
581 let unwind_attr = attr::find_unwind_attr(Some(tcx.sess.diagnostic()), attrs);
583 // We never unwind, so it's not relevant to stop an unwind
584 if tcx.sess.panic_strategy() != PanicStrategy::Unwind { return false; }
586 // We cannot add landing pads, so don't add one
587 if tcx.sess.no_landing_pads() { return false; }
589 // This is a special case: some functions have a C abi but are meant to
590 // unwind anyway. Don't stop them.
593 Some(UnwindAttr::Allowed) => false,
594 Some(UnwindAttr::Aborts) => true,
598 ///////////////////////////////////////////////////////////////////////////
599 /// the main entry point for building MIR for a function
601 struct ArgInfo<'gcx>(Ty<'gcx>,
603 Option<&'gcx hir::Pat>,
604 Option<ImplicitSelfKind>);
606 fn construct_fn<'a, 'gcx, 'tcx, A>(hir: Cx<'a, 'gcx, 'tcx>,
612 yield_ty: Option<Ty<'gcx>>,
613 return_ty_span: Span,
614 body: &'gcx hir::Body)
616 where A: Iterator<Item=ArgInfo<'gcx>>
618 let arguments: Vec<_> = arguments.collect();
621 let tcx_hir = tcx.hir();
622 let span = tcx_hir.span_by_hir_id(fn_id);
624 let hir_tables = hir.tables();
625 let fn_def_id = tcx_hir.local_def_id_from_hir_id(fn_id);
627 // Gather the upvars of a closure, if any.
628 // In analyze_closure() in upvar.rs we gathered a list of upvars used by a
629 // closure and we stored in a map called upvar_list in TypeckTables indexed
630 // with the closure's DefId. Here, we run through that vec of UpvarIds for
631 // the given closure and use the necessary information to create UpvarDecl.
632 let upvar_decls: Vec<_> = hir_tables
638 let var_hir_id = upvar_id.var_path.hir_id;
639 let var_node_id = tcx_hir.hir_to_node_id(var_hir_id);
640 let capture = hir_tables.upvar_capture(*upvar_id);
641 let by_ref = match capture {
642 ty::UpvarCapture::ByValue => false,
643 ty::UpvarCapture::ByRef(..) => true,
645 let mut decl = UpvarDecl {
646 debug_name: keywords::Invalid.name(),
647 var_hir_id: ClearCrossCrate::Set(var_hir_id),
649 mutability: Mutability::Not,
651 if let Some(Node::Binding(pat)) = tcx_hir.find(var_node_id) {
652 if let hir::PatKind::Binding(_, _, ident, _) = pat.node {
653 decl.debug_name = ident.name;
654 if let Some(&bm) = hir.tables.pat_binding_modes().get(pat.hir_id) {
655 if bm == ty::BindByValue(hir::MutMutable) {
656 decl.mutability = Mutability::Mut;
658 decl.mutability = Mutability::Not;
661 tcx.sess.delay_span_bug(pat.span, "missing binding mode");
669 let mut builder = Builder::new(hir,
677 let call_site_scope = region::Scope {
678 id: body.value.hir_id.local_id,
679 data: region::ScopeData::CallSite
681 let arg_scope = region::Scope {
682 id: body.value.hir_id.local_id,
683 data: region::ScopeData::Arguments
685 let mut block = START_BLOCK;
686 let source_info = builder.source_info(span);
687 let call_site_s = (call_site_scope, source_info);
688 unpack!(block = builder.in_scope(call_site_s, LintLevel::Inherited, block, |builder| {
689 if should_abort_on_panic(tcx, fn_def_id, abi) {
690 builder.schedule_abort();
693 let arg_scope_s = (arg_scope, source_info);
694 unpack!(block = builder.in_scope(arg_scope_s, LintLevel::Inherited, block, |builder| {
695 builder.args_and_body(block, &arguments, arg_scope, &body.value)
697 // Attribute epilogue to function's closing brace
698 let fn_end = span.shrink_to_hi();
699 let source_info = builder.source_info(fn_end);
700 let return_block = builder.return_block();
701 builder.cfg.terminate(block, source_info,
702 TerminatorKind::Goto { target: return_block });
703 builder.cfg.terminate(return_block, source_info,
704 TerminatorKind::Return);
705 // Attribute any unreachable codepaths to the function's closing brace
706 if let Some(unreachable_block) = builder.cached_unreachable_block {
707 builder.cfg.terminate(unreachable_block, source_info,
708 TerminatorKind::Unreachable);
712 assert_eq!(block, builder.return_block());
714 let mut spread_arg = None;
715 if abi == Abi::RustCall {
716 // RustCall pseudo-ABI untuples the last argument.
717 spread_arg = Some(Local::new(arguments.len()));
719 info!("fn_id {:?} has attrs {:?}", fn_def_id,
720 tcx.get_attrs(fn_def_id));
722 let mut mir = builder.finish(yield_ty);
723 mir.spread_arg = spread_arg;
727 fn construct_const<'a, 'gcx, 'tcx>(
728 hir: Cx<'a, 'gcx, 'tcx>,
729 body_id: hir::BodyId,
733 let ast_expr = &tcx.hir().body(body_id).value;
734 let ty = hir.tables().expr_ty_adjusted(ast_expr);
735 let owner_id = tcx.hir().body_owner(body_id);
736 let span = tcx.hir().span(owner_id);
737 let mut builder = Builder::new(hir, span, 0, Safety::Safe, ty, ty_span,vec![]);
739 let mut block = START_BLOCK;
740 let expr = builder.hir.mirror(ast_expr);
741 unpack!(block = builder.into_expr(&Place::RETURN_PLACE, block, expr));
743 let source_info = builder.source_info(span);
744 builder.cfg.terminate(block, source_info, TerminatorKind::Return);
746 // Constants can't `return` so a return block should not be created.
747 assert_eq!(builder.cached_return_block, None);
749 // Constants may be match expressions in which case an unreachable block may
750 // be created, so terminate it properly.
751 if let Some(unreachable_block) = builder.cached_unreachable_block {
752 builder.cfg.terminate(unreachable_block, source_info,
753 TerminatorKind::Unreachable);
759 fn construct_error<'a, 'gcx, 'tcx>(hir: Cx<'a, 'gcx, 'tcx>,
760 body_id: hir::BodyId)
762 let owner_id = hir.tcx().hir().body_owner(body_id);
763 let span = hir.tcx().hir().span(owner_id);
764 let ty = hir.tcx().types.err;
765 let mut builder = Builder::new(hir, span, 0, Safety::Safe, ty, span, vec![]);
766 let source_info = builder.source_info(span);
767 builder.cfg.terminate(START_BLOCK, source_info, TerminatorKind::Unreachable);
771 impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> {
772 fn new(hir: Cx<'a, 'gcx, 'tcx>,
778 upvar_decls: Vec<UpvarDecl>)
779 -> Builder<'a, 'gcx, 'tcx> {
780 let lint_level = LintLevel::Explicit(hir.root_lint_level);
781 let mut builder = Builder {
783 cfg: CFG { basic_blocks: IndexVec::new() },
787 block_context: BlockContext::new(),
788 source_scopes: IndexVec::new(),
789 source_scope: OUTERMOST_SOURCE_SCOPE,
790 source_scope_local_data: IndexVec::new(),
791 guard_context: vec![],
792 push_unsafe_count: 0,
793 unpushed_unsafe: safety,
794 breakable_scopes: vec![],
795 local_decls: IndexVec::from_elem_n(
796 LocalDecl::new_return_place(return_ty, return_span),
799 canonical_user_type_annotations: IndexVec::new(),
801 var_indices: Default::default(),
803 cached_resume_block: None,
804 cached_return_block: None,
805 cached_unreachable_block: None,
808 assert_eq!(builder.cfg.start_new_block(), START_BLOCK);
810 builder.new_source_scope(span, lint_level, Some(safety)),
811 OUTERMOST_SOURCE_SCOPE);
812 builder.source_scopes[OUTERMOST_SOURCE_SCOPE].parent_scope = None;
818 yield_ty: Option<Ty<'tcx>>)
820 for (index, block) in self.cfg.basic_blocks.iter().enumerate() {
821 if block.terminator.is_none() {
822 span_bug!(self.fn_span, "no terminator on block {:?}", index);
827 self.cfg.basic_blocks,
829 ClearCrossCrate::Set(self.source_scope_local_data),
833 self.canonical_user_type_annotations,
837 self.hir.control_flow_destroyed(),
841 fn args_and_body(&mut self,
842 mut block: BasicBlock,
843 arguments: &[ArgInfo<'gcx>],
844 argument_scope: region::Scope,
845 ast_body: &'gcx hir::Expr)
848 // Allocate locals for the function arguments
849 for &ArgInfo(ty, _, pattern, _) in arguments.iter() {
850 // If this is a simple binding pattern, give the local a name for
851 // debuginfo and so that error reporting knows that this is a user
852 // variable. For any other pattern the pattern introduces new
853 // variables which will be named instead.
855 if let Some(pat) = pattern {
857 hir::PatKind::Binding(hir::BindingAnnotation::Unannotated, _, ident, _)
858 | hir::PatKind::Binding(hir::BindingAnnotation::Mutable, _, ident, _) => {
859 name = Some(ident.name);
865 let source_info = SourceInfo {
866 scope: OUTERMOST_SOURCE_SCOPE,
867 span: pattern.map_or(self.fn_span, |pat| pat.span)
869 self.local_decls.push(LocalDecl {
870 mutability: Mutability::Mut,
872 user_ty: UserTypeProjections::none(),
874 visibility_scope: source_info.scope,
877 is_user_variable: None,
882 let mut scope = None;
883 // Bind the argument patterns
884 for (index, arg_info) in arguments.iter().enumerate() {
885 // Function arguments always get the first Local indices after the return place
886 let local = Local::new(index + 1);
887 let place = Place::Base(PlaceBase::Local(local));
888 let &ArgInfo(ty, opt_ty_info, pattern, ref self_binding) = arg_info;
890 // Make sure we drop (parts of) the argument even when not matched on.
892 pattern.as_ref().map_or(ast_body.span, |pat| pat.span),
893 argument_scope, &place, ty,
894 DropKind::Value { cached_block: CachedBlock::default() },
897 if let Some(pattern) = pattern {
898 let pattern = self.hir.pattern_from_hir(pattern);
899 let span = pattern.span;
901 match *pattern.kind {
902 // Don't introduce extra copies for simple bindings
903 PatternKind::Binding { mutability, var, mode: BindingMode::ByValue, .. } => {
904 self.local_decls[local].mutability = mutability;
905 self.local_decls[local].is_user_variable =
906 if let Some(kind) = self_binding {
907 Some(ClearCrossCrate::Set(BindingForm::ImplicitSelf(*kind)))
909 let binding_mode = ty::BindingMode::BindByValue(mutability.into());
910 Some(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
913 opt_match_place: Some((Some(place.clone()), span)),
917 self.var_indices.insert(var, LocalsForNode::One(local));
920 scope = self.declare_bindings(scope, ast_body.span,
921 LintLevel::Inherited, &pattern,
922 matches::ArmHasGuard(false),
923 Some((Some(&place), span)));
924 unpack!(block = self.place_into_pattern(block, pattern, &place, false));
930 // Enter the argument pattern bindings source scope, if it exists.
931 if let Some(source_scope) = scope {
932 self.source_scope = source_scope;
935 let body = self.hir.mirror(ast_body);
936 self.into(&Place::RETURN_PLACE, block, body)
939 fn get_unit_temp(&mut self) -> Place<'tcx> {
940 match self.unit_temp {
941 Some(ref tmp) => tmp.clone(),
943 let ty = self.hir.unit_ty();
944 let fn_span = self.fn_span;
945 let tmp = self.temp(ty, fn_span);
946 self.unit_temp = Some(tmp.clone());
952 fn return_block(&mut self) -> BasicBlock {
953 match self.cached_return_block {
956 let rb = self.cfg.start_new_block();
957 self.cached_return_block = Some(rb);
963 fn unreachable_block(&mut self) -> BasicBlock {
964 match self.cached_unreachable_block {
967 let ub = self.cfg.start_new_block();
968 self.cached_unreachable_block = Some(ub);
975 ///////////////////////////////////////////////////////////////////////////
976 // Builder methods are broken up into modules, depending on what kind
977 // of thing is being lowered. Note that they use the `unpack` macro
978 // above extensively.