2 use crate::build::expr::as_place::PlaceBuilder;
3 use crate::build::scope::DropKind;
4 use crate::thir::pattern::pat_from_hir;
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::{InferCtxt, TyCtxtInferExt};
13 use rustc_middle::hir::place::PlaceBase as HirPlaceBase;
14 use rustc_middle::middle::region;
15 use rustc_middle::mir::*;
16 use rustc_middle::thir::{BindingMode, Expr, ExprId, LintLevel, PatKind, Thir};
17 use rustc_middle::ty::subst::Subst;
18 use rustc_middle::ty::{self, Ty, TyCtxt, TypeFoldable, TypeckResults};
19 use rustc_span::symbol::{kw, sym};
21 use rustc_target::spec::abi::Abi;
22 use rustc_target::spec::PanicStrategy;
26 crate fn mir_built<'tcx>(
28 def: ty::WithOptConstParam<LocalDefId>,
29 ) -> &'tcx rustc_data_structures::steal::Steal<Body<'tcx>> {
30 if let Some(def) = def.try_upgrade(tcx) {
31 return tcx.mir_built(def);
34 let mut body = mir_build(tcx, def);
35 if def.const_param_did.is_some() {
36 assert!(matches!(body.source.instance, ty::InstanceDef::Item(_)));
37 body.source = MirSource::from_instance(ty::InstanceDef::Item(def.to_global()));
40 tcx.alloc_steal_mir(body)
43 /// Construct the MIR for a given `DefId`.
44 fn mir_build(tcx: TyCtxt<'_>, def: ty::WithOptConstParam<LocalDefId>) -> Body<'_> {
45 let id = tcx.hir().local_def_id_to_hir_id(def.did);
46 let body_owner_kind = tcx.hir().body_owner_kind(id);
47 let typeck_results = tcx.typeck_opt_const_arg(def);
49 // Ensure unsafeck is ran before we steal the THIR.
51 ty::WithOptConstParam { did, const_param_did: Some(const_param_did) } => {
52 tcx.ensure().thir_check_unsafety_for_const_arg((did, const_param_did))
54 ty::WithOptConstParam { did, const_param_did: None } => {
55 tcx.ensure().thir_check_unsafety(did)
59 // Figure out what primary body this item has.
60 let (body_id, return_ty_span, span_with_body) = match tcx.hir().get(id) {
61 Node::Expr(hir::Expr { kind: hir::ExprKind::Closure(_, decl, body_id, _, _), .. }) => {
62 (*body_id, decl.output.span(), None)
64 Node::Item(hir::Item {
65 kind: hir::ItemKind::Fn(hir::FnSig { decl, .. }, _, body_id),
69 | Node::ImplItem(hir::ImplItem {
70 kind: hir::ImplItemKind::Fn(hir::FnSig { decl, .. }, body_id),
74 | Node::TraitItem(hir::TraitItem {
75 kind: hir::TraitItemKind::Fn(hir::FnSig { decl, .. }, hir::TraitFn::Provided(body_id)),
79 // Use the `Span` of the `Item/ImplItem/TraitItem` as the body span,
80 // since the def span of a function does not include the body
81 (*body_id, decl.output.span(), Some(*span))
83 Node::Item(hir::Item {
84 kind: hir::ItemKind::Static(ty, _, body_id) | hir::ItemKind::Const(ty, body_id),
87 | Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Const(ty, body_id), .. })
88 | Node::TraitItem(hir::TraitItem {
89 kind: hir::TraitItemKind::Const(ty, Some(body_id)),
91 }) => (*body_id, ty.span, None),
92 Node::AnonConst(hir::AnonConst { body, hir_id, .. }) => {
93 (*body, tcx.hir().span(*hir_id), None)
96 _ => span_bug!(tcx.hir().span(id), "can't build MIR for {:?}", def.did),
99 // If we don't have a specialized span for the body, just use the
101 let span_with_body = span_with_body.unwrap_or_else(|| tcx.hir().span(id));
103 tcx.infer_ctxt().enter(|infcx| {
104 let body = if let Some(ErrorReported) = typeck_results.tainted_by_errors {
105 build::construct_error(&infcx, def, id, body_id, body_owner_kind)
106 } else if body_owner_kind.is_fn_or_closure() {
107 // fetch the fully liberated fn signature (that is, all bound
108 // types/lifetimes replaced)
109 let fn_sig = typeck_results.liberated_fn_sigs()[id];
110 let fn_def_id = tcx.hir().local_def_id(id);
112 let safety = match fn_sig.unsafety {
113 hir::Unsafety::Normal => Safety::Safe,
114 hir::Unsafety::Unsafe => Safety::FnUnsafe,
117 let body = tcx.hir().body(body_id);
118 let (thir, expr) = tcx.thir_body(def);
119 // We ran all queries that depended on THIR at the beginning
120 // of `mir_build`, so now we can steal it
121 let thir = thir.steal();
122 let ty = tcx.type_of(fn_def_id);
123 let mut abi = fn_sig.abi;
124 let implicit_argument = match ty.kind() {
126 // HACK(eddyb) Avoid having RustCall on closures,
127 // as it adds unnecessary (and wrong) auto-tupling.
129 vec![ArgInfo(liberated_closure_env_ty(tcx, id, body_id), None, None, None)]
131 ty::Generator(..) => {
132 let gen_ty = tcx.typeck_body(body_id).node_type(id);
134 // The resume argument may be missing, in that case we need to provide it here.
135 // It will always be `()` in this case.
136 if body.params.is_empty() {
138 ArgInfo(gen_ty, None, None, None),
139 ArgInfo(tcx.mk_unit(), None, None, None),
142 vec![ArgInfo(gen_ty, None, None, None)]
148 let explicit_arguments = body.params.iter().enumerate().map(|(index, arg)| {
149 let owner_id = tcx.hir().body_owner(body_id);
152 if let Some(ref fn_decl) = tcx.hir().fn_decl_by_hir_id(owner_id) {
153 opt_ty_info = fn_decl.inputs.get(index).map(|ty| ty.span);
154 self_arg = if index == 0 && fn_decl.implicit_self.has_implicit_self() {
155 match fn_decl.implicit_self {
156 hir::ImplicitSelfKind::Imm => Some(ImplicitSelfKind::Imm),
157 hir::ImplicitSelfKind::Mut => Some(ImplicitSelfKind::Mut),
158 hir::ImplicitSelfKind::ImmRef => Some(ImplicitSelfKind::ImmRef),
159 hir::ImplicitSelfKind::MutRef => Some(ImplicitSelfKind::MutRef),
170 // C-variadic fns also have a `VaList` input that's not listed in `fn_sig`
171 // (as it's created inside the body itself, not passed in from outside).
172 let ty = if fn_sig.c_variadic && index == fn_sig.inputs().len() {
173 let va_list_did = tcx.require_lang_item(LangItem::VaList, Some(arg.span));
175 tcx.type_of(va_list_did).subst(tcx, &[tcx.lifetimes.re_erased.into()])
177 fn_sig.inputs()[index]
180 ArgInfo(ty, opt_ty_info, Some(&arg), self_arg)
183 let arguments = implicit_argument.into_iter().chain(explicit_arguments);
185 let (yield_ty, return_ty) = if body.generator_kind.is_some() {
186 let gen_ty = tcx.typeck_body(body_id).node_type(id);
187 let gen_sig = match gen_ty.kind() {
188 ty::Generator(_, gen_substs, ..) => gen_substs.as_generator().sig(),
189 _ => span_bug!(tcx.hir().span(id), "generator w/o generator type: {:?}", ty),
191 (Some(gen_sig.yield_ty), gen_sig.return_ty)
193 (None, fn_sig.output())
196 let mut mir = build::construct_fn(
210 if yield_ty.is_some() {
211 mir.generator.as_mut().unwrap().yield_ty = yield_ty;
215 // Get the revealed type of this const. This is *not* the adjusted
216 // type of its body, which may be a subtype of this type. For
220 // static X: fn(&'static ()) = foo;
222 // The adjusted type of the body of X is `for<'a> fn(&'a ())` which
223 // is not the same as the type of X. We need the type of the return
224 // place to be the type of the constant because NLL typeck will
227 let return_ty = typeck_results.node_type(id);
229 let (thir, expr) = tcx.thir_body(def);
230 // We ran all queries that depended on THIR at the beginning
231 // of `mir_build`, so now we can steal it
232 let thir = thir.steal();
234 build::construct_const(&thir, &infcx, expr, def, id, return_ty, return_ty_span)
237 lints::check(tcx, &body);
239 // The borrow checker will replace all the regions here with its own
240 // inference variables. There's no point having non-erased regions here.
241 // The exception is `body.user_type_annotations`, which is used unmodified
242 // by borrow checking.
244 !(body.local_decls.has_free_regions()
245 || body.basic_blocks().has_free_regions()
246 || body.var_debug_info.has_free_regions()
247 || body.yield_ty().has_free_regions()),
248 "Unexpected free regions in MIR: {:?}",
256 ///////////////////////////////////////////////////////////////////////////
257 // BuildMir -- walks a crate, looking for fn items and methods to build MIR from
259 fn liberated_closure_env_ty(
261 closure_expr_id: hir::HirId,
262 body_id: hir::BodyId,
264 let closure_ty = tcx.typeck_body(body_id).node_type(closure_expr_id);
266 let (closure_def_id, closure_substs) = match *closure_ty.kind() {
267 ty::Closure(closure_def_id, closure_substs) => (closure_def_id, closure_substs),
268 _ => bug!("closure expr does not have closure type: {:?}", closure_ty),
272 tcx.mk_bound_variable_kinds(std::iter::once(ty::BoundVariableKind::Region(ty::BrEnv)));
274 ty::BoundRegion { var: ty::BoundVar::from_usize(bound_vars.len() - 1), kind: ty::BrEnv };
275 let env_region = ty::ReLateBound(ty::INNERMOST, br);
276 let closure_env_ty = tcx.closure_env_ty(closure_def_id, closure_substs, env_region).unwrap();
277 tcx.erase_late_bound_regions(ty::Binder::bind_with_vars(closure_env_ty, bound_vars))
280 #[derive(Debug, PartialEq, Eq)]
282 /// Evaluation is currently within a statement.
284 /// Examples include:
286 /// 2. `let _ = EXPR;`
287 /// 3. `let x = EXPR;`
289 /// If true, then statement discards result from evaluating
290 /// the expression (such as examples 1 and 2 above).
291 ignores_expr_result: bool,
294 /// Evaluation is currently within the tail expression of a block.
296 /// Example: `{ STMT_1; STMT_2; EXPR }`
298 /// If true, then the surrounding context of the block ignores
299 /// the result of evaluating the block's tail expression.
301 /// Example: `let _ = { STMT_1; EXPR };`
302 tail_result_is_ignored: bool,
304 /// `Span` of the tail expression.
308 /// Generic mark meaning that the block occurred as a subexpression
309 /// where the result might be used.
311 /// Examples: `foo(EXPR)`, `match EXPR { ... }`
316 fn is_tail_expr(&self) -> bool {
318 BlockFrame::TailExpr { .. } => true,
320 BlockFrame::Statement { .. } | BlockFrame::SubExpr => false,
323 fn is_statement(&self) -> bool {
325 BlockFrame::Statement { .. } => true,
327 BlockFrame::TailExpr { .. } | BlockFrame::SubExpr => false,
333 struct BlockContext(Vec<BlockFrame>);
335 struct Builder<'a, 'tcx> {
337 infcx: &'a InferCtxt<'a, 'tcx>,
338 typeck_results: &'tcx TypeckResults<'tcx>,
339 region_scope_tree: &'tcx region::ScopeTree,
340 param_env: ty::ParamEnv<'tcx>,
342 thir: &'a Thir<'tcx>,
347 check_overflow: bool,
350 generator_kind: Option<GeneratorKind>,
352 /// The current set of scopes, updated as we traverse;
353 /// see the `scope` module for more details.
354 scopes: scope::Scopes<'tcx>,
356 /// The block-context: each time we build the code within an thir::Block,
357 /// we push a frame here tracking whether we are building a statement or
358 /// if we are pushing the tail expression of the block. This is used to
359 /// embed information in generated temps about whether they were created
360 /// for a block tail expression or not.
362 /// It would be great if we could fold this into `self.scopes`
363 /// somehow, but right now I think that is very tightly tied to
364 /// the code generation in ways that we cannot (or should not)
365 /// start just throwing new entries onto that vector in order to
366 /// distinguish the context of EXPR1 from the context of EXPR2 in
367 /// `{ STMTS; EXPR1 } + EXPR2`.
368 block_context: BlockContext,
370 /// The current unsafe block in scope
371 in_scope_unsafe: Safety,
373 /// The vector of all scopes that we have created thus far;
374 /// we track this for debuginfo later.
375 source_scopes: IndexVec<SourceScope, SourceScopeData<'tcx>>,
376 source_scope: SourceScope,
378 /// The guard-context: each time we build the guard expression for
379 /// a match arm, we push onto this stack, and then pop when we
380 /// finish building it.
381 guard_context: Vec<GuardFrame>,
383 /// Maps `HirId`s of variable bindings to the `Local`s created for them.
384 /// (A match binding can have two locals; the 2nd is for the arm's guard.)
385 var_indices: HirIdMap<LocalsForNode>,
386 local_decls: IndexVec<Local, LocalDecl<'tcx>>,
387 canonical_user_type_annotations: ty::CanonicalUserTypeAnnotations<'tcx>,
388 upvar_mutbls: Vec<Mutability>,
389 unit_temp: Option<Place<'tcx>>,
391 var_debug_info: Vec<VarDebugInfo<'tcx>>,
394 impl<'a, 'tcx> Builder<'a, 'tcx> {
395 fn is_bound_var_in_guard(&self, id: hir::HirId) -> bool {
396 self.guard_context.iter().any(|frame| frame.locals.iter().any(|local| local.id == id))
399 fn var_local_id(&self, id: hir::HirId, for_guard: ForGuard) -> Local {
400 self.var_indices[&id].local_id(for_guard)
408 fn push(&mut self, bf: BlockFrame) {
411 fn pop(&mut self) -> Option<BlockFrame> {
415 /// Traverses the frames on the `BlockContext`, searching for either
416 /// the first block-tail expression frame with no intervening
419 /// Notably, this skips over `SubExpr` frames; this method is
420 /// meant to be used in the context of understanding the
421 /// relationship of a temp (created within some complicated
422 /// expression) with its containing expression, and whether the
423 /// value of that *containing expression* (not the temp!) is
425 fn currently_in_block_tail(&self) -> Option<BlockTailInfo> {
426 for bf in self.0.iter().rev() {
428 BlockFrame::SubExpr => continue,
429 BlockFrame::Statement { .. } => break,
430 &BlockFrame::TailExpr { tail_result_is_ignored, span } => {
431 return Some(BlockTailInfo { tail_result_is_ignored, span });
439 /// Looks at the topmost frame on the BlockContext and reports
440 /// whether its one that would discard a block tail result.
442 /// Unlike `currently_within_ignored_tail_expression`, this does
443 /// *not* skip over `SubExpr` frames: here, we want to know
444 /// whether the block result itself is discarded.
445 fn currently_ignores_tail_results(&self) -> bool {
446 match self.0.last() {
447 // no context: conservatively assume result is read
450 // sub-expression: block result feeds into some computation
451 Some(BlockFrame::SubExpr) => false,
453 // otherwise: use accumulated is_ignored state.
455 BlockFrame::TailExpr { tail_result_is_ignored: ignored, .. }
456 | BlockFrame::Statement { ignores_expr_result: ignored },
464 /// In the usual case, a `HirId` for an identifier maps to at most
465 /// one `Local` declaration.
468 /// The exceptional case is identifiers in a match arm's pattern
469 /// that are referenced in a guard of that match arm. For these,
470 /// we have `2` Locals.
472 /// * `for_arm_body` is the Local used in the arm body (which is
473 /// just like the `One` case above),
475 /// * `ref_for_guard` is the Local used in the arm's guard (which
476 /// is a reference to a temp that is an alias of
478 ForGuard { ref_for_guard: Local, for_arm_body: Local },
482 struct GuardFrameLocal {
486 impl GuardFrameLocal {
487 fn new(id: hir::HirId, _binding_mode: BindingMode) -> Self {
488 GuardFrameLocal { id }
494 /// These are the id's of names that are bound by patterns of the
495 /// arm of *this* guard.
497 /// (Frames higher up the stack will have the id's bound in arms
498 /// further out, such as in a case like:
501 /// P1(id1) if (... (match E2 { P2(id2) if ... => B2 })) => B1,
504 /// here, when building for FIXME.
505 locals: Vec<GuardFrameLocal>,
508 /// `ForGuard` indicates whether we are talking about:
509 /// 1. The variable for use outside of guard expressions, or
510 /// 2. The temp that holds reference to (1.), which is actually what the
511 /// guard expressions see.
512 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
519 fn local_id(&self, for_guard: ForGuard) -> Local {
520 match (self, for_guard) {
521 (&LocalsForNode::One(local_id), ForGuard::OutsideGuard)
523 &LocalsForNode::ForGuard { ref_for_guard: local_id, .. },
524 ForGuard::RefWithinGuard,
526 | (&LocalsForNode::ForGuard { for_arm_body: local_id, .. }, ForGuard::OutsideGuard) => {
530 (&LocalsForNode::One(_), ForGuard::RefWithinGuard) => {
531 bug!("anything with one local should never be within a guard.")
538 basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
541 rustc_index::newtype_index! {
542 struct ScopeId { .. }
545 ///////////////////////////////////////////////////////////////////////////
546 /// The `BlockAnd` "monad" packages up the new basic block along with a
547 /// produced value (sometimes just unit, of course). The `unpack!`
548 /// macro (and methods below) makes working with `BlockAnd` much more
551 #[must_use = "if you don't use one of these results, you're leaving a dangling edge"]
552 struct BlockAnd<T>(BasicBlock, T);
554 trait BlockAndExtension {
555 fn and<T>(self, v: T) -> BlockAnd<T>;
556 fn unit(self) -> BlockAnd<()>;
559 impl BlockAndExtension for BasicBlock {
560 fn and<T>(self, v: T) -> BlockAnd<T> {
564 fn unit(self) -> BlockAnd<()> {
569 /// Update a block pointer and return the value.
570 /// Use it like `let x = unpack!(block = self.foo(block, foo))`.
571 macro_rules! unpack {
572 ($x:ident = $c:expr) => {{
573 let BlockAnd(b, v) = $c;
579 let BlockAnd(b, ()) = $c;
584 fn should_abort_on_panic(tcx: TyCtxt<'_>, fn_def_id: LocalDefId, abi: Abi) -> bool {
585 // Validate `#[unwind]` syntax regardless of platform-specific panic strategy.
586 let attrs = &tcx.get_attrs(fn_def_id.to_def_id());
587 let unwind_attr = attr::find_unwind_attr(&tcx.sess, attrs);
589 // We never unwind, so it's not relevant to stop an unwind.
590 if tcx.sess.panic_strategy() != PanicStrategy::Unwind {
595 // If an `#[unwind]` attribute was found, we should adhere to it.
596 Some(UnwindAttr::Allowed) => false,
597 Some(UnwindAttr::Aborts) => true,
598 // If no attribute was found and the panic strategy is `unwind`, then we should examine
599 // the function's ABI string to determine whether it should abort upon panic.
600 None if tcx.features().c_unwind => {
603 // In the case of ABI's that have an `-unwind` equivalent, check whether the ABI
604 // permits unwinding. If so, we should not abort. Otherwise, we should.
605 C { unwind } | Stdcall { unwind } | System { unwind } | Thiscall { unwind } => {
608 // Rust and `rust-call` functions are allowed to unwind, and should not abort.
609 Rust | RustCall => false,
610 // Other ABI's should abort.
623 | AvrNonBlockingInterrupt
628 | Unadjusted => true,
631 // If the `c_unwind` feature gate is not active, follow the behavior that was in place
632 // prior to #76570. This is a special case: some functions have a C ABI but are meant to
633 // unwind anyway. Don't stop them.
634 None => false, // FIXME(#58794); should be `!(abi == Abi::Rust || abi == Abi::RustCall)`
638 ///////////////////////////////////////////////////////////////////////////
639 /// the main entry point for building MIR for a function
641 struct ArgInfo<'tcx>(
644 Option<&'tcx hir::Param<'tcx>>,
645 Option<ImplicitSelfKind>,
648 fn construct_fn<'tcx, A>(
650 infcx: &InferCtxt<'_, 'tcx>,
651 fn_def: ty::WithOptConstParam<LocalDefId>,
657 return_ty_span: Span,
658 body: &'tcx hir::Body<'tcx>,
660 span_with_body: Span,
663 A: Iterator<Item = ArgInfo<'tcx>>,
665 let arguments: Vec<_> = arguments.collect();
668 let span = tcx.hir().span(fn_id);
670 let mut builder = Builder::new(
683 let call_site_scope =
684 region::Scope { id: body.value.hir_id.local_id, data: region::ScopeData::CallSite };
686 region::Scope { id: body.value.hir_id.local_id, data: region::ScopeData::Arguments };
687 let source_info = builder.source_info(span);
688 let call_site_s = (call_site_scope, source_info);
689 unpack!(builder.in_scope(call_site_s, LintLevel::Inherited, |builder| {
690 let arg_scope_s = (arg_scope, source_info);
691 // Attribute epilogue to function's closing brace
692 let fn_end = span_with_body.shrink_to_hi();
694 unpack!(builder.in_breakable_scope(None, Place::return_place(), fn_end, |builder| {
695 Some(builder.in_scope(arg_scope_s, LintLevel::Inherited, |builder| {
696 builder.args_and_body(
698 fn_def.did.to_def_id(),
705 let source_info = builder.source_info(fn_end);
706 builder.cfg.terminate(return_block, source_info, TerminatorKind::Return);
707 let should_abort = should_abort_on_panic(tcx, fn_def.did, abi);
708 builder.build_drop_trees(should_abort);
712 let spread_arg = if abi == Abi::RustCall {
713 // RustCall pseudo-ABI untuples the last argument.
714 Some(Local::new(arguments.len()))
718 debug!("fn_id {:?} has attrs {:?}", fn_def, tcx.get_attrs(fn_def.did.to_def_id()));
720 let mut body = builder.finish();
721 body.spread_arg = spread_arg;
725 fn construct_const<'a, 'tcx>(
726 thir: &'a Thir<'tcx>,
727 infcx: &'a InferCtxt<'a, 'tcx>,
729 def: ty::WithOptConstParam<LocalDefId>,
735 let span = tcx.hir().span(hir_id);
736 let mut builder = Builder::new(
749 let mut block = START_BLOCK;
750 unpack!(block = builder.expr_into_dest(Place::return_place(), block, &thir[expr]));
752 let source_info = builder.source_info(span);
753 builder.cfg.terminate(block, source_info, TerminatorKind::Return);
755 builder.build_drop_trees(false);
760 /// Construct MIR for a item that has had errors in type checking.
762 /// This is required because we may still want to run MIR passes on an item
763 /// with type errors, but normal MIR construction can't handle that in general.
764 fn construct_error<'a, 'tcx>(
765 infcx: &'a InferCtxt<'a, 'tcx>,
766 def: ty::WithOptConstParam<LocalDefId>,
768 body_id: hir::BodyId,
769 body_owner_kind: hir::BodyOwnerKind,
772 let span = tcx.hir().span(hir_id);
773 let ty = tcx.ty_error();
774 let generator_kind = tcx.hir().body(body_id).generator_kind;
775 let num_params = match body_owner_kind {
776 hir::BodyOwnerKind::Fn => tcx.hir().fn_decl_by_hir_id(hir_id).unwrap().inputs.len(),
777 hir::BodyOwnerKind::Closure => {
778 if generator_kind.is_some() {
779 // Generators have an implicit `self` parameter *and* a possibly
780 // implicit resume parameter.
783 // The implicit self parameter adds another local in MIR.
784 1 + tcx.hir().fn_decl_by_hir_id(hir_id).unwrap().inputs.len()
787 hir::BodyOwnerKind::Const => 0,
788 hir::BodyOwnerKind::Static(_) => 0,
790 let mut cfg = CFG { basic_blocks: IndexVec::new() };
791 let mut source_scopes = IndexVec::new();
792 let mut local_decls = IndexVec::from_elem_n(LocalDecl::new(ty, span), 1);
794 cfg.start_new_block();
795 source_scopes.push(SourceScopeData {
799 inlined_parent_scope: None,
800 local_data: ClearCrossCrate::Set(SourceScopeLocalData {
802 safety: Safety::Safe,
805 let source_info = SourceInfo { span, scope: OUTERMOST_SOURCE_SCOPE };
807 // Some MIR passes will expect the number of parameters to match the
808 // function declaration.
809 for _ in 0..num_params {
810 local_decls.push(LocalDecl::with_source_info(ty, source_info));
812 cfg.terminate(START_BLOCK, source_info, TerminatorKind::Unreachable);
814 let mut body = Body::new(
815 MirSource::item(def.did.to_def_id()),
825 body.generator.as_mut().map(|gen| gen.yield_ty = Some(ty));
829 impl<'a, 'tcx> Builder<'a, 'tcx> {
831 thir: &'a Thir<'tcx>,
832 infcx: &'a InferCtxt<'a, 'tcx>,
833 def: ty::WithOptConstParam<LocalDefId>,
840 generator_kind: Option<GeneratorKind>,
841 ) -> Builder<'a, 'tcx> {
843 let attrs = tcx.hir().attrs(hir_id);
844 // Some functions always have overflow checks enabled,
845 // however, they may not get codegen'd, depending on
846 // the settings for the crate they are codegened in.
847 let mut check_overflow = tcx.sess.contains_name(attrs, sym::rustc_inherit_overflow_checks);
848 // Respect -C overflow-checks.
849 check_overflow |= tcx.sess.overflow_checks();
850 // Constants always need overflow checks.
851 check_overflow |= matches!(
852 tcx.hir().body_owner_kind(hir_id),
853 hir::BodyOwnerKind::Const | hir::BodyOwnerKind::Static(_)
856 let lint_level = LintLevel::Explicit(hir_id);
857 let mut builder = Builder {
861 typeck_results: tcx.typeck_opt_const_arg(def),
862 region_scope_tree: tcx.region_scope_tree(def.did),
863 param_env: tcx.param_env(def.did),
864 def_id: def.did.to_def_id(),
867 cfg: CFG { basic_blocks: IndexVec::new() },
871 scopes: scope::Scopes::new(),
872 block_context: BlockContext::new(),
873 source_scopes: IndexVec::new(),
874 source_scope: OUTERMOST_SOURCE_SCOPE,
875 guard_context: vec![],
876 in_scope_unsafe: safety,
877 local_decls: IndexVec::from_elem_n(LocalDecl::new(return_ty, return_span), 1),
878 canonical_user_type_annotations: IndexVec::new(),
879 upvar_mutbls: vec![],
880 var_indices: Default::default(),
882 var_debug_info: vec![],
885 assert_eq!(builder.cfg.start_new_block(), START_BLOCK);
887 builder.new_source_scope(span, lint_level, Some(safety)),
888 OUTERMOST_SOURCE_SCOPE
890 builder.source_scopes[OUTERMOST_SOURCE_SCOPE].parent_scope = None;
895 fn finish(self) -> Body<'tcx> {
896 for (index, block) in self.cfg.basic_blocks.iter().enumerate() {
897 if block.terminator.is_none() {
898 span_bug!(self.fn_span, "no terminator on block {:?}", index);
903 MirSource::item(self.def_id),
904 self.cfg.basic_blocks,
907 self.canonical_user_type_annotations,
917 mut block: BasicBlock,
919 arguments: &[ArgInfo<'tcx>],
920 argument_scope: region::Scope,
923 // Allocate locals for the function arguments
924 for &ArgInfo(ty, _, arg_opt, _) in arguments.iter() {
926 SourceInfo::outermost(arg_opt.map_or(self.fn_span, |arg| arg.pat.span));
927 let arg_local = self.local_decls.push(LocalDecl::with_source_info(ty, source_info));
929 // If this is a simple binding pattern, give debuginfo a nice name.
930 if let Some(arg) = arg_opt {
931 if let Some(ident) = arg.pat.simple_ident() {
932 self.var_debug_info.push(VarDebugInfo {
935 value: VarDebugInfoContents::Place(arg_local.into()),
942 let tcx_hir = tcx.hir();
943 let hir_typeck_results = self.typeck_results;
945 // In analyze_closure() in upvar.rs we gathered a list of upvars used by a
946 // indexed closure and we stored in a map called closure_min_captures in TypeckResults
947 // with the closure's DefId. Here, we run through that vec of UpvarIds for
948 // the given closure and use the necessary information to create upvar
949 // debuginfo and to fill `self.upvar_mutbls`.
950 if hir_typeck_results.closure_min_captures.get(&fn_def_id).is_some() {
951 let mut closure_env_projs = vec![];
952 let mut closure_ty = self.local_decls[ty::CAPTURE_STRUCT_LOCAL].ty;
953 if let ty::Ref(_, ty, _) = closure_ty.kind() {
954 closure_env_projs.push(ProjectionElem::Deref);
957 let upvar_substs = match closure_ty.kind() {
958 ty::Closure(_, substs) => ty::UpvarSubsts::Closure(substs),
959 ty::Generator(_, substs, _) => ty::UpvarSubsts::Generator(substs),
960 _ => span_bug!(self.fn_span, "upvars with non-closure env ty {:?}", closure_ty),
962 let capture_tys = upvar_substs.upvar_tys();
963 let captures_with_tys =
964 hir_typeck_results.closure_min_captures_flattened(fn_def_id).zip(capture_tys);
966 self.upvar_mutbls = captures_with_tys
968 .map(|(i, (captured_place, ty))| {
969 let capture = captured_place.info.capture_kind;
970 let var_id = match captured_place.place.base {
971 HirPlaceBase::Upvar(upvar_id) => upvar_id.var_path.hir_id,
972 _ => bug!("Expected an upvar"),
975 let mutability = captured_place.mutability;
977 // FIXME(project-rfc-2229#8): Store more precise information
978 let mut name = kw::Empty;
979 if let Some(Node::Binding(pat)) = tcx_hir.find(var_id) {
980 if let hir::PatKind::Binding(_, _, ident, _) = pat.kind {
985 let mut projs = closure_env_projs.clone();
986 projs.push(ProjectionElem::Field(Field::new(i), ty));
988 ty::UpvarCapture::ByValue(_) => {}
989 ty::UpvarCapture::ByRef(..) => {
990 projs.push(ProjectionElem::Deref);
994 self.var_debug_info.push(VarDebugInfo {
996 source_info: SourceInfo::outermost(tcx_hir.span(var_id)),
997 value: VarDebugInfoContents::Place(Place {
998 local: ty::CAPTURE_STRUCT_LOCAL,
999 projection: tcx.intern_place_elems(&projs),
1008 let mut scope = None;
1009 // Bind the argument patterns
1010 for (index, arg_info) in arguments.iter().enumerate() {
1011 // Function arguments always get the first Local indices after the return place
1012 let local = Local::new(index + 1);
1013 let place = Place::from(local);
1014 let &ArgInfo(_, opt_ty_info, arg_opt, ref self_binding) = arg_info;
1016 // Make sure we drop (parts of) the argument even when not matched on.
1018 arg_opt.as_ref().map_or(expr.span, |arg| arg.pat.span),
1024 if let Some(arg) = arg_opt {
1025 let pat = match tcx.hir().get(arg.pat.hir_id) {
1026 Node::Pat(pat) | Node::Binding(pat) => pat,
1027 node => bug!("pattern became {:?}", node),
1029 let pattern = pat_from_hir(tcx, self.param_env, self.typeck_results, pat);
1030 let original_source_scope = self.source_scope;
1031 let span = pattern.span;
1032 self.set_correct_source_scope_for_arg(arg.hir_id, original_source_scope, span);
1033 match *pattern.kind {
1034 // Don't introduce extra copies for simple bindings
1038 mode: BindingMode::ByValue,
1042 self.local_decls[local].mutability = mutability;
1043 self.local_decls[local].source_info.scope = self.source_scope;
1044 self.local_decls[local].local_info = if let Some(kind) = self_binding {
1045 Some(box LocalInfo::User(ClearCrossCrate::Set(
1046 BindingForm::ImplicitSelf(*kind),
1049 let binding_mode = ty::BindingMode::BindByValue(mutability);
1050 Some(box LocalInfo::User(ClearCrossCrate::Set(BindingForm::Var(
1054 opt_match_place: Some((Some(place), span)),
1059 self.var_indices.insert(var, LocalsForNode::One(local));
1062 scope = self.declare_bindings(
1066 matches::ArmHasGuard(false),
1067 Some((Some(&place), span)),
1069 let place_builder = PlaceBuilder::from(local);
1071 block = self.place_into_pattern(block, pattern, place_builder, false)
1075 self.source_scope = original_source_scope;
1079 // Enter the argument pattern bindings source scope, if it exists.
1080 if let Some(source_scope) = scope {
1081 self.source_scope = source_scope;
1084 self.expr_into_dest(Place::return_place(), block, &expr)
1087 fn set_correct_source_scope_for_arg(
1089 arg_hir_id: hir::HirId,
1090 original_source_scope: SourceScope,
1094 let current_root = tcx.maybe_lint_level_root_bounded(arg_hir_id, self.hir_id);
1095 let parent_root = tcx.maybe_lint_level_root_bounded(
1096 self.source_scopes[original_source_scope]
1099 .assert_crate_local()
1103 if current_root != parent_root {
1105 self.new_source_scope(pattern_span, LintLevel::Explicit(current_root), None);
1109 fn get_unit_temp(&mut self) -> Place<'tcx> {
1110 match self.unit_temp {
1113 let ty = self.tcx.mk_unit();
1114 let fn_span = self.fn_span;
1115 let tmp = self.temp(ty, fn_span);
1116 self.unit_temp = Some(tmp);
1123 ///////////////////////////////////////////////////////////////////////////
1124 // Builder methods are broken up into modules, depending on what kind
1125 // of thing is being lowered. Note that they use the `unpack` macro
1126 // above extensively.