2 use crate::build::scope::DropKind;
3 use crate::thir::cx::Cx;
4 use crate::thir::{BindingMode, LintLevel, PatKind};
5 use rustc_attr::{self as attr, UnwindAttr};
6 use rustc_errors::ErrorReported;
8 use rustc_hir::def_id::{DefId, LocalDefId};
9 use rustc_hir::lang_items::LangItem;
10 use rustc_hir::{GeneratorKind, HirIdMap, Node};
11 use rustc_index::vec::{Idx, IndexVec};
12 use rustc_infer::infer::TyCtxtInferExt;
13 use rustc_middle::middle::region;
14 use rustc_middle::mir::*;
15 use rustc_middle::ty::subst::Subst;
16 use rustc_middle::ty::{self, Ty, TyCtxt, TypeFoldable};
17 use rustc_span::symbol::kw;
19 use rustc_target::spec::abi::Abi;
20 use rustc_target::spec::PanicStrategy;
24 crate fn mir_built<'tcx>(
26 def: ty::WithOptConstParam<LocalDefId>,
27 ) -> &'tcx ty::steal::Steal<Body<'tcx>> {
28 if let Some(def) = def.try_upgrade(tcx) {
29 return tcx.mir_built(def);
32 tcx.alloc_steal_mir(mir_build(tcx, def))
35 /// Construct the MIR for a given `DefId`.
36 fn mir_build(tcx: TyCtxt<'_>, def: ty::WithOptConstParam<LocalDefId>) -> Body<'_> {
37 let id = tcx.hir().local_def_id_to_hir_id(def.did);
39 // Figure out what primary body this item has.
40 let (body_id, return_ty_span, span_with_body) = match tcx.hir().get(id) {
41 Node::Expr(hir::Expr { kind: hir::ExprKind::Closure(_, decl, body_id, _, _), .. }) => {
42 (*body_id, decl.output.span(), None)
44 Node::Item(hir::Item {
45 kind: hir::ItemKind::Fn(hir::FnSig { decl, .. }, _, body_id),
49 | Node::ImplItem(hir::ImplItem {
50 kind: hir::ImplItemKind::Fn(hir::FnSig { decl, .. }, body_id),
54 | Node::TraitItem(hir::TraitItem {
55 kind: hir::TraitItemKind::Fn(hir::FnSig { decl, .. }, hir::TraitFn::Provided(body_id)),
59 // Use the `Span` of the `Item/ImplItem/TraitItem` as the body span,
60 // since the def span of a function does not include the body
61 (*body_id, decl.output.span(), Some(*span))
63 Node::Item(hir::Item {
64 kind: hir::ItemKind::Static(ty, _, body_id) | hir::ItemKind::Const(ty, body_id),
67 | Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Const(ty, body_id), .. })
68 | Node::TraitItem(hir::TraitItem {
69 kind: hir::TraitItemKind::Const(ty, Some(body_id)),
71 }) => (*body_id, ty.span, None),
72 Node::AnonConst(hir::AnonConst { body, hir_id, .. }) => (*body, tcx.hir().span(*hir_id), None),
74 _ => span_bug!(tcx.hir().span(id), "can't build MIR for {:?}", def.did),
77 // If we don't have a specialized span for the body, just use the
79 let span_with_body = span_with_body.unwrap_or_else(|| tcx.hir().span(id));
81 tcx.infer_ctxt().enter(|infcx| {
82 let cx = Cx::new(&infcx, def, id);
83 let body = if let Some(ErrorReported) = cx.typeck_results().tainted_by_errors {
84 build::construct_error(cx, body_id)
85 } else if cx.body_owner_kind.is_fn_or_closure() {
86 // fetch the fully liberated fn signature (that is, all bound
87 // types/lifetimes replaced)
88 let fn_sig = cx.typeck_results().liberated_fn_sigs()[id];
89 let fn_def_id = tcx.hir().local_def_id(id);
91 let safety = match fn_sig.unsafety {
92 hir::Unsafety::Normal => Safety::Safe,
93 hir::Unsafety::Unsafe => Safety::FnUnsafe,
96 let body = tcx.hir().body(body_id);
97 let ty = tcx.type_of(fn_def_id);
98 let mut abi = fn_sig.abi;
99 let implicit_argument = match ty.kind {
101 // HACK(eddyb) Avoid having RustCall on closures,
102 // as it adds unnecessary (and wrong) auto-tupling.
104 vec![ArgInfo(liberated_closure_env_ty(tcx, id, body_id), None, None, None)]
106 ty::Generator(..) => {
107 let gen_ty = tcx.typeck_body(body_id).node_type(id);
109 // The resume argument may be missing, in that case we need to provide it here.
110 // It will always be `()` in this case.
111 if body.params.is_empty() {
113 ArgInfo(gen_ty, None, None, None),
114 ArgInfo(tcx.mk_unit(), None, None, None),
117 vec![ArgInfo(gen_ty, None, None, None)]
123 let explicit_arguments = body.params.iter().enumerate().map(|(index, arg)| {
124 let owner_id = tcx.hir().body_owner(body_id);
127 if let Some(ref fn_decl) = tcx.hir().fn_decl_by_hir_id(owner_id) {
128 opt_ty_info = fn_decl.inputs.get(index).map(|ty| ty.span);
129 self_arg = if index == 0 && fn_decl.implicit_self.has_implicit_self() {
130 match fn_decl.implicit_self {
131 hir::ImplicitSelfKind::Imm => Some(ImplicitSelfKind::Imm),
132 hir::ImplicitSelfKind::Mut => Some(ImplicitSelfKind::Mut),
133 hir::ImplicitSelfKind::ImmRef => Some(ImplicitSelfKind::ImmRef),
134 hir::ImplicitSelfKind::MutRef => Some(ImplicitSelfKind::MutRef),
145 // C-variadic fns also have a `VaList` input that's not listed in `fn_sig`
146 // (as it's created inside the body itself, not passed in from outside).
147 let ty = if fn_sig.c_variadic && index == fn_sig.inputs().len() {
148 let va_list_did = tcx.require_lang_item(LangItem::VaList, Some(arg.span));
150 tcx.type_of(va_list_did).subst(tcx, &[tcx.lifetimes.re_erased.into()])
152 fn_sig.inputs()[index]
155 ArgInfo(ty, opt_ty_info, Some(&arg), self_arg)
158 let arguments = implicit_argument.into_iter().chain(explicit_arguments);
160 let (yield_ty, return_ty) = if body.generator_kind.is_some() {
161 let gen_ty = tcx.typeck_body(body_id).node_type(id);
162 let gen_sig = match gen_ty.kind {
163 ty::Generator(_, gen_substs, ..) => gen_substs.as_generator().sig(),
164 _ => span_bug!(tcx.hir().span(id), "generator w/o generator type: {:?}", ty),
166 (Some(gen_sig.yield_ty), gen_sig.return_ty)
168 (None, fn_sig.output())
171 let mut mir = build::construct_fn(
182 mir.yield_ty = yield_ty;
185 // Get the revealed type of this const. This is *not* the adjusted
186 // type of its body, which may be a subtype of this type. For
190 // static X: fn(&'static ()) = foo;
192 // The adjusted type of the body of X is `for<'a> fn(&'a ())` which
193 // is not the same as the type of X. We need the type of the return
194 // place to be the type of the constant because NLL typeck will
197 let return_ty = cx.typeck_results().node_type(id);
199 build::construct_const(cx, body_id, return_ty, return_ty_span)
202 lints::check(tcx, &body, def.did);
204 // The borrow checker will replace all the regions here with its own
205 // inference variables. There's no point having non-erased regions here.
206 // The exception is `body.user_type_annotations`, which is used unmodified
207 // by borrow checking.
209 !(body.local_decls.has_free_regions()
210 || body.basic_blocks().has_free_regions()
211 || body.var_debug_info.has_free_regions()
212 || body.yield_ty.has_free_regions()),
213 "Unexpected free regions in MIR: {:?}",
221 ///////////////////////////////////////////////////////////////////////////
222 // BuildMir -- walks a crate, looking for fn items and methods to build MIR from
224 fn liberated_closure_env_ty(
226 closure_expr_id: hir::HirId,
227 body_id: hir::BodyId,
229 let closure_ty = tcx.typeck_body(body_id).node_type(closure_expr_id);
231 let (closure_def_id, closure_substs) = match closure_ty.kind {
232 ty::Closure(closure_def_id, closure_substs) => (closure_def_id, closure_substs),
233 _ => bug!("closure expr does not have closure type: {:?}", closure_ty),
236 let closure_env_ty = tcx.closure_env_ty(closure_def_id, closure_substs).unwrap();
237 tcx.erase_late_bound_regions(&closure_env_ty)
240 #[derive(Debug, PartialEq, Eq)]
242 /// Evaluation is currently within a statement.
244 /// Examples include:
246 /// 2. `let _ = EXPR;`
247 /// 3. `let x = EXPR;`
249 /// If true, then statement discards result from evaluating
250 /// the expression (such as examples 1 and 2 above).
251 ignores_expr_result: bool,
254 /// Evaluation is currently within the tail expression of a block.
256 /// Example: `{ STMT_1; STMT_2; EXPR }`
258 /// If true, then the surrounding context of the block ignores
259 /// the result of evaluating the block's tail expression.
261 /// Example: `let _ = { STMT_1; EXPR };`
262 tail_result_is_ignored: bool,
264 /// `Span` of the tail expression.
268 /// Generic mark meaning that the block occurred as a subexpression
269 /// where the result might be used.
271 /// Examples: `foo(EXPR)`, `match EXPR { ... }`
276 fn is_tail_expr(&self) -> bool {
278 BlockFrame::TailExpr { .. } => true,
280 BlockFrame::Statement { .. } | BlockFrame::SubExpr => false,
283 fn is_statement(&self) -> bool {
285 BlockFrame::Statement { .. } => true,
287 BlockFrame::TailExpr { .. } | BlockFrame::SubExpr => false,
293 struct BlockContext(Vec<BlockFrame>);
295 struct Builder<'a, 'tcx> {
301 generator_kind: Option<GeneratorKind>,
303 /// The current set of scopes, updated as we traverse;
304 /// see the `scope` module for more details.
305 scopes: scope::Scopes<'tcx>,
307 /// The block-context: each time we build the code within an thir::Block,
308 /// we push a frame here tracking whether we are building a statement or
309 /// if we are pushing the tail expression of the block. This is used to
310 /// embed information in generated temps about whether they were created
311 /// for a block tail expression or not.
313 /// It would be great if we could fold this into `self.scopes`
314 /// somehow, but right now I think that is very tightly tied to
315 /// the code generation in ways that we cannot (or should not)
316 /// start just throwing new entries onto that vector in order to
317 /// distinguish the context of EXPR1 from the context of EXPR2 in
318 /// `{ STMTS; EXPR1 } + EXPR2`.
319 block_context: BlockContext,
321 /// The current unsafe block in scope, even if it is hidden by
322 /// a `PushUnsafeBlock`.
323 unpushed_unsafe: Safety,
325 /// The number of `push_unsafe_block` levels in scope.
326 push_unsafe_count: usize,
328 /// The vector of all scopes that we have created thus far;
329 /// we track this for debuginfo later.
330 source_scopes: IndexVec<SourceScope, SourceScopeData>,
331 source_scope: SourceScope,
333 /// The guard-context: each time we build the guard expression for
334 /// a match arm, we push onto this stack, and then pop when we
335 /// finish building it.
336 guard_context: Vec<GuardFrame>,
338 /// Maps `HirId`s of variable bindings to the `Local`s created for them.
339 /// (A match binding can have two locals; the 2nd is for the arm's guard.)
340 var_indices: HirIdMap<LocalsForNode>,
341 local_decls: IndexVec<Local, LocalDecl<'tcx>>,
342 canonical_user_type_annotations: ty::CanonicalUserTypeAnnotations<'tcx>,
343 upvar_mutbls: Vec<Mutability>,
344 unit_temp: Option<Place<'tcx>>,
346 var_debug_info: Vec<VarDebugInfo<'tcx>>,
348 /// Cached block with the `RESUME` terminator; this is created
349 /// when first set of cleanups are built.
350 cached_resume_block: Option<BasicBlock>,
351 /// Cached block with the `RETURN` terminator.
352 cached_return_block: Option<BasicBlock>,
353 /// Cached block with the `UNREACHABLE` terminator.
354 cached_unreachable_block: Option<BasicBlock>,
357 impl<'a, 'tcx> Builder<'a, 'tcx> {
358 fn is_bound_var_in_guard(&self, id: hir::HirId) -> bool {
359 self.guard_context.iter().any(|frame| frame.locals.iter().any(|local| local.id == id))
362 fn var_local_id(&self, id: hir::HirId, for_guard: ForGuard) -> Local {
363 self.var_indices[&id].local_id(for_guard)
371 fn push(&mut self, bf: BlockFrame) {
374 fn pop(&mut self) -> Option<BlockFrame> {
378 /// Traverses the frames on the `BlockContext`, searching for either
379 /// the first block-tail expression frame with no intervening
382 /// Notably, this skips over `SubExpr` frames; this method is
383 /// meant to be used in the context of understanding the
384 /// relationship of a temp (created within some complicated
385 /// expression) with its containing expression, and whether the
386 /// value of that *containing expression* (not the temp!) is
388 fn currently_in_block_tail(&self) -> Option<BlockTailInfo> {
389 for bf in self.0.iter().rev() {
391 BlockFrame::SubExpr => continue,
392 BlockFrame::Statement { .. } => break,
393 &BlockFrame::TailExpr { tail_result_is_ignored, span } => {
394 return Some(BlockTailInfo { tail_result_is_ignored, span });
402 /// Looks at the topmost frame on the BlockContext and reports
403 /// whether its one that would discard a block tail result.
405 /// Unlike `currently_within_ignored_tail_expression`, this does
406 /// *not* skip over `SubExpr` frames: here, we want to know
407 /// whether the block result itself is discarded.
408 fn currently_ignores_tail_results(&self) -> bool {
409 match self.0.last() {
410 // no context: conservatively assume result is read
413 // sub-expression: block result feeds into some computation
414 Some(BlockFrame::SubExpr) => false,
416 // otherwise: use accumulated is_ignored state.
418 BlockFrame::TailExpr { tail_result_is_ignored: ignored, .. }
419 | BlockFrame::Statement { ignores_expr_result: ignored },
427 /// In the usual case, a `HirId` for an identifier maps to at most
428 /// one `Local` declaration.
431 /// The exceptional case is identifiers in a match arm's pattern
432 /// that are referenced in a guard of that match arm. For these,
433 /// we have `2` Locals.
435 /// * `for_arm_body` is the Local used in the arm body (which is
436 /// just like the `One` case above),
438 /// * `ref_for_guard` is the Local used in the arm's guard (which
439 /// is a reference to a temp that is an alias of
441 ForGuard { ref_for_guard: Local, for_arm_body: Local },
445 struct GuardFrameLocal {
449 impl GuardFrameLocal {
450 fn new(id: hir::HirId, _binding_mode: BindingMode) -> Self {
451 GuardFrameLocal { id }
457 /// These are the id's of names that are bound by patterns of the
458 /// arm of *this* guard.
460 /// (Frames higher up the stack will have the id's bound in arms
461 /// further out, such as in a case like:
464 /// P1(id1) if (... (match E2 { P2(id2) if ... => B2 })) => B1,
467 /// here, when building for FIXME.
468 locals: Vec<GuardFrameLocal>,
471 /// `ForGuard` indicates whether we are talking about:
472 /// 1. The variable for use outside of guard expressions, or
473 /// 2. The temp that holds reference to (1.), which is actually what the
474 /// guard expressions see.
475 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
482 fn local_id(&self, for_guard: ForGuard) -> Local {
483 match (self, for_guard) {
484 (&LocalsForNode::One(local_id), ForGuard::OutsideGuard)
486 &LocalsForNode::ForGuard { ref_for_guard: local_id, .. },
487 ForGuard::RefWithinGuard,
489 | (&LocalsForNode::ForGuard { for_arm_body: local_id, .. }, ForGuard::OutsideGuard) => {
493 (&LocalsForNode::One(_), ForGuard::RefWithinGuard) => {
494 bug!("anything with one local should never be within a guard.")
501 basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
504 rustc_index::newtype_index! {
505 struct ScopeId { .. }
508 ///////////////////////////////////////////////////////////////////////////
509 /// The `BlockAnd` "monad" packages up the new basic block along with a
510 /// produced value (sometimes just unit, of course). The `unpack!`
511 /// macro (and methods below) makes working with `BlockAnd` much more
514 #[must_use = "if you don't use one of these results, you're leaving a dangling edge"]
515 struct BlockAnd<T>(BasicBlock, T);
517 trait BlockAndExtension {
518 fn and<T>(self, v: T) -> BlockAnd<T>;
519 fn unit(self) -> BlockAnd<()>;
522 impl BlockAndExtension for BasicBlock {
523 fn and<T>(self, v: T) -> BlockAnd<T> {
527 fn unit(self) -> BlockAnd<()> {
532 /// Update a block pointer and return the value.
533 /// Use it like `let x = unpack!(block = self.foo(block, foo))`.
534 macro_rules! unpack {
535 ($x:ident = $c:expr) => {{
536 let BlockAnd(b, v) = $c;
542 let BlockAnd(b, ()) = $c;
547 fn should_abort_on_panic(tcx: TyCtxt<'_>, fn_def_id: LocalDefId, _abi: Abi) -> bool {
548 // Validate `#[unwind]` syntax regardless of platform-specific panic strategy.
549 let attrs = &tcx.get_attrs(fn_def_id.to_def_id());
550 let unwind_attr = attr::find_unwind_attr(&tcx.sess, attrs);
552 // We never unwind, so it's not relevant to stop an unwind.
553 if tcx.sess.panic_strategy() != PanicStrategy::Unwind {
557 // This is a special case: some functions have a C abi but are meant to
558 // unwind anyway. Don't stop them.
560 None => false, // FIXME(#58794); should be `!(abi == Abi::Rust || abi == Abi::RustCall)`
561 Some(UnwindAttr::Allowed) => false,
562 Some(UnwindAttr::Aborts) => true,
566 ///////////////////////////////////////////////////////////////////////////
567 /// the main entry point for building MIR for a function
569 struct ArgInfo<'tcx>(
572 Option<&'tcx hir::Param<'tcx>>,
573 Option<ImplicitSelfKind>,
576 fn construct_fn<'a, 'tcx, A>(
583 return_ty_span: Span,
584 body: &'tcx hir::Body<'tcx>,
588 A: Iterator<Item = ArgInfo<'tcx>>,
590 let arguments: Vec<_> = arguments.collect();
593 let tcx_hir = tcx.hir();
594 let span = tcx_hir.span(fn_id);
596 let fn_def_id = tcx_hir.local_def_id(fn_id);
598 let mut builder = Builder::new(
608 let call_site_scope =
609 region::Scope { id: body.value.hir_id.local_id, data: region::ScopeData::CallSite };
611 region::Scope { id: body.value.hir_id.local_id, data: region::ScopeData::Arguments };
612 let mut block = START_BLOCK;
613 let source_info = builder.source_info(span);
614 let call_site_s = (call_site_scope, source_info);
616 block = builder.in_scope(call_site_s, LintLevel::Inherited, |builder| {
617 if should_abort_on_panic(tcx, fn_def_id, abi) {
618 builder.schedule_abort();
621 let arg_scope_s = (arg_scope, source_info);
622 // `return_block` is called when we evaluate a `return` expression, so
623 // we just use `START_BLOCK` here.
625 block = builder.in_breakable_scope(
628 Place::return_place(),
630 builder.in_scope(arg_scope_s, LintLevel::Inherited, |builder| {
631 builder.args_and_body(
633 fn_def_id.to_def_id(),
642 // Attribute epilogue to function's closing brace
643 let fn_end = span_with_body.shrink_to_hi();
644 let source_info = builder.source_info(fn_end);
645 let return_block = builder.return_block();
646 builder.cfg.goto(block, source_info, return_block);
647 builder.cfg.terminate(return_block, source_info, TerminatorKind::Return);
648 // Attribute any unreachable codepaths to the function's closing brace
649 if let Some(unreachable_block) = builder.cached_unreachable_block {
650 builder.cfg.terminate(unreachable_block, source_info, TerminatorKind::Unreachable);
655 assert_eq!(block, builder.return_block());
657 let spread_arg = if abi == Abi::RustCall {
658 // RustCall pseudo-ABI untuples the last argument.
659 Some(Local::new(arguments.len()))
663 debug!("fn_id {:?} has attrs {:?}", fn_def_id, tcx.get_attrs(fn_def_id.to_def_id()));
665 let mut body = builder.finish();
666 body.spread_arg = spread_arg;
670 fn construct_const<'a, 'tcx>(
672 body_id: hir::BodyId,
677 let owner_id = tcx.hir().body_owner(body_id);
678 let span = tcx.hir().span(owner_id);
679 let mut builder = Builder::new(hir, span, 0, Safety::Safe, const_ty, const_ty_span, None);
681 let mut block = START_BLOCK;
682 let ast_expr = &tcx.hir().body(body_id).value;
683 let expr = builder.hir.mirror(ast_expr);
684 unpack!(block = builder.into_expr(Place::return_place(), block, expr));
686 let source_info = builder.source_info(span);
687 builder.cfg.terminate(block, source_info, TerminatorKind::Return);
689 // Constants can't `return` so a return block should not be created.
690 assert_eq!(builder.cached_return_block, None);
692 // Constants may be match expressions in which case an unreachable block may
693 // be created, so terminate it properly.
694 if let Some(unreachable_block) = builder.cached_unreachable_block {
695 builder.cfg.terminate(unreachable_block, source_info, TerminatorKind::Unreachable);
701 /// Construct MIR for a item that has had errors in type checking.
703 /// This is required because we may still want to run MIR passes on an item
704 /// with type errors, but normal MIR construction can't handle that in general.
705 fn construct_error<'a, 'tcx>(hir: Cx<'a, 'tcx>, body_id: hir::BodyId) -> Body<'tcx> {
707 let owner_id = tcx.hir().body_owner(body_id);
708 let span = tcx.hir().span(owner_id);
709 let ty = tcx.ty_error();
710 let num_params = match hir.body_owner_kind {
711 hir::BodyOwnerKind::Fn => tcx.hir().fn_decl_by_hir_id(owner_id).unwrap().inputs.len(),
712 hir::BodyOwnerKind::Closure => {
713 if tcx.hir().body(body_id).generator_kind().is_some() {
714 // Generators have an implicit `self` parameter *and* a possibly
715 // implicit resume parameter.
718 // The implicit self parameter adds another local in MIR.
719 1 + tcx.hir().fn_decl_by_hir_id(owner_id).unwrap().inputs.len()
722 hir::BodyOwnerKind::Const => 0,
723 hir::BodyOwnerKind::Static(_) => 0,
725 let mut builder = Builder::new(hir, span, num_params, Safety::Safe, ty, span, None);
726 let source_info = builder.source_info(span);
727 // Some MIR passes will expect the number of parameters to match the
728 // function declaration.
729 for _ in 0..num_params {
730 builder.local_decls.push(LocalDecl::with_source_info(ty, source_info));
732 builder.cfg.terminate(START_BLOCK, source_info, TerminatorKind::Unreachable);
733 let mut body = builder.finish();
734 if tcx.hir().body(body_id).generator_kind.is_some() {
735 body.yield_ty = Some(ty);
740 impl<'a, 'tcx> Builder<'a, 'tcx> {
748 generator_kind: Option<GeneratorKind>,
749 ) -> Builder<'a, 'tcx> {
750 let lint_level = LintLevel::Explicit(hir.root_lint_level);
751 let mut builder = Builder {
753 cfg: CFG { basic_blocks: IndexVec::new() },
757 scopes: Default::default(),
758 block_context: BlockContext::new(),
759 source_scopes: IndexVec::new(),
760 source_scope: OUTERMOST_SOURCE_SCOPE,
761 guard_context: vec![],
762 push_unsafe_count: 0,
763 unpushed_unsafe: safety,
764 local_decls: IndexVec::from_elem_n(LocalDecl::new(return_ty, return_span), 1),
765 canonical_user_type_annotations: IndexVec::new(),
766 upvar_mutbls: vec![],
767 var_indices: Default::default(),
769 var_debug_info: vec![],
770 cached_resume_block: None,
771 cached_return_block: None,
772 cached_unreachable_block: None,
775 assert_eq!(builder.cfg.start_new_block(), START_BLOCK);
777 builder.new_source_scope(span, lint_level, Some(safety)),
778 OUTERMOST_SOURCE_SCOPE
780 builder.source_scopes[OUTERMOST_SOURCE_SCOPE].parent_scope = None;
785 fn finish(self) -> Body<'tcx> {
786 for (index, block) in self.cfg.basic_blocks.iter().enumerate() {
787 if block.terminator.is_none() {
788 span_bug!(self.fn_span, "no terminator on block {:?}", index);
793 self.cfg.basic_blocks,
796 self.canonical_user_type_annotations,
806 mut block: BasicBlock,
808 arguments: &[ArgInfo<'tcx>],
809 argument_scope: region::Scope,
810 ast_body: &'tcx hir::Expr<'tcx>,
812 // Allocate locals for the function arguments
813 for &ArgInfo(ty, _, arg_opt, _) in arguments.iter() {
815 SourceInfo::outermost(arg_opt.map_or(self.fn_span, |arg| arg.pat.span));
816 let arg_local = self.local_decls.push(LocalDecl::with_source_info(ty, source_info));
818 // If this is a simple binding pattern, give debuginfo a nice name.
819 if let Some(arg) = arg_opt {
820 if let Some(ident) = arg.pat.simple_ident() {
821 self.var_debug_info.push(VarDebugInfo {
824 place: arg_local.into(),
830 let tcx = self.hir.tcx();
831 let tcx_hir = tcx.hir();
832 let hir_typeck_results = self.hir.typeck_results();
834 // In analyze_closure() in upvar.rs we gathered a list of upvars used by a
835 // indexed closure and we stored in a map called closure_captures in TypeckResults
836 // with the closure's DefId. Here, we run through that vec of UpvarIds for
837 // the given closure and use the necessary information to create upvar
838 // debuginfo and to fill `self.upvar_mutbls`.
839 if let Some(upvars) = hir_typeck_results.closure_captures.get(&fn_def_id) {
840 let closure_env_arg = Local::new(1);
841 let mut closure_env_projs = vec![];
842 let mut closure_ty = self.local_decls[closure_env_arg].ty;
843 if let ty::Ref(_, ty, _) = closure_ty.kind {
844 closure_env_projs.push(ProjectionElem::Deref);
847 let upvar_substs = match closure_ty.kind {
848 ty::Closure(_, substs) => ty::UpvarSubsts::Closure(substs),
849 ty::Generator(_, substs, _) => ty::UpvarSubsts::Generator(substs),
850 _ => span_bug!(self.fn_span, "upvars with non-closure env ty {:?}", closure_ty),
852 let upvar_tys = upvar_substs.upvar_tys();
853 let upvars_with_tys = upvars.iter().zip(upvar_tys);
854 self.upvar_mutbls = upvars_with_tys
856 .map(|(i, ((&var_id, &upvar_id), ty))| {
857 let capture = hir_typeck_results.upvar_capture(upvar_id);
859 let mut mutability = Mutability::Not;
860 let mut name = kw::Invalid;
861 if let Some(Node::Binding(pat)) = tcx_hir.find(var_id) {
862 if let hir::PatKind::Binding(_, _, ident, _) = pat.kind {
864 match hir_typeck_results
865 .extract_binding_mode(tcx.sess, pat.hir_id, pat.span)
867 Some(ty::BindByValue(hir::Mutability::Mut)) => {
868 mutability = Mutability::Mut;
870 Some(_) => mutability = Mutability::Not,
876 let mut projs = closure_env_projs.clone();
877 projs.push(ProjectionElem::Field(Field::new(i), ty));
879 ty::UpvarCapture::ByValue => {}
880 ty::UpvarCapture::ByRef(..) => {
881 projs.push(ProjectionElem::Deref);
885 self.var_debug_info.push(VarDebugInfo {
887 source_info: SourceInfo::outermost(tcx_hir.span(var_id)),
889 local: closure_env_arg,
890 projection: tcx.intern_place_elems(&projs),
899 let mut scope = None;
900 // Bind the argument patterns
901 for (index, arg_info) in arguments.iter().enumerate() {
902 // Function arguments always get the first Local indices after the return place
903 let local = Local::new(index + 1);
904 let place = Place::from(local);
905 let &ArgInfo(_, opt_ty_info, arg_opt, ref self_binding) = arg_info;
907 // Make sure we drop (parts of) the argument even when not matched on.
909 arg_opt.as_ref().map_or(ast_body.span, |arg| arg.pat.span),
915 if let Some(arg) = arg_opt {
916 let pattern = self.hir.pattern_from_hir(&arg.pat);
917 let original_source_scope = self.source_scope;
918 let span = pattern.span;
919 self.set_correct_source_scope_for_arg(arg.hir_id, original_source_scope, span);
920 match *pattern.kind {
921 // Don't introduce extra copies for simple bindings
925 mode: BindingMode::ByValue,
929 self.local_decls[local].mutability = mutability;
930 self.local_decls[local].source_info.scope = self.source_scope;
931 self.local_decls[local].local_info = if let Some(kind) = self_binding {
932 Some(box LocalInfo::User(ClearCrossCrate::Set(
933 BindingForm::ImplicitSelf(*kind),
936 let binding_mode = ty::BindingMode::BindByValue(mutability);
937 Some(box LocalInfo::User(ClearCrossCrate::Set(BindingForm::Var(
941 opt_match_place: Some((Some(place), span)),
946 self.var_indices.insert(var, LocalsForNode::One(local));
949 scope = self.declare_bindings(
953 matches::ArmHasGuard(false),
954 Some((Some(&place), span)),
956 unpack!(block = self.place_into_pattern(block, pattern, place, false));
959 self.source_scope = original_source_scope;
963 // Enter the argument pattern bindings source scope, if it exists.
964 if let Some(source_scope) = scope {
965 self.source_scope = source_scope;
968 let body = self.hir.mirror(ast_body);
969 self.into(Place::return_place(), block, body)
972 fn set_correct_source_scope_for_arg(
974 arg_hir_id: hir::HirId,
975 original_source_scope: SourceScope,
978 let tcx = self.hir.tcx();
979 let current_root = tcx.maybe_lint_level_root_bounded(arg_hir_id, self.hir.root_lint_level);
980 let parent_root = tcx.maybe_lint_level_root_bounded(
981 self.source_scopes[original_source_scope]
984 .assert_crate_local()
986 self.hir.root_lint_level,
988 if current_root != parent_root {
990 self.new_source_scope(pattern_span, LintLevel::Explicit(current_root), None);
994 fn get_unit_temp(&mut self) -> Place<'tcx> {
995 match self.unit_temp {
998 let ty = self.hir.unit_ty();
999 let fn_span = self.fn_span;
1000 let tmp = self.temp(ty, fn_span);
1001 self.unit_temp = Some(tmp);
1007 fn return_block(&mut self) -> BasicBlock {
1008 match self.cached_return_block {
1011 let rb = self.cfg.start_new_block();
1012 self.cached_return_block = Some(rb);
1019 ///////////////////////////////////////////////////////////////////////////
1020 // Builder methods are broken up into modules, depending on what kind
1021 // of thing is being lowered. Note that they use the `unpack` macro
1022 // above extensively.