2 use crate::build::scope::DropKind;
3 use crate::hair::cx::Cx;
4 use crate::hair::{BindingMode, LintLevel, PatKind};
5 use rustc_attr::{self as attr, UnwindAttr};
6 use rustc_errors::ErrorReported;
8 use rustc_hir::def_id::DefId;
9 use rustc_hir::lang_items;
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: TyCtxt<'_>, def_id: DefId) -> &ty::steal::Steal<Body<'_>> {
25 tcx.alloc_steal_mir(mir_build(tcx, def_id))
28 /// Construct the MIR for a given `DefId`.
29 fn mir_build(tcx: TyCtxt<'_>, def_id: DefId) -> Body<'_> {
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(id) {
34 Node::Expr(hir::Expr { kind: hir::ExprKind::Closure(_, decl, body_id, _, _), .. }) => {
35 (*body_id, decl.output.span())
37 Node::Item(hir::Item {
38 kind: hir::ItemKind::Fn(hir::FnSig { decl, .. }, _, body_id),
41 | Node::ImplItem(hir::ImplItem {
42 kind: hir::ImplItemKind::Fn(hir::FnSig { decl, .. }, body_id),
45 | Node::TraitItem(hir::TraitItem {
46 kind: hir::TraitItemKind::Fn(hir::FnSig { decl, .. }, hir::TraitFn::Provided(body_id)),
48 }) => (*body_id, decl.output.span()),
49 Node::Item(hir::Item {
50 kind: hir::ItemKind::Static(ty, _, body_id) | hir::ItemKind::Const(ty, body_id),
53 | Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Const(ty, body_id), .. })
54 | Node::TraitItem(hir::TraitItem {
55 kind: hir::TraitItemKind::Const(ty, Some(body_id)),
57 }) => (*body_id, ty.span),
58 Node::AnonConst(hir::AnonConst { body, hir_id, .. }) => (*body, tcx.hir().span(*hir_id)),
60 _ => span_bug!(tcx.hir().span(id), "can't build MIR for {:?}", def_id),
63 tcx.infer_ctxt().enter(|infcx| {
64 let cx = Cx::new(&infcx, id);
65 let body = if let Some(ErrorReported) = cx.tables().tainted_by_errors {
66 build::construct_error(cx, body_id)
67 } else if cx.body_owner_kind.is_fn_or_closure() {
68 // fetch the fully liberated fn signature (that is, all bound
69 // types/lifetimes replaced)
70 let fn_sig = cx.tables().liberated_fn_sigs()[id];
71 let fn_def_id = tcx.hir().local_def_id(id);
73 let safety = match fn_sig.unsafety {
74 hir::Unsafety::Normal => Safety::Safe,
75 hir::Unsafety::Unsafe => Safety::FnUnsafe,
78 let body = tcx.hir().body(body_id);
79 let ty = tcx.type_of(fn_def_id);
80 let mut abi = fn_sig.abi;
81 let implicit_argument = match ty.kind {
83 // HACK(eddyb) Avoid having RustCall on closures,
84 // as it adds unnecessary (and wrong) auto-tupling.
86 vec![ArgInfo(liberated_closure_env_ty(tcx, id, body_id), None, None, None)]
88 ty::Generator(..) => {
89 let gen_ty = tcx.body_tables(body_id).node_type(id);
91 // The resume argument may be missing, in that case we need to provide it here.
92 // It will always be `()` in this case.
93 if body.params.is_empty() {
95 ArgInfo(gen_ty, None, None, None),
96 ArgInfo(tcx.mk_unit(), None, None, None),
99 vec![ArgInfo(gen_ty, None, None, None)]
105 let explicit_arguments = body.params.iter().enumerate().map(|(index, arg)| {
106 let owner_id = tcx.hir().body_owner(body_id);
109 if let Some(ref fn_decl) = tcx.hir().fn_decl_by_hir_id(owner_id) {
110 opt_ty_info = fn_decl.inputs.get(index).map(|ty| ty.span);
111 self_arg = if index == 0 && fn_decl.implicit_self.has_implicit_self() {
112 match fn_decl.implicit_self {
113 hir::ImplicitSelfKind::Imm => Some(ImplicitSelfKind::Imm),
114 hir::ImplicitSelfKind::Mut => Some(ImplicitSelfKind::Mut),
115 hir::ImplicitSelfKind::ImmRef => Some(ImplicitSelfKind::ImmRef),
116 hir::ImplicitSelfKind::MutRef => Some(ImplicitSelfKind::MutRef),
127 // C-variadic fns also have a `VaList` input that's not listed in `fn_sig`
128 // (as it's created inside the body itself, not passed in from outside).
129 let ty = if fn_sig.c_variadic && index == fn_sig.inputs().len() {
131 tcx.require_lang_item(lang_items::VaListTypeLangItem, Some(arg.span));
133 tcx.type_of(va_list_did).subst(tcx, &[tcx.lifetimes.re_erased.into()])
135 fn_sig.inputs()[index]
138 ArgInfo(ty, opt_ty_info, Some(&arg), self_arg)
141 let arguments = implicit_argument.into_iter().chain(explicit_arguments);
143 let (yield_ty, return_ty) = if body.generator_kind.is_some() {
144 let gen_ty = tcx.body_tables(body_id).node_type(id);
145 let gen_sig = match gen_ty.kind {
146 ty::Generator(_, gen_substs, ..) => gen_substs.as_generator().sig(),
147 _ => span_bug!(tcx.hir().span(id), "generator w/o generator type: {:?}", ty),
149 (Some(gen_sig.yield_ty), gen_sig.return_ty)
151 (None, fn_sig.output())
154 let mut mir = build::construct_fn(
164 mir.yield_ty = yield_ty;
167 // Get the revealed type of this const. This is *not* the adjusted
168 // type of its body, which may be a subtype of this type. For
172 // static X: fn(&'static ()) = foo;
174 // The adjusted type of the body of X is `for<'a> fn(&'a ())` which
175 // is not the same as the type of X. We need the type of the return
176 // place to be the type of the constant because NLL typeck will
179 let return_ty = cx.tables().node_type(id);
181 build::construct_const(cx, body_id, return_ty, return_ty_span)
184 lints::check(tcx, &body, def_id);
186 // The borrow checker will replace all the regions here with its own
187 // inference variables. There's no point having non-erased regions here.
188 // The exception is `body.user_type_annotations`, which is used unmodified
189 // by borrow checking.
191 !(body.local_decls.has_free_regions()
192 || body.basic_blocks().has_free_regions()
193 || body.var_debug_info.has_free_regions()
194 || body.yield_ty.has_free_regions()),
195 "Unexpected free regions in MIR: {:?}",
203 ///////////////////////////////////////////////////////////////////////////
204 // BuildMir -- walks a crate, looking for fn items and methods to build MIR from
206 fn liberated_closure_env_ty(
208 closure_expr_id: hir::HirId,
209 body_id: hir::BodyId,
211 let closure_ty = tcx.body_tables(body_id).node_type(closure_expr_id);
213 let (closure_def_id, closure_substs) = match closure_ty.kind {
214 ty::Closure(closure_def_id, closure_substs) => (closure_def_id, closure_substs),
215 _ => bug!("closure expr does not have closure type: {:?}", closure_ty),
218 let closure_env_ty = tcx.closure_env_ty(closure_def_id, closure_substs).unwrap();
219 tcx.erase_late_bound_regions(&closure_env_ty)
222 #[derive(Debug, PartialEq, Eq)]
224 /// Evaluation is currently within a statement.
226 /// Examples include:
228 /// 2. `let _ = EXPR;`
229 /// 3. `let x = EXPR;`
231 /// If true, then statement discards result from evaluating
232 /// the expression (such as examples 1 and 2 above).
233 ignores_expr_result: bool,
236 /// Evaluation is currently within the tail expression of a block.
238 /// Example: `{ STMT_1; STMT_2; EXPR }`
240 /// If true, then the surrounding context of the block ignores
241 /// the result of evaluating the block's tail expression.
243 /// Example: `let _ = { STMT_1; EXPR };`
244 tail_result_is_ignored: bool,
247 /// Generic mark meaning that the block occurred as a subexpression
248 /// where the result might be used.
250 /// Examples: `foo(EXPR)`, `match EXPR { ... }`
255 fn is_tail_expr(&self) -> bool {
257 BlockFrame::TailExpr { .. } => true,
259 BlockFrame::Statement { .. } | BlockFrame::SubExpr => false,
262 fn is_statement(&self) -> bool {
264 BlockFrame::Statement { .. } => true,
266 BlockFrame::TailExpr { .. } | BlockFrame::SubExpr => false,
272 struct BlockContext(Vec<BlockFrame>);
274 struct Builder<'a, 'tcx> {
280 generator_kind: Option<GeneratorKind>,
282 /// The current set of scopes, updated as we traverse;
283 /// see the `scope` module for more details.
284 scopes: scope::Scopes<'tcx>,
286 /// The block-context: each time we build the code within an hair::Block,
287 /// we push a frame here tracking whether we are building a statement or
288 /// if we are pushing the tail expression of the block. This is used to
289 /// embed information in generated temps about whether they were created
290 /// for a block tail expression or not.
292 /// It would be great if we could fold this into `self.scopes`
293 /// somehow, but right now I think that is very tightly tied to
294 /// the code generation in ways that we cannot (or should not)
295 /// start just throwing new entries onto that vector in order to
296 /// distinguish the context of EXPR1 from the context of EXPR2 in
297 /// `{ STMTS; EXPR1 } + EXPR2`.
298 block_context: BlockContext,
300 /// The current unsafe block in scope, even if it is hidden by
301 /// a `PushUnsafeBlock`.
302 unpushed_unsafe: Safety,
304 /// The number of `push_unsafe_block` levels in scope.
305 push_unsafe_count: usize,
307 /// The vector of all scopes that we have created thus far;
308 /// we track this for debuginfo later.
309 source_scopes: IndexVec<SourceScope, SourceScopeData>,
310 source_scope: SourceScope,
312 /// The guard-context: each time we build the guard expression for
313 /// a match arm, we push onto this stack, and then pop when we
314 /// finish building it.
315 guard_context: Vec<GuardFrame>,
317 /// Maps `HirId`s of variable bindings to the `Local`s created for them.
318 /// (A match binding can have two locals; the 2nd is for the arm's guard.)
319 var_indices: HirIdMap<LocalsForNode>,
320 local_decls: IndexVec<Local, LocalDecl<'tcx>>,
321 canonical_user_type_annotations: ty::CanonicalUserTypeAnnotations<'tcx>,
322 upvar_mutbls: Vec<Mutability>,
323 unit_temp: Option<Place<'tcx>>,
325 var_debug_info: Vec<VarDebugInfo<'tcx>>,
327 /// Cached block with the `RESUME` terminator; this is created
328 /// when first set of cleanups are built.
329 cached_resume_block: Option<BasicBlock>,
330 /// Cached block with the `RETURN` terminator.
331 cached_return_block: Option<BasicBlock>,
332 /// Cached block with the `UNREACHABLE` terminator.
333 cached_unreachable_block: Option<BasicBlock>,
336 impl<'a, 'tcx> Builder<'a, 'tcx> {
337 fn is_bound_var_in_guard(&self, id: hir::HirId) -> bool {
338 self.guard_context.iter().any(|frame| frame.locals.iter().any(|local| local.id == id))
341 fn var_local_id(&self, id: hir::HirId, for_guard: ForGuard) -> Local {
342 self.var_indices[&id].local_id(for_guard)
350 fn push(&mut self, bf: BlockFrame) {
353 fn pop(&mut self) -> Option<BlockFrame> {
357 /// Traverses the frames on the `BlockContext`, searching for either
358 /// the first block-tail expression frame with no intervening
361 /// Notably, this skips over `SubExpr` frames; this method is
362 /// meant to be used in the context of understanding the
363 /// relationship of a temp (created within some complicated
364 /// expression) with its containing expression, and whether the
365 /// value of that *containing expression* (not the temp!) is
367 fn currently_in_block_tail(&self) -> Option<BlockTailInfo> {
368 for bf in self.0.iter().rev() {
370 BlockFrame::SubExpr => continue,
371 BlockFrame::Statement { .. } => break,
372 &BlockFrame::TailExpr { tail_result_is_ignored } => {
373 return Some(BlockTailInfo { tail_result_is_ignored });
381 /// Looks at the topmost frame on the BlockContext and reports
382 /// whether its one that would discard a block tail result.
384 /// Unlike `currently_within_ignored_tail_expression`, this does
385 /// *not* skip over `SubExpr` frames: here, we want to know
386 /// whether the block result itself is discarded.
387 fn currently_ignores_tail_results(&self) -> bool {
388 match self.0.last() {
389 // no context: conservatively assume result is read
392 // sub-expression: block result feeds into some computation
393 Some(BlockFrame::SubExpr) => false,
395 // otherwise: use accumulated is_ignored state.
397 BlockFrame::TailExpr { tail_result_is_ignored: ignored }
398 | BlockFrame::Statement { ignores_expr_result: ignored },
406 /// In the usual case, a `HirId` for an identifier maps to at most
407 /// one `Local` declaration.
410 /// The exceptional case is identifiers in a match arm's pattern
411 /// that are referenced in a guard of that match arm. For these,
412 /// we have `2` Locals.
414 /// * `for_arm_body` is the Local used in the arm body (which is
415 /// just like the `One` case above),
417 /// * `ref_for_guard` is the Local used in the arm's guard (which
418 /// is a reference to a temp that is an alias of
420 ForGuard { ref_for_guard: Local, for_arm_body: Local },
424 struct GuardFrameLocal {
428 impl GuardFrameLocal {
429 fn new(id: hir::HirId, _binding_mode: BindingMode) -> Self {
430 GuardFrameLocal { id }
436 /// These are the id's of names that are bound by patterns of the
437 /// arm of *this* guard.
439 /// (Frames higher up the stack will have the id's bound in arms
440 /// further out, such as in a case like:
443 /// P1(id1) if (... (match E2 { P2(id2) if ... => B2 })) => B1,
446 /// here, when building for FIXME.
447 locals: Vec<GuardFrameLocal>,
450 /// `ForGuard` indicates whether we are talking about:
451 /// 1. The variable for use outside of guard expressions, or
452 /// 2. The temp that holds reference to (1.), which is actually what the
453 /// guard expressions see.
454 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
461 fn local_id(&self, for_guard: ForGuard) -> Local {
462 match (self, for_guard) {
463 (&LocalsForNode::One(local_id), ForGuard::OutsideGuard)
465 &LocalsForNode::ForGuard { ref_for_guard: local_id, .. },
466 ForGuard::RefWithinGuard,
468 | (&LocalsForNode::ForGuard { for_arm_body: local_id, .. }, ForGuard::OutsideGuard) => {
472 (&LocalsForNode::One(_), ForGuard::RefWithinGuard) => {
473 bug!("anything with one local should never be within a guard.")
480 basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
483 rustc_index::newtype_index! {
484 struct ScopeId { .. }
487 ///////////////////////////////////////////////////////////////////////////
488 /// The `BlockAnd` "monad" packages up the new basic block along with a
489 /// produced value (sometimes just unit, of course). The `unpack!`
490 /// macro (and methods below) makes working with `BlockAnd` much more
493 #[must_use = "if you don't use one of these results, you're leaving a dangling edge"]
494 struct BlockAnd<T>(BasicBlock, T);
496 trait BlockAndExtension {
497 fn and<T>(self, v: T) -> BlockAnd<T>;
498 fn unit(self) -> BlockAnd<()>;
501 impl BlockAndExtension for BasicBlock {
502 fn and<T>(self, v: T) -> BlockAnd<T> {
506 fn unit(self) -> BlockAnd<()> {
511 /// Update a block pointer and return the value.
512 /// Use it like `let x = unpack!(block = self.foo(block, foo))`.
513 macro_rules! unpack {
514 ($x:ident = $c:expr) => {{
515 let BlockAnd(b, v) = $c;
521 let BlockAnd(b, ()) = $c;
526 fn should_abort_on_panic(tcx: TyCtxt<'_>, fn_def_id: DefId, _abi: Abi) -> bool {
527 // Validate `#[unwind]` syntax regardless of platform-specific panic strategy.
528 let attrs = &tcx.get_attrs(fn_def_id);
529 let unwind_attr = attr::find_unwind_attr(Some(tcx.sess.diagnostic()), attrs);
531 // We never unwind, so it's not relevant to stop an unwind.
532 if tcx.sess.panic_strategy() != PanicStrategy::Unwind {
536 // We cannot add landing pads, so don't add one.
537 if tcx.sess.no_landing_pads() {
541 // This is a special case: some functions have a C abi but are meant to
542 // unwind anyway. Don't stop them.
544 None => false, // FIXME(#58794); should be `!(abi == Abi::Rust || abi == Abi::RustCall)`
545 Some(UnwindAttr::Allowed) => false,
546 Some(UnwindAttr::Aborts) => true,
550 ///////////////////////////////////////////////////////////////////////////
551 /// the main entry point for building MIR for a function
553 struct ArgInfo<'tcx>(
556 Option<&'tcx hir::Param<'tcx>>,
557 Option<ImplicitSelfKind>,
560 fn construct_fn<'a, 'tcx, A>(
567 return_ty_span: Span,
568 body: &'tcx hir::Body<'tcx>,
571 A: Iterator<Item = ArgInfo<'tcx>>,
573 let arguments: Vec<_> = arguments.collect();
576 let tcx_hir = tcx.hir();
577 let span = tcx_hir.span(fn_id);
579 let fn_def_id = tcx_hir.local_def_id(fn_id);
581 let mut builder = Builder::new(
591 let call_site_scope =
592 region::Scope { id: body.value.hir_id.local_id, data: region::ScopeData::CallSite };
594 region::Scope { id: body.value.hir_id.local_id, data: region::ScopeData::Arguments };
595 let mut block = START_BLOCK;
596 let source_info = builder.source_info(span);
597 let call_site_s = (call_site_scope, source_info);
599 block = builder.in_scope(call_site_s, LintLevel::Inherited, |builder| {
600 if should_abort_on_panic(tcx, fn_def_id, abi) {
601 builder.schedule_abort();
604 let arg_scope_s = (arg_scope, source_info);
605 // `return_block` is called when we evaluate a `return` expression, so
606 // we just use `START_BLOCK` here.
608 block = builder.in_breakable_scope(
611 Place::return_place(),
613 builder.in_scope(arg_scope_s, LintLevel::Inherited, |builder| {
614 builder.args_and_body(
625 // Attribute epilogue to function's closing brace
626 let fn_end = span.shrink_to_hi();
627 let source_info = builder.source_info(fn_end);
628 let return_block = builder.return_block();
629 builder.cfg.goto(block, source_info, return_block);
630 builder.cfg.terminate(return_block, source_info, TerminatorKind::Return);
631 // Attribute any unreachable codepaths to the function's closing brace
632 if let Some(unreachable_block) = builder.cached_unreachable_block {
633 builder.cfg.terminate(unreachable_block, source_info, TerminatorKind::Unreachable);
638 assert_eq!(block, builder.return_block());
640 let spread_arg = if abi == Abi::RustCall {
641 // RustCall pseudo-ABI untuples the last argument.
642 Some(Local::new(arguments.len()))
646 debug!("fn_id {:?} has attrs {:?}", fn_def_id, tcx.get_attrs(fn_def_id));
648 let mut body = builder.finish();
649 body.spread_arg = spread_arg;
653 fn construct_const<'a, 'tcx>(
655 body_id: hir::BodyId,
660 let owner_id = tcx.hir().body_owner(body_id);
661 let span = tcx.hir().span(owner_id);
662 let mut builder = Builder::new(hir, span, 0, Safety::Safe, const_ty, const_ty_span, None);
664 let mut block = START_BLOCK;
665 let ast_expr = &tcx.hir().body(body_id).value;
666 let expr = builder.hir.mirror(ast_expr);
667 unpack!(block = builder.into_expr(Place::return_place(), block, expr));
669 let source_info = builder.source_info(span);
670 builder.cfg.terminate(block, source_info, TerminatorKind::Return);
672 // Constants can't `return` so a return block should not be created.
673 assert_eq!(builder.cached_return_block, None);
675 // Constants may be match expressions in which case an unreachable block may
676 // be created, so terminate it properly.
677 if let Some(unreachable_block) = builder.cached_unreachable_block {
678 builder.cfg.terminate(unreachable_block, source_info, TerminatorKind::Unreachable);
684 /// Construct MIR for a item that has had errors in type checking.
686 /// This is required because we may still want to run MIR passes on an item
687 /// with type errors, but normal MIR construction can't handle that in general.
688 fn construct_error<'a, 'tcx>(hir: Cx<'a, 'tcx>, body_id: hir::BodyId) -> Body<'tcx> {
690 let owner_id = tcx.hir().body_owner(body_id);
691 let span = tcx.hir().span(owner_id);
692 let ty = tcx.types.err;
693 let num_params = match hir.body_owner_kind {
694 hir::BodyOwnerKind::Fn => tcx.hir().fn_decl_by_hir_id(owner_id).unwrap().inputs.len(),
695 hir::BodyOwnerKind::Closure => {
696 if tcx.hir().body(body_id).generator_kind().is_some() {
697 // Generators have an implicit `self` parameter *and* a possibly
698 // implicit resume parameter.
701 // The implicit self parameter adds another local in MIR.
702 1 + tcx.hir().fn_decl_by_hir_id(owner_id).unwrap().inputs.len()
705 hir::BodyOwnerKind::Const => 0,
706 hir::BodyOwnerKind::Static(_) => 0,
708 let mut builder = Builder::new(hir, span, num_params, Safety::Safe, ty, span, None);
709 let source_info = builder.source_info(span);
710 // Some MIR passes will expect the number of parameters to match the
711 // function declaration.
712 for _ in 0..num_params {
713 builder.local_decls.push(LocalDecl {
714 mutability: Mutability::Mut,
716 user_ty: UserTypeProjections::none(),
719 local_info: LocalInfo::Other,
723 builder.cfg.terminate(START_BLOCK, source_info, TerminatorKind::Unreachable);
724 let mut body = builder.finish();
725 if tcx.hir().body(body_id).generator_kind.is_some() {
726 body.yield_ty = Some(ty);
731 impl<'a, 'tcx> Builder<'a, 'tcx> {
739 generator_kind: Option<GeneratorKind>,
740 ) -> Builder<'a, 'tcx> {
741 let lint_level = LintLevel::Explicit(hir.root_lint_level);
742 let mut builder = Builder {
744 cfg: CFG { basic_blocks: IndexVec::new() },
748 scopes: Default::default(),
749 block_context: BlockContext::new(),
750 source_scopes: IndexVec::new(),
751 source_scope: OUTERMOST_SOURCE_SCOPE,
752 guard_context: vec![],
753 push_unsafe_count: 0,
754 unpushed_unsafe: safety,
755 local_decls: IndexVec::from_elem_n(
756 LocalDecl::new_return_place(return_ty, return_span),
759 canonical_user_type_annotations: IndexVec::new(),
760 upvar_mutbls: vec![],
761 var_indices: Default::default(),
763 var_debug_info: vec![],
764 cached_resume_block: None,
765 cached_return_block: None,
766 cached_unreachable_block: None,
769 assert_eq!(builder.cfg.start_new_block(), START_BLOCK);
771 builder.new_source_scope(span, lint_level, Some(safety)),
772 OUTERMOST_SOURCE_SCOPE
774 builder.source_scopes[OUTERMOST_SOURCE_SCOPE].parent_scope = None;
779 fn finish(self) -> Body<'tcx> {
780 for (index, block) in self.cfg.basic_blocks.iter().enumerate() {
781 if block.terminator.is_none() {
782 span_bug!(self.fn_span, "no terminator on block {:?}", index);
787 self.cfg.basic_blocks,
790 self.canonical_user_type_annotations,
794 self.hir.control_flow_destroyed(),
801 mut block: BasicBlock,
803 arguments: &[ArgInfo<'tcx>],
804 argument_scope: region::Scope,
805 ast_body: &'tcx hir::Expr<'tcx>,
807 // Allocate locals for the function arguments
808 for &ArgInfo(ty, _, arg_opt, _) in arguments.iter() {
809 let source_info = SourceInfo {
810 scope: OUTERMOST_SOURCE_SCOPE,
811 span: arg_opt.map_or(self.fn_span, |arg| arg.pat.span),
813 let arg_local = self.local_decls.push(LocalDecl {
814 mutability: Mutability::Mut,
816 user_ty: UserTypeProjections::none(),
819 local_info: LocalInfo::Other,
823 // If this is a simple binding pattern, give debuginfo a nice name.
824 if let Some(arg) = arg_opt {
825 if let Some(ident) = arg.pat.simple_ident() {
826 self.var_debug_info.push(VarDebugInfo {
829 place: arg_local.into(),
835 let tcx = self.hir.tcx();
836 let tcx_hir = tcx.hir();
837 let hir_tables = self.hir.tables();
839 // In analyze_closure() in upvar.rs we gathered a list of upvars used by a
840 // closure and we stored in a map called upvar_list in TypeckTables indexed
841 // with the closure's DefId. Here, we run through that vec of UpvarIds for
842 // the given closure and use the necessary information to create upvar
843 // debuginfo and to fill `self.upvar_mutbls`.
844 if let Some(upvars) = hir_tables.upvar_list.get(&fn_def_id) {
845 let closure_env_arg = Local::new(1);
846 let mut closure_env_projs = vec![];
847 let mut closure_ty = self.local_decls[closure_env_arg].ty;
848 if let ty::Ref(_, ty, _) = closure_ty.kind {
849 closure_env_projs.push(ProjectionElem::Deref);
852 let upvar_substs = match closure_ty.kind {
853 ty::Closure(_, substs) => ty::UpvarSubsts::Closure(substs),
854 ty::Generator(_, substs, _) => ty::UpvarSubsts::Generator(substs),
855 _ => span_bug!(self.fn_span, "upvars with non-closure env ty {:?}", closure_ty),
857 let upvar_tys = upvar_substs.upvar_tys();
858 let upvars_with_tys = upvars.iter().zip(upvar_tys);
859 self.upvar_mutbls = upvars_with_tys
861 .map(|(i, ((&var_id, &upvar_id), ty))| {
862 let capture = hir_tables.upvar_capture(upvar_id);
864 let mut mutability = Mutability::Not;
865 let mut name = kw::Invalid;
866 if let Some(Node::Binding(pat)) = tcx_hir.find(var_id) {
867 if let hir::PatKind::Binding(_, _, ident, _) = pat.kind {
869 match hir_tables.extract_binding_mode(tcx.sess, pat.hir_id, pat.span) {
870 Some(ty::BindByValue(hir::Mutability::Mut)) => {
871 mutability = Mutability::Mut;
873 Some(_) => mutability = Mutability::Not,
879 let mut projs = closure_env_projs.clone();
880 projs.push(ProjectionElem::Field(Field::new(i), ty));
882 ty::UpvarCapture::ByValue => {}
883 ty::UpvarCapture::ByRef(..) => {
884 projs.push(ProjectionElem::Deref);
888 self.var_debug_info.push(VarDebugInfo {
890 source_info: SourceInfo {
891 scope: OUTERMOST_SOURCE_SCOPE,
892 span: tcx_hir.span(var_id),
895 local: closure_env_arg,
896 projection: tcx.intern_place_elems(&projs),
905 let mut scope = None;
906 // Bind the argument patterns
907 for (index, arg_info) in arguments.iter().enumerate() {
908 // Function arguments always get the first Local indices after the return place
909 let local = Local::new(index + 1);
910 let place = Place::from(local);
911 let &ArgInfo(_, opt_ty_info, arg_opt, ref self_binding) = arg_info;
913 // Make sure we drop (parts of) the argument even when not matched on.
915 arg_opt.as_ref().map_or(ast_body.span, |arg| arg.pat.span),
921 if let Some(arg) = arg_opt {
922 let pattern = self.hir.pattern_from_hir(&arg.pat);
923 let original_source_scope = self.source_scope;
924 let span = pattern.span;
925 self.set_correct_source_scope_for_arg(arg.hir_id, original_source_scope, span);
926 match *pattern.kind {
927 // Don't introduce extra copies for simple bindings
931 mode: BindingMode::ByValue,
935 self.local_decls[local].mutability = mutability;
936 self.local_decls[local].source_info.scope = self.source_scope;
937 self.local_decls[local].local_info = if let Some(kind) = self_binding {
938 LocalInfo::User(ClearCrossCrate::Set(BindingForm::ImplicitSelf(*kind)))
940 let binding_mode = ty::BindingMode::BindByValue(mutability);
941 LocalInfo::User(ClearCrossCrate::Set(BindingForm::Var(
945 opt_match_place: Some((Some(place), span)),
950 self.var_indices.insert(var, LocalsForNode::One(local));
953 scope = self.declare_bindings(
957 matches::ArmHasGuard(false),
958 Some((Some(&place), span)),
960 unpack!(block = self.place_into_pattern(block, pattern, place, false));
963 self.source_scope = original_source_scope;
967 // Enter the argument pattern bindings source scope, if it exists.
968 if let Some(source_scope) = scope {
969 self.source_scope = source_scope;
972 let body = self.hir.mirror(ast_body);
973 self.into(Place::return_place(), block, body)
976 fn set_correct_source_scope_for_arg(
978 arg_hir_id: hir::HirId,
979 original_source_scope: SourceScope,
982 let tcx = self.hir.tcx();
983 let current_root = tcx.maybe_lint_level_root_bounded(arg_hir_id, self.hir.root_lint_level);
984 let parent_root = tcx.maybe_lint_level_root_bounded(
985 self.source_scopes[original_source_scope]
988 .assert_crate_local()
990 self.hir.root_lint_level,
992 if current_root != parent_root {
994 self.new_source_scope(pattern_span, LintLevel::Explicit(current_root), None);
998 fn get_unit_temp(&mut self) -> Place<'tcx> {
999 match self.unit_temp {
1002 let ty = self.hir.unit_ty();
1003 let fn_span = self.fn_span;
1004 let tmp = self.temp(ty, fn_span);
1005 self.unit_temp = Some(tmp);
1011 fn return_block(&mut self) -> BasicBlock {
1012 match self.cached_return_block {
1015 let rb = self.cfg.start_new_block();
1016 self.cached_return_block = Some(rb);
1023 ///////////////////////////////////////////////////////////////////////////
1024 // Builder methods are broken up into modules, depending on what kind
1025 // of thing is being lowered. Note that they use the `unpack` macro
1026 // above extensively.