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;
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::codegen_fn_attrs::CodegenFnAttrFlags;
14 use rustc_middle::middle::region;
15 use rustc_middle::mir::*;
16 use rustc_middle::ty::subst::Subst;
17 use rustc_middle::ty::{self, Ty, TyCtxt, TypeFoldable};
18 use rustc_span::symbol::kw;
20 use rustc_target::spec::abi::Abi;
21 use rustc_target::spec::PanicStrategy;
25 crate fn mir_built<'tcx>(
27 def: ty::WithOptConstParam<LocalDefId>,
28 ) -> &'tcx ty::steal::Steal<Body<'tcx>> {
29 if let Some(def) = def.try_upgrade(tcx) {
30 return tcx.mir_built(def);
33 tcx.alloc_steal_mir(mir_build(tcx, def))
36 /// Construct the MIR for a given `DefId`.
37 fn mir_build(tcx: TyCtxt<'_>, def: ty::WithOptConstParam<LocalDefId>) -> Body<'_> {
38 let id = tcx.hir().as_local_hir_id(def.did);
40 // Figure out what primary body this item has.
41 let (body_id, return_ty_span) = match tcx.hir().get(id) {
42 Node::Expr(hir::Expr { kind: hir::ExprKind::Closure(_, decl, body_id, _, _), .. }) => {
43 (*body_id, decl.output.span())
45 Node::Item(hir::Item {
46 kind: hir::ItemKind::Fn(hir::FnSig { decl, .. }, _, body_id),
49 | Node::ImplItem(hir::ImplItem {
50 kind: hir::ImplItemKind::Fn(hir::FnSig { decl, .. }, body_id),
53 | Node::TraitItem(hir::TraitItem {
54 kind: hir::TraitItemKind::Fn(hir::FnSig { decl, .. }, hir::TraitFn::Provided(body_id)),
56 }) => (*body_id, decl.output.span()),
57 Node::Item(hir::Item {
58 kind: hir::ItemKind::Static(ty, _, body_id) | hir::ItemKind::Const(ty, body_id),
61 | Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Const(ty, body_id), .. })
62 | Node::TraitItem(hir::TraitItem {
63 kind: hir::TraitItemKind::Const(ty, Some(body_id)),
65 }) => (*body_id, ty.span),
66 Node::AnonConst(hir::AnonConst { body, hir_id, .. }) => (*body, tcx.hir().span(*hir_id)),
68 _ => span_bug!(tcx.hir().span(id), "can't build MIR for {:?}", def.did),
71 tcx.infer_ctxt().enter(|infcx| {
72 let cx = Cx::new(&infcx, def, id);
73 let body = if let Some(ErrorReported) = cx.typeck_results().tainted_by_errors {
74 build::construct_error(cx, body_id)
75 } else if cx.body_owner_kind.is_fn_or_closure() {
76 // fetch the fully liberated fn signature (that is, all bound
77 // types/lifetimes replaced)
78 let fn_sig = cx.typeck_results().liberated_fn_sigs()[id];
79 let fn_def_id = tcx.hir().local_def_id(id);
81 let safety = match fn_sig.unsafety {
82 hir::Unsafety::Normal => Safety::Safe,
83 hir::Unsafety::Unsafe => Safety::FnUnsafe,
86 let body = tcx.hir().body(body_id);
87 let ty = tcx.type_of(fn_def_id);
88 let mut abi = fn_sig.abi;
89 let implicit_argument = match ty.kind {
91 // HACK(eddyb) Avoid having RustCall on closures,
92 // as it adds unnecessary (and wrong) auto-tupling.
94 vec![ArgInfo(liberated_closure_env_ty(tcx, id, body_id), None, None, None)]
96 ty::Generator(..) => {
97 let gen_ty = tcx.typeck_body(body_id).node_type(id);
99 // The resume argument may be missing, in that case we need to provide it here.
100 // It will always be `()` in this case.
101 if body.params.is_empty() {
103 ArgInfo(gen_ty, None, None, None),
104 ArgInfo(tcx.mk_unit(), None, None, None),
107 vec![ArgInfo(gen_ty, None, None, None)]
113 let explicit_arguments = body.params.iter().enumerate().map(|(index, arg)| {
114 let owner_id = tcx.hir().body_owner(body_id);
117 if let Some(ref fn_decl) = tcx.hir().fn_decl_by_hir_id(owner_id) {
118 opt_ty_info = fn_decl.inputs.get(index).map(|ty| ty.span);
119 self_arg = if index == 0 && fn_decl.implicit_self.has_implicit_self() {
120 match fn_decl.implicit_self {
121 hir::ImplicitSelfKind::Imm => Some(ImplicitSelfKind::Imm),
122 hir::ImplicitSelfKind::Mut => Some(ImplicitSelfKind::Mut),
123 hir::ImplicitSelfKind::ImmRef => Some(ImplicitSelfKind::ImmRef),
124 hir::ImplicitSelfKind::MutRef => Some(ImplicitSelfKind::MutRef),
135 // C-variadic fns also have a `VaList` input that's not listed in `fn_sig`
136 // (as it's created inside the body itself, not passed in from outside).
137 let ty = if fn_sig.c_variadic && index == fn_sig.inputs().len() {
139 tcx.require_lang_item(lang_items::VaListTypeLangItem, Some(arg.span));
141 tcx.type_of(va_list_did).subst(tcx, &[tcx.lifetimes.re_erased.into()])
143 fn_sig.inputs()[index]
146 ArgInfo(ty, opt_ty_info, Some(&arg), self_arg)
149 let arguments = implicit_argument.into_iter().chain(explicit_arguments);
151 let (yield_ty, return_ty) = if body.generator_kind.is_some() {
152 let gen_ty = tcx.typeck_body(body_id).node_type(id);
153 let gen_sig = match gen_ty.kind {
154 ty::Generator(_, gen_substs, ..) => gen_substs.as_generator().sig(),
155 _ => span_bug!(tcx.hir().span(id), "generator w/o generator type: {:?}", ty),
157 (Some(gen_sig.yield_ty), gen_sig.return_ty)
159 (None, fn_sig.output())
162 let mut mir = build::construct_fn(
172 mir.yield_ty = yield_ty;
175 // Get the revealed type of this const. This is *not* the adjusted
176 // type of its body, which may be a subtype of this type. For
180 // static X: fn(&'static ()) = foo;
182 // The adjusted type of the body of X is `for<'a> fn(&'a ())` which
183 // is not the same as the type of X. We need the type of the return
184 // place to be the type of the constant because NLL typeck will
187 let return_ty = cx.typeck_results().node_type(id);
189 build::construct_const(cx, body_id, return_ty, return_ty_span)
192 lints::check(tcx, &body, def.did);
194 // The borrow checker will replace all the regions here with its own
195 // inference variables. There's no point having non-erased regions here.
196 // The exception is `body.user_type_annotations`, which is used unmodified
197 // by borrow checking.
199 !(body.local_decls.has_free_regions()
200 || body.basic_blocks().has_free_regions()
201 || body.var_debug_info.has_free_regions()
202 || body.yield_ty.has_free_regions()),
203 "Unexpected free regions in MIR: {:?}",
211 ///////////////////////////////////////////////////////////////////////////
212 // BuildMir -- walks a crate, looking for fn items and methods to build MIR from
214 fn liberated_closure_env_ty(
216 closure_expr_id: hir::HirId,
217 body_id: hir::BodyId,
219 let closure_ty = tcx.typeck_body(body_id).node_type(closure_expr_id);
221 let (closure_def_id, closure_substs) = match closure_ty.kind {
222 ty::Closure(closure_def_id, closure_substs) => (closure_def_id, closure_substs),
223 _ => bug!("closure expr does not have closure type: {:?}", closure_ty),
226 let closure_env_ty = tcx.closure_env_ty(closure_def_id, closure_substs).unwrap();
227 tcx.erase_late_bound_regions(&closure_env_ty)
230 #[derive(Debug, PartialEq, Eq)]
232 /// Evaluation is currently within a statement.
234 /// Examples include:
236 /// 2. `let _ = EXPR;`
237 /// 3. `let x = EXPR;`
239 /// If true, then statement discards result from evaluating
240 /// the expression (such as examples 1 and 2 above).
241 ignores_expr_result: bool,
244 /// Evaluation is currently within the tail expression of a block.
246 /// Example: `{ STMT_1; STMT_2; EXPR }`
248 /// If true, then the surrounding context of the block ignores
249 /// the result of evaluating the block's tail expression.
251 /// Example: `let _ = { STMT_1; EXPR };`
252 tail_result_is_ignored: bool,
254 /// `Span` of the tail expression.
258 /// Generic mark meaning that the block occurred as a subexpression
259 /// where the result might be used.
261 /// Examples: `foo(EXPR)`, `match EXPR { ... }`
266 fn is_tail_expr(&self) -> bool {
268 BlockFrame::TailExpr { .. } => true,
270 BlockFrame::Statement { .. } | BlockFrame::SubExpr => false,
273 fn is_statement(&self) -> bool {
275 BlockFrame::Statement { .. } => true,
277 BlockFrame::TailExpr { .. } | BlockFrame::SubExpr => false,
283 struct BlockContext(Vec<BlockFrame>);
285 struct Builder<'a, 'tcx> {
291 generator_kind: Option<GeneratorKind>,
293 /// The current set of scopes, updated as we traverse;
294 /// see the `scope` module for more details.
295 scopes: scope::Scopes<'tcx>,
297 /// The block-context: each time we build the code within an thir::Block,
298 /// we push a frame here tracking whether we are building a statement or
299 /// if we are pushing the tail expression of the block. This is used to
300 /// embed information in generated temps about whether they were created
301 /// for a block tail expression or not.
303 /// It would be great if we could fold this into `self.scopes`
304 /// somehow, but right now I think that is very tightly tied to
305 /// the code generation in ways that we cannot (or should not)
306 /// start just throwing new entries onto that vector in order to
307 /// distinguish the context of EXPR1 from the context of EXPR2 in
308 /// `{ STMTS; EXPR1 } + EXPR2`.
309 block_context: BlockContext,
311 /// The current unsafe block in scope, even if it is hidden by
312 /// a `PushUnsafeBlock`.
313 unpushed_unsafe: Safety,
315 /// The number of `push_unsafe_block` levels in scope.
316 push_unsafe_count: usize,
318 /// The vector of all scopes that we have created thus far;
319 /// we track this for debuginfo later.
320 source_scopes: IndexVec<SourceScope, SourceScopeData>,
321 source_scope: SourceScope,
323 /// The guard-context: each time we build the guard expression for
324 /// a match arm, we push onto this stack, and then pop when we
325 /// finish building it.
326 guard_context: Vec<GuardFrame>,
328 /// Maps `HirId`s of variable bindings to the `Local`s created for them.
329 /// (A match binding can have two locals; the 2nd is for the arm's guard.)
330 var_indices: HirIdMap<LocalsForNode>,
331 local_decls: IndexVec<Local, LocalDecl<'tcx>>,
332 canonical_user_type_annotations: ty::CanonicalUserTypeAnnotations<'tcx>,
333 upvar_mutbls: Vec<Mutability>,
334 unit_temp: Option<Place<'tcx>>,
336 var_debug_info: Vec<VarDebugInfo<'tcx>>,
338 /// Cached block with the `RESUME` terminator; this is created
339 /// when first set of cleanups are built.
340 cached_resume_block: Option<BasicBlock>,
341 /// Cached block with the `RETURN` terminator.
342 cached_return_block: Option<BasicBlock>,
343 /// Cached block with the `UNREACHABLE` terminator.
344 cached_unreachable_block: Option<BasicBlock>,
347 impl<'a, 'tcx> Builder<'a, 'tcx> {
348 fn is_bound_var_in_guard(&self, id: hir::HirId) -> bool {
349 self.guard_context.iter().any(|frame| frame.locals.iter().any(|local| local.id == id))
352 fn var_local_id(&self, id: hir::HirId, for_guard: ForGuard) -> Local {
353 self.var_indices[&id].local_id(for_guard)
361 fn push(&mut self, bf: BlockFrame) {
364 fn pop(&mut self) -> Option<BlockFrame> {
368 /// Traverses the frames on the `BlockContext`, searching for either
369 /// the first block-tail expression frame with no intervening
372 /// Notably, this skips over `SubExpr` frames; this method is
373 /// meant to be used in the context of understanding the
374 /// relationship of a temp (created within some complicated
375 /// expression) with its containing expression, and whether the
376 /// value of that *containing expression* (not the temp!) is
378 fn currently_in_block_tail(&self) -> Option<BlockTailInfo> {
379 for bf in self.0.iter().rev() {
381 BlockFrame::SubExpr => continue,
382 BlockFrame::Statement { .. } => break,
383 &BlockFrame::TailExpr { tail_result_is_ignored, span } => {
384 return Some(BlockTailInfo { tail_result_is_ignored, span });
392 /// Looks at the topmost frame on the BlockContext and reports
393 /// whether its one that would discard a block tail result.
395 /// Unlike `currently_within_ignored_tail_expression`, this does
396 /// *not* skip over `SubExpr` frames: here, we want to know
397 /// whether the block result itself is discarded.
398 fn currently_ignores_tail_results(&self) -> bool {
399 match self.0.last() {
400 // no context: conservatively assume result is read
403 // sub-expression: block result feeds into some computation
404 Some(BlockFrame::SubExpr) => false,
406 // otherwise: use accumulated is_ignored state.
408 BlockFrame::TailExpr { tail_result_is_ignored: ignored, .. }
409 | BlockFrame::Statement { ignores_expr_result: ignored },
417 /// In the usual case, a `HirId` for an identifier maps to at most
418 /// one `Local` declaration.
421 /// The exceptional case is identifiers in a match arm's pattern
422 /// that are referenced in a guard of that match arm. For these,
423 /// we have `2` Locals.
425 /// * `for_arm_body` is the Local used in the arm body (which is
426 /// just like the `One` case above),
428 /// * `ref_for_guard` is the Local used in the arm's guard (which
429 /// is a reference to a temp that is an alias of
431 ForGuard { ref_for_guard: Local, for_arm_body: Local },
435 struct GuardFrameLocal {
439 impl GuardFrameLocal {
440 fn new(id: hir::HirId, _binding_mode: BindingMode) -> Self {
441 GuardFrameLocal { id }
447 /// These are the id's of names that are bound by patterns of the
448 /// arm of *this* guard.
450 /// (Frames higher up the stack will have the id's bound in arms
451 /// further out, such as in a case like:
454 /// P1(id1) if (... (match E2 { P2(id2) if ... => B2 })) => B1,
457 /// here, when building for FIXME.
458 locals: Vec<GuardFrameLocal>,
461 /// `ForGuard` indicates whether we are talking about:
462 /// 1. The variable for use outside of guard expressions, or
463 /// 2. The temp that holds reference to (1.), which is actually what the
464 /// guard expressions see.
465 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
472 fn local_id(&self, for_guard: ForGuard) -> Local {
473 match (self, for_guard) {
474 (&LocalsForNode::One(local_id), ForGuard::OutsideGuard)
476 &LocalsForNode::ForGuard { ref_for_guard: local_id, .. },
477 ForGuard::RefWithinGuard,
479 | (&LocalsForNode::ForGuard { for_arm_body: local_id, .. }, ForGuard::OutsideGuard) => {
483 (&LocalsForNode::One(_), ForGuard::RefWithinGuard) => {
484 bug!("anything with one local should never be within a guard.")
491 basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
494 rustc_index::newtype_index! {
495 struct ScopeId { .. }
498 ///////////////////////////////////////////////////////////////////////////
499 /// The `BlockAnd` "monad" packages up the new basic block along with a
500 /// produced value (sometimes just unit, of course). The `unpack!`
501 /// macro (and methods below) makes working with `BlockAnd` much more
504 #[must_use = "if you don't use one of these results, you're leaving a dangling edge"]
505 struct BlockAnd<T>(BasicBlock, T);
507 trait BlockAndExtension {
508 fn and<T>(self, v: T) -> BlockAnd<T>;
509 fn unit(self) -> BlockAnd<()>;
512 impl BlockAndExtension for BasicBlock {
513 fn and<T>(self, v: T) -> BlockAnd<T> {
517 fn unit(self) -> BlockAnd<()> {
522 /// Update a block pointer and return the value.
523 /// Use it like `let x = unpack!(block = self.foo(block, foo))`.
524 macro_rules! unpack {
525 ($x:ident = $c:expr) => {{
526 let BlockAnd(b, v) = $c;
532 let BlockAnd(b, ()) = $c;
537 fn should_abort_on_panic(tcx: TyCtxt<'_>, fn_def_id: LocalDefId, _abi: Abi) -> bool {
538 // Validate `#[unwind]` syntax regardless of platform-specific panic strategy.
539 let attrs = &tcx.get_attrs(fn_def_id.to_def_id());
540 let unwind_attr = attr::find_unwind_attr(&tcx.sess, attrs);
542 // We never unwind, so it's not relevant to stop an unwind.
543 if tcx.sess.panic_strategy() != PanicStrategy::Unwind {
547 // This is a special case: some functions have a C abi but are meant to
548 // unwind anyway. Don't stop them.
550 None => false, // FIXME(#58794); should be `!(abi == Abi::Rust || abi == Abi::RustCall)`
551 Some(UnwindAttr::Allowed) => false,
552 Some(UnwindAttr::Aborts) => true,
556 ///////////////////////////////////////////////////////////////////////////
557 /// the main entry point for building MIR for a function
559 struct ArgInfo<'tcx>(
562 Option<&'tcx hir::Param<'tcx>>,
563 Option<ImplicitSelfKind>,
566 fn construct_fn<'a, 'tcx, A>(
573 return_ty_span: Span,
574 body: &'tcx hir::Body<'tcx>,
577 A: Iterator<Item = ArgInfo<'tcx>>,
579 let arguments: Vec<_> = arguments.collect();
582 let tcx_hir = tcx.hir();
583 let span = tcx_hir.span(fn_id);
585 let fn_def_id = tcx_hir.local_def_id(fn_id);
587 let mut builder = Builder::new(
597 let call_site_scope =
598 region::Scope { id: body.value.hir_id.local_id, data: region::ScopeData::CallSite };
600 region::Scope { id: body.value.hir_id.local_id, data: region::ScopeData::Arguments };
601 let mut block = START_BLOCK;
602 let source_info = builder.source_info(span);
603 let call_site_s = (call_site_scope, source_info);
605 block = builder.in_scope(call_site_s, LintLevel::Inherited, |builder| {
606 if should_abort_on_panic(tcx, fn_def_id, abi) {
607 builder.schedule_abort();
610 let arg_scope_s = (arg_scope, source_info);
611 // `return_block` is called when we evaluate a `return` expression, so
612 // we just use `START_BLOCK` here.
614 block = builder.in_breakable_scope(
617 Place::return_place(),
619 builder.in_scope(arg_scope_s, LintLevel::Inherited, |builder| {
620 builder.args_and_body(
622 fn_def_id.to_def_id(),
631 // Attribute epilogue to function's closing brace
632 let fn_end = span.shrink_to_hi();
633 let source_info = builder.source_info(fn_end);
634 let return_block = builder.return_block();
635 builder.cfg.goto(block, source_info, return_block);
636 builder.cfg.terminate(return_block, source_info, TerminatorKind::Return);
637 // Attribute any unreachable codepaths to the function's closing brace
638 if let Some(unreachable_block) = builder.cached_unreachable_block {
639 builder.cfg.terminate(unreachable_block, source_info, TerminatorKind::Unreachable);
644 assert_eq!(block, builder.return_block());
646 let spread_arg = if abi == Abi::RustCall {
647 // RustCall pseudo-ABI untuples the last argument.
648 Some(Local::new(arguments.len()))
652 debug!("fn_id {:?} has attrs {:?}", fn_def_id, tcx.get_attrs(fn_def_id.to_def_id()));
654 let mut body = builder.finish();
655 body.spread_arg = spread_arg;
659 fn construct_const<'a, 'tcx>(
661 body_id: hir::BodyId,
666 let owner_id = tcx.hir().body_owner(body_id);
667 let span = tcx.hir().span(owner_id);
668 let mut builder = Builder::new(hir, span, 0, Safety::Safe, const_ty, const_ty_span, None);
670 let mut block = START_BLOCK;
671 let ast_expr = &tcx.hir().body(body_id).value;
672 let expr = builder.hir.mirror(ast_expr);
673 unpack!(block = builder.into_expr(Place::return_place(), block, expr));
675 let source_info = builder.source_info(span);
676 builder.cfg.terminate(block, source_info, TerminatorKind::Return);
678 // Constants can't `return` so a return block should not be created.
679 assert_eq!(builder.cached_return_block, None);
681 // Constants may be match expressions in which case an unreachable block may
682 // be created, so terminate it properly.
683 if let Some(unreachable_block) = builder.cached_unreachable_block {
684 builder.cfg.terminate(unreachable_block, source_info, TerminatorKind::Unreachable);
690 /// Construct MIR for a item that has had errors in type checking.
692 /// This is required because we may still want to run MIR passes on an item
693 /// with type errors, but normal MIR construction can't handle that in general.
694 fn construct_error<'a, 'tcx>(hir: Cx<'a, 'tcx>, body_id: hir::BodyId) -> Body<'tcx> {
696 let owner_id = tcx.hir().body_owner(body_id);
697 let span = tcx.hir().span(owner_id);
698 let ty = tcx.ty_error();
699 let num_params = match hir.body_owner_kind {
700 hir::BodyOwnerKind::Fn => tcx.hir().fn_decl_by_hir_id(owner_id).unwrap().inputs.len(),
701 hir::BodyOwnerKind::Closure => {
702 if tcx.hir().body(body_id).generator_kind().is_some() {
703 // Generators have an implicit `self` parameter *and* a possibly
704 // implicit resume parameter.
707 // The implicit self parameter adds another local in MIR.
708 1 + tcx.hir().fn_decl_by_hir_id(owner_id).unwrap().inputs.len()
711 hir::BodyOwnerKind::Const => 0,
712 hir::BodyOwnerKind::Static(_) => 0,
714 let mut builder = Builder::new(hir, span, num_params, Safety::Safe, ty, span, None);
715 let source_info = builder.source_info(span);
716 // Some MIR passes will expect the number of parameters to match the
717 // function declaration.
718 for _ in 0..num_params {
719 builder.local_decls.push(LocalDecl::with_source_info(ty, source_info));
721 builder.cfg.terminate(START_BLOCK, source_info, TerminatorKind::Unreachable);
722 let mut body = builder.finish();
723 if tcx.hir().body(body_id).generator_kind.is_some() {
724 body.yield_ty = Some(ty);
729 impl<'a, 'tcx> Builder<'a, 'tcx> {
737 generator_kind: Option<GeneratorKind>,
738 ) -> Builder<'a, 'tcx> {
739 let lint_level = LintLevel::Explicit(hir.root_lint_level);
740 let mut builder = Builder {
742 cfg: CFG { basic_blocks: IndexVec::new() },
746 scopes: Default::default(),
747 block_context: BlockContext::new(),
748 source_scopes: IndexVec::new(),
749 source_scope: OUTERMOST_SOURCE_SCOPE,
750 guard_context: vec![],
751 push_unsafe_count: 0,
752 unpushed_unsafe: safety,
753 local_decls: IndexVec::from_elem_n(LocalDecl::new(return_ty, return_span), 1),
754 canonical_user_type_annotations: IndexVec::new(),
755 upvar_mutbls: vec![],
756 var_indices: Default::default(),
758 var_debug_info: vec![],
759 cached_resume_block: None,
760 cached_return_block: None,
761 cached_unreachable_block: None,
764 assert_eq!(builder.cfg.start_new_block(), START_BLOCK);
766 builder.new_source_scope(span, lint_level, Some(safety)),
767 OUTERMOST_SOURCE_SCOPE
769 builder.source_scopes[OUTERMOST_SOURCE_SCOPE].parent_scope = None;
774 fn finish(self) -> Body<'tcx> {
775 for (index, block) in self.cfg.basic_blocks.iter().enumerate() {
776 if block.terminator.is_none() {
777 span_bug!(self.fn_span, "no terminator on block {:?}", index);
782 self.cfg.basic_blocks,
785 self.canonical_user_type_annotations,
795 mut block: BasicBlock,
797 arguments: &[ArgInfo<'tcx>],
798 argument_scope: region::Scope,
799 ast_body: &'tcx hir::Expr<'tcx>,
801 let tcx = self.hir.tcx();
802 let attrs = tcx.codegen_fn_attrs(fn_def_id);
803 let naked = attrs.flags.contains(CodegenFnAttrFlags::NAKED);
805 // Allocate locals for the function arguments
806 for &ArgInfo(ty, _, arg_opt, _) in arguments.iter() {
808 SourceInfo::outermost(arg_opt.map_or(self.fn_span, |arg| arg.pat.span));
809 let arg_local = self.local_decls.push(LocalDecl::with_source_info(ty, source_info));
811 // Emit function argument debuginfo only for non-naked functions.
812 // See: https://github.com/rust-lang/rust/issues/42779
817 // If this is a simple binding pattern, give debuginfo a nice name.
818 if let Some(arg) = arg_opt {
819 if let Some(ident) = arg.pat.simple_ident() {
820 self.var_debug_info.push(VarDebugInfo {
823 place: arg_local.into(),
829 let tcx_hir = tcx.hir();
830 let hir_typeck_results = self.hir.typeck_results();
832 // In analyze_closure() in upvar.rs we gathered a list of upvars used by a
833 // indexed closure and we stored in a map called closure_captures in TypeckResults
834 // with the closure's DefId. Here, we run through that vec of UpvarIds for
835 // the given closure and use the necessary information to create upvar
836 // debuginfo and to fill `self.upvar_mutbls`.
837 if let Some(upvars) = hir_typeck_results.closure_captures.get(&fn_def_id) {
838 let closure_env_arg = Local::new(1);
839 let mut closure_env_projs = vec![];
840 let mut closure_ty = self.local_decls[closure_env_arg].ty;
841 if let ty::Ref(_, ty, _) = closure_ty.kind {
842 closure_env_projs.push(ProjectionElem::Deref);
845 let upvar_substs = match closure_ty.kind {
846 ty::Closure(_, substs) => ty::UpvarSubsts::Closure(substs),
847 ty::Generator(_, substs, _) => ty::UpvarSubsts::Generator(substs),
848 _ => span_bug!(self.fn_span, "upvars with non-closure env ty {:?}", closure_ty),
850 let upvar_tys = upvar_substs.upvar_tys();
851 let upvars_with_tys = upvars.iter().zip(upvar_tys);
852 self.upvar_mutbls = upvars_with_tys
854 .map(|(i, ((&var_id, &upvar_id), ty))| {
855 let capture = hir_typeck_results.upvar_capture(upvar_id);
857 let mut mutability = Mutability::Not;
858 let mut name = kw::Invalid;
859 if let Some(Node::Binding(pat)) = tcx_hir.find(var_id) {
860 if let hir::PatKind::Binding(_, _, ident, _) = pat.kind {
862 match hir_typeck_results
863 .extract_binding_mode(tcx.sess, pat.hir_id, pat.span)
865 Some(ty::BindByValue(hir::Mutability::Mut)) => {
866 mutability = Mutability::Mut;
868 Some(_) => mutability = Mutability::Not,
874 let mut projs = closure_env_projs.clone();
875 projs.push(ProjectionElem::Field(Field::new(i), ty));
877 ty::UpvarCapture::ByValue => {}
878 ty::UpvarCapture::ByRef(..) => {
879 projs.push(ProjectionElem::Deref);
883 self.var_debug_info.push(VarDebugInfo {
885 source_info: SourceInfo::outermost(tcx_hir.span(var_id)),
887 local: closure_env_arg,
888 projection: tcx.intern_place_elems(&projs),
897 let mut scope = None;
898 // Bind the argument patterns
899 for (index, arg_info) in arguments.iter().enumerate() {
900 // Function arguments always get the first Local indices after the return place
901 let local = Local::new(index + 1);
902 let place = Place::from(local);
903 let &ArgInfo(_, opt_ty_info, arg_opt, ref self_binding) = arg_info;
905 // Make sure we drop (parts of) the argument even when not matched on.
907 arg_opt.as_ref().map_or(ast_body.span, |arg| arg.pat.span),
913 if let Some(arg) = arg_opt {
914 let pattern = self.hir.pattern_from_hir(&arg.pat);
915 let original_source_scope = self.source_scope;
916 let span = pattern.span;
917 self.set_correct_source_scope_for_arg(arg.hir_id, original_source_scope, span);
918 match *pattern.kind {
919 // Don't introduce extra copies for simple bindings
923 mode: BindingMode::ByValue,
927 self.local_decls[local].mutability = mutability;
928 self.local_decls[local].source_info.scope = self.source_scope;
929 self.local_decls[local].local_info = if let Some(kind) = self_binding {
930 Some(box LocalInfo::User(ClearCrossCrate::Set(
931 BindingForm::ImplicitSelf(*kind),
934 let binding_mode = ty::BindingMode::BindByValue(mutability);
935 Some(box LocalInfo::User(ClearCrossCrate::Set(BindingForm::Var(
939 opt_match_place: Some((Some(place), span)),
944 self.var_indices.insert(var, LocalsForNode::One(local));
947 scope = self.declare_bindings(
951 matches::ArmHasGuard(false),
952 Some((Some(&place), span)),
954 unpack!(block = self.place_into_pattern(block, pattern, place, false));
957 self.source_scope = original_source_scope;
961 // Enter the argument pattern bindings source scope, if it exists.
962 if let Some(source_scope) = scope {
963 self.source_scope = source_scope;
966 let body = self.hir.mirror(ast_body);
967 self.into(Place::return_place(), block, body)
970 fn set_correct_source_scope_for_arg(
972 arg_hir_id: hir::HirId,
973 original_source_scope: SourceScope,
976 let tcx = self.hir.tcx();
977 let current_root = tcx.maybe_lint_level_root_bounded(arg_hir_id, self.hir.root_lint_level);
978 let parent_root = tcx.maybe_lint_level_root_bounded(
979 self.source_scopes[original_source_scope]
982 .assert_crate_local()
984 self.hir.root_lint_level,
986 if current_root != parent_root {
988 self.new_source_scope(pattern_span, LintLevel::Explicit(current_root), None);
992 fn get_unit_temp(&mut self) -> Place<'tcx> {
993 match self.unit_temp {
996 let ty = self.hir.unit_ty();
997 let fn_span = self.fn_span;
998 let tmp = self.temp(ty, fn_span);
999 self.unit_temp = Some(tmp);
1005 fn return_block(&mut self) -> BasicBlock {
1006 match self.cached_return_block {
1009 let rb = self.cfg.start_new_block();
1010 self.cached_return_block = Some(rb);
1017 ///////////////////////////////////////////////////////////////////////////
1018 // Builder methods are broken up into modules, depending on what kind
1019 // of thing is being lowered. Note that they use the `unpack` macro
1020 // above extensively.