2 use crate::build::scope::DropKind;
3 use crate::hair::cx::Cx;
4 use crate::hair::{BindingMode, LintLevel, PatKind};
5 use rustc::middle::lang_items;
6 use rustc::middle::region;
8 use rustc::ty::subst::Subst;
9 use rustc::ty::{self, Ty, TyCtxt};
10 use rustc_attr::{self as attr, UnwindAttr};
12 use rustc_hir::def_id::DefId;
13 use rustc_hir::{GeneratorKind, HirIdMap, Node};
14 use rustc_index::vec::{Idx, IndexVec};
15 use rustc_infer::infer::TyCtxtInferExt;
16 use rustc_span::symbol::kw;
18 use rustc_target::spec::abi::Abi;
19 use rustc_target::spec::PanicStrategy;
24 crate fn mir_built(tcx: TyCtxt<'_>, def_id: DefId) -> &ty::steal::Steal<BodyAndCache<'_>> {
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) -> BodyAndCache<'_> {
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 {
47 hir::TraitItemKind::Fn(hir::FnSig { decl, .. }, hir::TraitFn::Provided(body_id)),
49 }) => (*body_id, decl.output.span()),
50 Node::Item(hir::Item { kind: hir::ItemKind::Static(ty, _, body_id), .. })
51 | Node::Item(hir::Item { kind: hir::ItemKind::Const(ty, body_id), .. })
52 | Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Const(ty, body_id), .. })
53 | Node::TraitItem(hir::TraitItem {
54 kind: hir::TraitItemKind::Const(ty, Some(body_id)),
56 }) => (*body_id, ty.span),
57 Node::AnonConst(hir::AnonConst { body, hir_id, .. }) => (*body, tcx.hir().span(*hir_id)),
59 _ => span_bug!(tcx.hir().span(id), "can't build MIR for {:?}", def_id),
62 tcx.infer_ctxt().enter(|infcx| {
63 let cx = Cx::new(&infcx, id);
64 let body = if cx.tables().tainted_by_errors {
65 build::construct_error(cx, body_id)
66 } else if cx.body_owner_kind.is_fn_or_closure() {
67 // fetch the fully liberated fn signature (that is, all bound
68 // types/lifetimes replaced)
69 let fn_sig = cx.tables().liberated_fn_sigs()[id];
70 let fn_def_id = tcx.hir().local_def_id(id);
72 let safety = match fn_sig.unsafety {
73 hir::Unsafety::Normal => Safety::Safe,
74 hir::Unsafety::Unsafe => Safety::FnUnsafe,
77 let body = tcx.hir().body(body_id);
78 let ty = tcx.type_of(fn_def_id);
79 let mut abi = fn_sig.abi;
80 let implicit_argument = match ty.kind {
82 // HACK(eddyb) Avoid having RustCall on closures,
83 // as it adds unnecessary (and wrong) auto-tupling.
85 vec![ArgInfo(liberated_closure_env_ty(tcx, id, body_id), None, None, None)]
87 ty::Generator(..) => {
88 let gen_ty = tcx.body_tables(body_id).node_type(id);
90 // The resume argument may be missing, in that case we need to provide it here.
91 // It will always be `()` in this case.
92 if body.params.is_empty() {
94 ArgInfo(gen_ty, None, None, None),
95 ArgInfo(tcx.mk_unit(), None, None, None),
98 vec![ArgInfo(gen_ty, None, None, None)]
104 let explicit_arguments = body.params.iter().enumerate().map(|(index, arg)| {
105 let owner_id = tcx.hir().body_owner(body_id);
108 if let Some(ref fn_decl) = tcx.hir().fn_decl_by_hir_id(owner_id) {
109 opt_ty_info = fn_decl.inputs.get(index).map(|ty| ty.span);
110 self_arg = if index == 0 && fn_decl.implicit_self.has_implicit_self() {
111 match fn_decl.implicit_self {
112 hir::ImplicitSelfKind::Imm => Some(ImplicitSelfKind::Imm),
113 hir::ImplicitSelfKind::Mut => Some(ImplicitSelfKind::Mut),
114 hir::ImplicitSelfKind::ImmRef => Some(ImplicitSelfKind::ImmRef),
115 hir::ImplicitSelfKind::MutRef => Some(ImplicitSelfKind::MutRef),
126 // C-variadic fns also have a `VaList` input that's not listed in `fn_sig`
127 // (as it's created inside the body itself, not passed in from outside).
128 let ty = if fn_sig.c_variadic && index == fn_sig.inputs().len() {
130 tcx.require_lang_item(lang_items::VaListTypeLangItem, Some(arg.span));
131 let region = tcx.mk_region(ty::ReScope(region::Scope {
132 id: body.value.hir_id.local_id,
133 data: region::ScopeData::CallSite,
136 tcx.type_of(va_list_did).subst(tcx, &[region.into()])
138 fn_sig.inputs()[index]
141 ArgInfo(ty, opt_ty_info, Some(&arg), self_arg)
144 let arguments = implicit_argument.into_iter().chain(explicit_arguments);
146 let (yield_ty, return_ty) = if body.generator_kind.is_some() {
147 let gen_sig = match ty.kind {
148 ty::Generator(gen_def_id, gen_substs, ..) => {
149 gen_substs.as_generator().sig(gen_def_id, tcx)
151 _ => span_bug!(tcx.hir().span(id), "generator w/o generator type: {:?}", ty),
153 (Some(gen_sig.yield_ty), gen_sig.return_ty)
155 (None, fn_sig.output())
158 let mut mir = build::construct_fn(
168 mir.yield_ty = yield_ty;
171 // Get the revealed type of this const. This is *not* the adjusted
172 // type of its body, which may be a subtype of this type. For
176 // static X: fn(&'static ()) = foo;
178 // The adjusted type of the body of X is `for<'a> fn(&'a ())` which
179 // is not the same as the type of X. We need the type of the return
180 // place to be the type of the constant because NLL typeck will
183 let return_ty = cx.tables().node_type(id);
185 build::construct_const(cx, body_id, return_ty, return_ty_span)
188 lints::check(tcx, &body, def_id);
190 let mut body = BodyAndCache::new(body);
191 body.ensure_predecessors();
196 ///////////////////////////////////////////////////////////////////////////
197 // BuildMir -- walks a crate, looking for fn items and methods to build MIR from
199 fn liberated_closure_env_ty(
201 closure_expr_id: hir::HirId,
202 body_id: hir::BodyId,
204 let closure_ty = tcx.body_tables(body_id).node_type(closure_expr_id);
206 let (closure_def_id, closure_substs) = match closure_ty.kind {
207 ty::Closure(closure_def_id, closure_substs) => (closure_def_id, closure_substs),
208 _ => bug!("closure expr does not have closure type: {:?}", closure_ty),
211 let closure_env_ty = tcx.closure_env_ty(closure_def_id, closure_substs).unwrap();
212 tcx.liberate_late_bound_regions(closure_def_id, &closure_env_ty)
215 #[derive(Debug, PartialEq, Eq)]
217 /// Evaluation is currently within a statement.
219 /// Examples include:
221 /// 2. `let _ = EXPR;`
222 /// 3. `let x = EXPR;`
224 /// If true, then statement discards result from evaluating
225 /// the expression (such as examples 1 and 2 above).
226 ignores_expr_result: bool,
229 /// Evaluation is currently within the tail expression of a block.
231 /// Example: `{ STMT_1; STMT_2; EXPR }`
233 /// If true, then the surrounding context of the block ignores
234 /// the result of evaluating the block's tail expression.
236 /// Example: `let _ = { STMT_1; EXPR };`
237 tail_result_is_ignored: bool,
240 /// Generic mark meaning that the block occurred as a subexpression
241 /// where the result might be used.
243 /// Examples: `foo(EXPR)`, `match EXPR { ... }`
248 fn is_tail_expr(&self) -> bool {
250 BlockFrame::TailExpr { .. } => true,
252 BlockFrame::Statement { .. } | BlockFrame::SubExpr => false,
255 fn is_statement(&self) -> bool {
257 BlockFrame::Statement { .. } => true,
259 BlockFrame::TailExpr { .. } | BlockFrame::SubExpr => false,
265 struct BlockContext(Vec<BlockFrame>);
267 struct Builder<'a, 'tcx> {
273 generator_kind: Option<GeneratorKind>,
275 /// The current set of scopes, updated as we traverse;
276 /// see the `scope` module for more details.
277 scopes: scope::Scopes<'tcx>,
279 /// The block-context: each time we build the code within an hair::Block,
280 /// we push a frame here tracking whether we are building a statement or
281 /// if we are pushing the tail expression of the block. This is used to
282 /// embed information in generated temps about whether they were created
283 /// for a block tail expression or not.
285 /// It would be great if we could fold this into `self.scopes`
286 /// somehow, but right now I think that is very tightly tied to
287 /// the code generation in ways that we cannot (or should not)
288 /// start just throwing new entries onto that vector in order to
289 /// distinguish the context of EXPR1 from the context of EXPR2 in
290 /// `{ STMTS; EXPR1 } + EXPR2`.
291 block_context: BlockContext,
293 /// The current unsafe block in scope, even if it is hidden by
294 /// a `PushUnsafeBlock`.
295 unpushed_unsafe: Safety,
297 /// The number of `push_unsafe_block` levels in scope.
298 push_unsafe_count: usize,
300 /// The vector of all scopes that we have created thus far;
301 /// we track this for debuginfo later.
302 source_scopes: IndexVec<SourceScope, SourceScopeData>,
303 source_scope: SourceScope,
305 /// The guard-context: each time we build the guard expression for
306 /// a match arm, we push onto this stack, and then pop when we
307 /// finish building it.
308 guard_context: Vec<GuardFrame>,
310 /// Maps `HirId`s of variable bindings to the `Local`s created for them.
311 /// (A match binding can have two locals; the 2nd is for the arm's guard.)
312 var_indices: HirIdMap<LocalsForNode>,
313 local_decls: IndexVec<Local, LocalDecl<'tcx>>,
314 canonical_user_type_annotations: ty::CanonicalUserTypeAnnotations<'tcx>,
315 upvar_mutbls: Vec<Mutability>,
316 unit_temp: Option<Place<'tcx>>,
318 var_debug_info: Vec<VarDebugInfo<'tcx>>,
320 /// Cached block with the `RESUME` terminator; this is created
321 /// when first set of cleanups are built.
322 cached_resume_block: Option<BasicBlock>,
323 /// Cached block with the `RETURN` terminator.
324 cached_return_block: Option<BasicBlock>,
325 /// Cached block with the `UNREACHABLE` terminator.
326 cached_unreachable_block: Option<BasicBlock>,
329 impl<'a, 'tcx> Builder<'a, 'tcx> {
330 fn is_bound_var_in_guard(&self, id: hir::HirId) -> bool {
331 self.guard_context.iter().any(|frame| frame.locals.iter().any(|local| local.id == id))
334 fn var_local_id(&self, id: hir::HirId, for_guard: ForGuard) -> Local {
335 self.var_indices[&id].local_id(for_guard)
343 fn push(&mut self, bf: BlockFrame) {
346 fn pop(&mut self) -> Option<BlockFrame> {
350 /// Traverses the frames on the `BlockContext`, searching for either
351 /// the first block-tail expression frame with no intervening
354 /// Notably, this skips over `SubExpr` frames; this method is
355 /// meant to be used in the context of understanding the
356 /// relationship of a temp (created within some complicated
357 /// expression) with its containing expression, and whether the
358 /// value of that *containing expression* (not the temp!) is
360 fn currently_in_block_tail(&self) -> Option<BlockTailInfo> {
361 for bf in self.0.iter().rev() {
363 BlockFrame::SubExpr => continue,
364 BlockFrame::Statement { .. } => break,
365 &BlockFrame::TailExpr { tail_result_is_ignored } => {
366 return Some(BlockTailInfo { tail_result_is_ignored });
374 /// Looks at the topmost frame on the BlockContext and reports
375 /// whether its one that would discard a block tail result.
377 /// Unlike `currently_within_ignored_tail_expression`, this does
378 /// *not* skip over `SubExpr` frames: here, we want to know
379 /// whether the block result itself is discarded.
380 fn currently_ignores_tail_results(&self) -> bool {
381 match self.0.last() {
382 // no context: conservatively assume result is read
385 // sub-expression: block result feeds into some computation
386 Some(BlockFrame::SubExpr) => false,
388 // otherwise: use accumulated is_ignored state.
389 Some(BlockFrame::TailExpr { tail_result_is_ignored: ignored })
390 | Some(BlockFrame::Statement { ignores_expr_result: ignored }) => *ignored,
397 /// In the usual case, a `HirId` for an identifier maps to at most
398 /// one `Local` declaration.
401 /// The exceptional case is identifiers in a match arm's pattern
402 /// that are referenced in a guard of that match arm. For these,
403 /// we have `2` Locals.
405 /// * `for_arm_body` is the Local used in the arm body (which is
406 /// just like the `One` case above),
408 /// * `ref_for_guard` is the Local used in the arm's guard (which
409 /// is a reference to a temp that is an alias of
411 ForGuard { ref_for_guard: Local, for_arm_body: Local },
415 struct GuardFrameLocal {
419 impl GuardFrameLocal {
420 fn new(id: hir::HirId, _binding_mode: BindingMode) -> Self {
421 GuardFrameLocal { id }
427 /// These are the id's of names that are bound by patterns of the
428 /// arm of *this* guard.
430 /// (Frames higher up the stack will have the id's bound in arms
431 /// further out, such as in a case like:
434 /// P1(id1) if (... (match E2 { P2(id2) if ... => B2 })) => B1,
437 /// here, when building for FIXME.
438 locals: Vec<GuardFrameLocal>,
441 /// `ForGuard` indicates whether we are talking about:
442 /// 1. The variable for use outside of guard expressions, or
443 /// 2. The temp that holds reference to (1.), which is actually what the
444 /// guard expressions see.
445 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
452 fn local_id(&self, for_guard: ForGuard) -> Local {
453 match (self, for_guard) {
454 (&LocalsForNode::One(local_id), ForGuard::OutsideGuard)
456 &LocalsForNode::ForGuard { ref_for_guard: local_id, .. },
457 ForGuard::RefWithinGuard,
459 | (&LocalsForNode::ForGuard { for_arm_body: local_id, .. }, ForGuard::OutsideGuard) => {
463 (&LocalsForNode::One(_), ForGuard::RefWithinGuard) => {
464 bug!("anything with one local should never be within a guard.")
471 basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
474 rustc_index::newtype_index! {
475 struct ScopeId { .. }
478 ///////////////////////////////////////////////////////////////////////////
479 /// The `BlockAnd` "monad" packages up the new basic block along with a
480 /// produced value (sometimes just unit, of course). The `unpack!`
481 /// macro (and methods below) makes working with `BlockAnd` much more
484 #[must_use = "if you don't use one of these results, you're leaving a dangling edge"]
485 struct BlockAnd<T>(BasicBlock, T);
487 trait BlockAndExtension {
488 fn and<T>(self, v: T) -> BlockAnd<T>;
489 fn unit(self) -> BlockAnd<()>;
492 impl BlockAndExtension for BasicBlock {
493 fn and<T>(self, v: T) -> BlockAnd<T> {
497 fn unit(self) -> BlockAnd<()> {
502 /// Update a block pointer and return the value.
503 /// Use it like `let x = unpack!(block = self.foo(block, foo))`.
504 macro_rules! unpack {
505 ($x:ident = $c:expr) => {{
506 let BlockAnd(b, v) = $c;
512 let BlockAnd(b, ()) = $c;
517 fn should_abort_on_panic(tcx: TyCtxt<'_>, fn_def_id: DefId, _abi: Abi) -> bool {
518 // Validate `#[unwind]` syntax regardless of platform-specific panic strategy.
519 let attrs = &tcx.get_attrs(fn_def_id);
520 let unwind_attr = attr::find_unwind_attr(Some(tcx.sess.diagnostic()), attrs);
522 // We never unwind, so it's not relevant to stop an unwind.
523 if tcx.sess.panic_strategy() != PanicStrategy::Unwind {
527 // We cannot add landing pads, so don't add one.
528 if tcx.sess.no_landing_pads() {
532 // This is a special case: some functions have a C abi but are meant to
533 // unwind anyway. Don't stop them.
535 None => false, // FIXME(#58794); should be `!(abi == Abi::Rust || abi == Abi::RustCall)`
536 Some(UnwindAttr::Allowed) => false,
537 Some(UnwindAttr::Aborts) => true,
541 ///////////////////////////////////////////////////////////////////////////
542 /// the main entry point for building MIR for a function
544 struct ArgInfo<'tcx>(
547 Option<&'tcx hir::Param<'tcx>>,
548 Option<ImplicitSelfKind>,
551 fn construct_fn<'a, 'tcx, A>(
558 return_ty_span: Span,
559 body: &'tcx hir::Body<'tcx>,
562 A: Iterator<Item = ArgInfo<'tcx>>,
564 let arguments: Vec<_> = arguments.collect();
567 let tcx_hir = tcx.hir();
568 let span = tcx_hir.span(fn_id);
570 let fn_def_id = tcx_hir.local_def_id(fn_id);
572 let mut builder = Builder::new(
582 let call_site_scope =
583 region::Scope { id: body.value.hir_id.local_id, data: region::ScopeData::CallSite };
585 region::Scope { id: body.value.hir_id.local_id, data: region::ScopeData::Arguments };
586 let mut block = START_BLOCK;
587 let source_info = builder.source_info(span);
588 let call_site_s = (call_site_scope, source_info);
590 block = builder.in_scope(call_site_s, LintLevel::Inherited, |builder| {
591 if should_abort_on_panic(tcx, fn_def_id, abi) {
592 builder.schedule_abort();
595 let arg_scope_s = (arg_scope, source_info);
596 // `return_block` is called when we evaluate a `return` expression, so
597 // we just use `START_BLOCK` here.
599 block = builder.in_breakable_scope(
602 Place::return_place(),
604 builder.in_scope(arg_scope_s, LintLevel::Inherited, |builder| {
605 builder.args_and_body(
616 // Attribute epilogue to function's closing brace
617 let fn_end = span.shrink_to_hi();
618 let source_info = builder.source_info(fn_end);
619 let return_block = builder.return_block();
620 builder.cfg.goto(block, source_info, return_block);
621 builder.cfg.terminate(return_block, source_info, TerminatorKind::Return);
622 // Attribute any unreachable codepaths to the function's closing brace
623 if let Some(unreachable_block) = builder.cached_unreachable_block {
624 builder.cfg.terminate(unreachable_block, source_info, TerminatorKind::Unreachable);
629 assert_eq!(block, builder.return_block());
631 let mut spread_arg = None;
632 if abi == Abi::RustCall {
633 // RustCall pseudo-ABI untuples the last argument.
634 spread_arg = Some(Local::new(arguments.len()));
636 debug!("fn_id {:?} has attrs {:?}", fn_def_id, tcx.get_attrs(fn_def_id));
638 let mut body = builder.finish();
639 body.spread_arg = spread_arg;
643 fn construct_const<'a, 'tcx>(
645 body_id: hir::BodyId,
650 let owner_id = tcx.hir().body_owner(body_id);
651 let span = tcx.hir().span(owner_id);
652 let mut builder = Builder::new(hir, span, 0, Safety::Safe, const_ty, const_ty_span, None);
654 let mut block = START_BLOCK;
655 let ast_expr = &tcx.hir().body(body_id).value;
656 let expr = builder.hir.mirror(ast_expr);
657 unpack!(block = builder.into_expr(&Place::return_place(), block, expr));
659 let source_info = builder.source_info(span);
660 builder.cfg.terminate(block, source_info, TerminatorKind::Return);
662 // Constants can't `return` so a return block should not be created.
663 assert_eq!(builder.cached_return_block, None);
665 // Constants may be match expressions in which case an unreachable block may
666 // be created, so terminate it properly.
667 if let Some(unreachable_block) = builder.cached_unreachable_block {
668 builder.cfg.terminate(unreachable_block, source_info, TerminatorKind::Unreachable);
674 /// Construct MIR for a item that has had errors in type checking.
676 /// This is required because we may still want to run MIR passes on an item
677 /// with type errors, but normal MIR construction can't handle that in general.
678 fn construct_error<'a, 'tcx>(hir: Cx<'a, 'tcx>, body_id: hir::BodyId) -> Body<'tcx> {
680 let owner_id = tcx.hir().body_owner(body_id);
681 let span = tcx.hir().span(owner_id);
682 let ty = tcx.types.err;
683 let num_params = match hir.body_owner_kind {
684 hir::BodyOwnerKind::Fn => tcx.hir().fn_decl_by_hir_id(owner_id).unwrap().inputs.len(),
685 hir::BodyOwnerKind::Closure => {
686 if tcx.hir().body(body_id).generator_kind().is_some() {
687 // Generators have an implicit `self` parameter *and* a possibly
688 // implicit resume parameter.
691 // The implicit self parameter adds another local in MIR.
692 1 + tcx.hir().fn_decl_by_hir_id(owner_id).unwrap().inputs.len()
695 hir::BodyOwnerKind::Const => 0,
696 hir::BodyOwnerKind::Static(_) => 0,
698 let mut builder = Builder::new(hir, span, num_params, Safety::Safe, ty, span, None);
699 let source_info = builder.source_info(span);
700 // Some MIR passes will expect the number of parameters to match the
701 // function declaration.
702 for _ in 0..num_params {
703 builder.local_decls.push(LocalDecl {
704 mutability: Mutability::Mut,
706 user_ty: UserTypeProjections::none(),
709 local_info: LocalInfo::Other,
713 builder.cfg.terminate(START_BLOCK, source_info, TerminatorKind::Unreachable);
714 let mut body = builder.finish();
715 if tcx.hir().body(body_id).generator_kind.is_some() {
716 body.yield_ty = Some(ty);
721 impl<'a, 'tcx> Builder<'a, 'tcx> {
729 generator_kind: Option<GeneratorKind>,
730 ) -> Builder<'a, 'tcx> {
731 let lint_level = LintLevel::Explicit(hir.root_lint_level);
732 let mut builder = Builder {
734 cfg: CFG { basic_blocks: IndexVec::new() },
738 scopes: Default::default(),
739 block_context: BlockContext::new(),
740 source_scopes: IndexVec::new(),
741 source_scope: OUTERMOST_SOURCE_SCOPE,
742 guard_context: vec![],
743 push_unsafe_count: 0,
744 unpushed_unsafe: safety,
745 local_decls: IndexVec::from_elem_n(
746 LocalDecl::new_return_place(return_ty, return_span),
749 canonical_user_type_annotations: IndexVec::new(),
750 upvar_mutbls: vec![],
751 var_indices: Default::default(),
753 var_debug_info: vec![],
754 cached_resume_block: None,
755 cached_return_block: None,
756 cached_unreachable_block: None,
759 assert_eq!(builder.cfg.start_new_block(), START_BLOCK);
761 builder.new_source_scope(span, lint_level, Some(safety)),
762 OUTERMOST_SOURCE_SCOPE
764 builder.source_scopes[OUTERMOST_SOURCE_SCOPE].parent_scope = None;
769 fn finish(self) -> Body<'tcx> {
770 for (index, block) in self.cfg.basic_blocks.iter().enumerate() {
771 if block.terminator.is_none() {
772 span_bug!(self.fn_span, "no terminator on block {:?}", index);
777 self.cfg.basic_blocks,
780 self.canonical_user_type_annotations,
784 self.hir.control_flow_destroyed(),
791 mut block: BasicBlock,
793 arguments: &[ArgInfo<'tcx>],
794 argument_scope: region::Scope,
795 ast_body: &'tcx hir::Expr<'tcx>,
797 // Allocate locals for the function arguments
798 for &ArgInfo(ty, _, arg_opt, _) in arguments.iter() {
799 let source_info = SourceInfo {
800 scope: OUTERMOST_SOURCE_SCOPE,
801 span: arg_opt.map_or(self.fn_span, |arg| arg.pat.span),
803 let arg_local = self.local_decls.push(LocalDecl {
804 mutability: Mutability::Mut,
806 user_ty: UserTypeProjections::none(),
809 local_info: LocalInfo::Other,
813 // If this is a simple binding pattern, give debuginfo a nice name.
814 if let Some(arg) = arg_opt {
815 if let Some(ident) = arg.pat.simple_ident() {
816 self.var_debug_info.push(VarDebugInfo {
819 place: arg_local.into(),
825 let tcx = self.hir.tcx();
826 let tcx_hir = tcx.hir();
827 let hir_tables = self.hir.tables();
829 // In analyze_closure() in upvar.rs we gathered a list of upvars used by a
830 // closure and we stored in a map called upvar_list in TypeckTables indexed
831 // with the closure's DefId. Here, we run through that vec of UpvarIds for
832 // the given closure and use the necessary information to create upvar
833 // debuginfo and to fill `self.upvar_mutbls`.
834 if let Some(upvars) = hir_tables.upvar_list.get(&fn_def_id) {
835 let closure_env_arg = Local::new(1);
836 let mut closure_env_projs = vec![];
837 let mut closure_ty = self.local_decls[closure_env_arg].ty;
838 if let ty::Ref(_, ty, _) = closure_ty.kind {
839 closure_env_projs.push(ProjectionElem::Deref);
842 let (def_id, upvar_substs) = match closure_ty.kind {
843 ty::Closure(def_id, substs) => (def_id, ty::UpvarSubsts::Closure(substs)),
844 ty::Generator(def_id, substs, _) => (def_id, ty::UpvarSubsts::Generator(substs)),
845 _ => span_bug!(self.fn_span, "upvars with non-closure env ty {:?}", closure_ty),
847 let upvar_tys = upvar_substs.upvar_tys(def_id, tcx);
848 let upvars_with_tys = upvars.iter().zip(upvar_tys);
849 self.upvar_mutbls = upvars_with_tys
851 .map(|(i, ((&var_id, &upvar_id), ty))| {
852 let capture = hir_tables.upvar_capture(upvar_id);
854 let mut mutability = Mutability::Not;
855 let mut name = kw::Invalid;
856 if let Some(Node::Binding(pat)) = tcx_hir.find(var_id) {
857 if let hir::PatKind::Binding(_, _, ident, _) = pat.kind {
859 match hir_tables.extract_binding_mode(tcx.sess, pat.hir_id, pat.span) {
860 Some(ty::BindByValue(hir::Mutability::Mut)) => {
861 mutability = Mutability::Mut;
863 Some(_) => mutability = Mutability::Not,
869 let mut projs = closure_env_projs.clone();
870 projs.push(ProjectionElem::Field(Field::new(i), ty));
872 ty::UpvarCapture::ByValue => {}
873 ty::UpvarCapture::ByRef(..) => {
874 projs.push(ProjectionElem::Deref);
878 self.var_debug_info.push(VarDebugInfo {
880 source_info: SourceInfo {
881 scope: OUTERMOST_SOURCE_SCOPE,
882 span: tcx_hir.span(var_id),
885 local: closure_env_arg,
886 projection: tcx.intern_place_elems(&projs),
895 let mut scope = None;
896 // Bind the argument patterns
897 for (index, arg_info) in arguments.iter().enumerate() {
898 // Function arguments always get the first Local indices after the return place
899 let local = Local::new(index + 1);
900 let place = Place::from(local);
901 let &ArgInfo(_, opt_ty_info, arg_opt, ref self_binding) = arg_info;
903 // Make sure we drop (parts of) the argument even when not matched on.
905 arg_opt.as_ref().map_or(ast_body.span, |arg| arg.pat.span),
911 if let Some(arg) = arg_opt {
912 let pattern = self.hir.pattern_from_hir(&arg.pat);
913 let original_source_scope = self.source_scope;
914 let span = pattern.span;
915 self.set_correct_source_scope_for_arg(arg.hir_id, original_source_scope, span);
916 match *pattern.kind {
917 // Don't introduce extra copies for simple bindings
921 mode: BindingMode::ByValue,
925 self.local_decls[local].mutability = mutability;
926 self.local_decls[local].source_info.scope = self.source_scope;
927 self.local_decls[local].local_info = if let Some(kind) = self_binding {
928 LocalInfo::User(ClearCrossCrate::Set(BindingForm::ImplicitSelf(*kind)))
930 let binding_mode = ty::BindingMode::BindByValue(mutability);
931 LocalInfo::User(ClearCrossCrate::Set(BindingForm::Var(
935 opt_match_place: Some((Some(place), span)),
940 self.var_indices.insert(var, LocalsForNode::One(local));
943 scope = self.declare_bindings(
947 matches::ArmHasGuard(false),
948 Some((Some(&place), span)),
950 unpack!(block = self.place_into_pattern(block, pattern, place, false));
953 self.source_scope = original_source_scope;
957 // Enter the argument pattern bindings source scope, if it exists.
958 if let Some(source_scope) = scope {
959 self.source_scope = source_scope;
962 let body = self.hir.mirror(ast_body);
963 self.into(&Place::return_place(), block, body)
966 fn set_correct_source_scope_for_arg(
968 arg_hir_id: hir::HirId,
969 original_source_scope: SourceScope,
972 let tcx = self.hir.tcx();
973 let current_root = tcx.maybe_lint_level_root_bounded(arg_hir_id, self.hir.root_lint_level);
974 let parent_root = tcx.maybe_lint_level_root_bounded(
975 self.source_scopes[original_source_scope]
978 .assert_crate_local()
980 self.hir.root_lint_level,
982 if current_root != parent_root {
984 self.new_source_scope(pattern_span, LintLevel::Explicit(current_root), None);
988 fn get_unit_temp(&mut self) -> Place<'tcx> {
989 match self.unit_temp {
992 let ty = self.hir.unit_ty();
993 let fn_span = self.fn_span;
994 let tmp = self.temp(ty, fn_span);
995 self.unit_temp = Some(tmp);
1001 fn return_block(&mut self) -> BasicBlock {
1002 match self.cached_return_block {
1005 let rb = self.cfg.start_new_block();
1006 self.cached_return_block = Some(rb);
1013 ///////////////////////////////////////////////////////////////////////////
1014 // Builder methods are broken up into modules, depending on what kind
1015 // of thing is being lowered. Note that they use the `unpack` macro
1016 // above extensively.