2 pub(crate) use crate::build::expr::as_constant::lit_to_mir_constant;
3 use crate::build::expr::as_place::PlaceBuilder;
4 use crate::build::scope::DropKind;
5 use crate::thir::pattern::pat_from_hir;
6 use rustc_apfloat::ieee::{Double, Single};
7 use rustc_apfloat::Float;
8 use rustc_data_structures::fx::FxHashMap;
9 use rustc_errors::ErrorGuaranteed;
11 use rustc_hir::def_id::{DefId, LocalDefId};
12 use rustc_hir::lang_items::LangItem;
13 use rustc_hir::{GeneratorKind, Node};
14 use rustc_index::vec::{Idx, IndexVec};
15 use rustc_infer::infer::{InferCtxt, TyCtxtInferExt};
16 use rustc_middle::hir::place::PlaceBase as HirPlaceBase;
17 use rustc_middle::middle::region;
18 use rustc_middle::mir::interpret::ConstValue;
19 use rustc_middle::mir::interpret::Scalar;
20 use rustc_middle::mir::*;
21 use rustc_middle::thir::{BindingMode, Expr, ExprId, LintLevel, LocalVarId, PatKind, Thir};
22 use rustc_middle::ty::subst::Subst;
23 use rustc_middle::ty::{self, Ty, TyCtxt, TypeVisitable, TypeckResults};
24 use rustc_span::symbol::sym;
26 use rustc_span::Symbol;
27 use rustc_target::spec::abi::Abi;
31 pub(crate) fn mir_built<'tcx>(
33 def: ty::WithOptConstParam<LocalDefId>,
34 ) -> &'tcx rustc_data_structures::steal::Steal<Body<'tcx>> {
35 if let Some(def) = def.try_upgrade(tcx) {
36 return tcx.mir_built(def);
39 let mut body = mir_build(tcx, def);
40 if def.const_param_did.is_some() {
41 assert!(matches!(body.source.instance, ty::InstanceDef::Item(_)));
42 body.source = MirSource::from_instance(ty::InstanceDef::Item(def.to_global()));
45 tcx.alloc_steal_mir(body)
48 /// Construct the MIR for a given `DefId`.
49 fn mir_build(tcx: TyCtxt<'_>, def: ty::WithOptConstParam<LocalDefId>) -> Body<'_> {
50 let id = tcx.hir().local_def_id_to_hir_id(def.did);
51 let body_owner_kind = tcx.hir().body_owner_kind(def.did);
52 let typeck_results = tcx.typeck_opt_const_arg(def);
54 // Ensure unsafeck and abstract const building is ran before we steal the THIR.
55 // We can't use `ensure()` for `thir_abstract_const` as it doesn't compute the query
56 // if inputs are green. This can cause ICEs when calling `thir_abstract_const` after
57 // THIR has been stolen if we haven't computed this query yet.
59 ty::WithOptConstParam { did, const_param_did: Some(const_param_did) } => {
60 tcx.ensure().thir_check_unsafety_for_const_arg((did, const_param_did));
61 drop(tcx.thir_abstract_const_of_const_arg((did, const_param_did)));
63 ty::WithOptConstParam { did, const_param_did: None } => {
64 tcx.ensure().thir_check_unsafety(did);
65 drop(tcx.thir_abstract_const(did));
69 // Figure out what primary body this item has.
70 let (body_id, return_ty_span, span_with_body) = match tcx.hir().get(id) {
71 Node::Expr(hir::Expr {
72 kind: hir::ExprKind::Closure(hir::Closure { fn_decl, body, .. }),
74 }) => (*body, fn_decl.output.span(), None),
75 Node::Item(hir::Item {
76 kind: hir::ItemKind::Fn(hir::FnSig { decl, .. }, _, body_id),
80 | Node::ImplItem(hir::ImplItem {
81 kind: hir::ImplItemKind::Fn(hir::FnSig { decl, .. }, body_id),
85 | Node::TraitItem(hir::TraitItem {
86 kind: hir::TraitItemKind::Fn(hir::FnSig { decl, .. }, hir::TraitFn::Provided(body_id)),
90 // Use the `Span` of the `Item/ImplItem/TraitItem` as the body span,
91 // since the def span of a function does not include the body
92 (*body_id, decl.output.span(), Some(*span))
94 Node::Item(hir::Item {
95 kind: hir::ItemKind::Static(ty, _, body_id) | hir::ItemKind::Const(ty, body_id),
98 | Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Const(ty, body_id), .. })
99 | Node::TraitItem(hir::TraitItem {
100 kind: hir::TraitItemKind::Const(ty, Some(body_id)),
102 }) => (*body_id, ty.span, None),
103 Node::AnonConst(hir::AnonConst { body, hir_id, .. }) => {
104 (*body, tcx.hir().span(*hir_id), None)
107 _ => span_bug!(tcx.hir().span(id), "can't build MIR for {:?}", def.did),
110 // If we don't have a specialized span for the body, just use the
112 let span_with_body = span_with_body.unwrap_or_else(|| tcx.hir().span(id));
114 tcx.infer_ctxt().enter(|infcx| {
115 let body = if let Some(error_reported) = typeck_results.tainted_by_errors {
116 build::construct_error(&infcx, def, id, body_id, body_owner_kind, error_reported)
117 } else if body_owner_kind.is_fn_or_closure() {
118 // fetch the fully liberated fn signature (that is, all bound
119 // types/lifetimes replaced)
120 let fn_sig = typeck_results.liberated_fn_sigs()[id];
121 let fn_def_id = tcx.hir().local_def_id(id);
123 let safety = match fn_sig.unsafety {
124 hir::Unsafety::Normal => Safety::Safe,
125 hir::Unsafety::Unsafe => Safety::FnUnsafe,
128 let body = tcx.hir().body(body_id);
129 let (thir, expr) = tcx
131 .unwrap_or_else(|_| (tcx.alloc_steal_thir(Thir::new()), ExprId::from_u32(0)));
132 // We ran all queries that depended on THIR at the beginning
133 // of `mir_build`, so now we can steal it
134 let thir = thir.steal();
135 let ty = tcx.type_of(fn_def_id);
136 let mut abi = fn_sig.abi;
137 let implicit_argument = match ty.kind() {
139 // HACK(eddyb) Avoid having RustCall on closures,
140 // as it adds unnecessary (and wrong) auto-tupling.
142 vec![ArgInfo(liberated_closure_env_ty(tcx, id, body_id), None, None, None)]
144 ty::Generator(..) => {
145 let gen_ty = tcx.typeck_body(body_id).node_type(id);
147 // The resume argument may be missing, in that case we need to provide it here.
148 // It will always be `()` in this case.
149 if body.params.is_empty() {
151 ArgInfo(gen_ty, None, None, None),
152 ArgInfo(tcx.mk_unit(), None, None, None),
155 vec![ArgInfo(gen_ty, None, None, None)]
161 let explicit_arguments = body.params.iter().enumerate().map(|(index, arg)| {
162 let owner_id = tcx.hir().body_owner(body_id);
165 if let Some(ref fn_decl) = tcx.hir().fn_decl_by_hir_id(owner_id) {
166 opt_ty_info = fn_decl
169 // Make sure that inferred closure args have no type span
170 .and_then(|ty| if arg.pat.span != ty.span { Some(ty.span) } else { None });
171 self_arg = if index == 0 && fn_decl.implicit_self.has_implicit_self() {
172 match fn_decl.implicit_self {
173 hir::ImplicitSelfKind::Imm => Some(ImplicitSelfKind::Imm),
174 hir::ImplicitSelfKind::Mut => Some(ImplicitSelfKind::Mut),
175 hir::ImplicitSelfKind::ImmRef => Some(ImplicitSelfKind::ImmRef),
176 hir::ImplicitSelfKind::MutRef => Some(ImplicitSelfKind::MutRef),
187 // C-variadic fns also have a `VaList` input that's not listed in `fn_sig`
188 // (as it's created inside the body itself, not passed in from outside).
189 let ty = if fn_sig.c_variadic && index == fn_sig.inputs().len() {
190 let va_list_did = tcx.require_lang_item(LangItem::VaList, Some(arg.span));
192 tcx.bound_type_of(va_list_did).subst(tcx, &[tcx.lifetimes.re_erased.into()])
194 fn_sig.inputs()[index]
197 ArgInfo(ty, opt_ty_info, Some(&arg), self_arg)
200 let arguments = implicit_argument.into_iter().chain(explicit_arguments);
202 let (yield_ty, return_ty) = if body.generator_kind.is_some() {
203 let gen_ty = tcx.typeck_body(body_id).node_type(id);
204 let gen_sig = match gen_ty.kind() {
205 ty::Generator(_, gen_substs, ..) => gen_substs.as_generator().sig(),
206 _ => span_bug!(tcx.hir().span(id), "generator w/o generator type: {:?}", ty),
208 (Some(gen_sig.yield_ty), gen_sig.return_ty)
210 (None, fn_sig.output())
213 let mut mir = build::construct_fn(
227 if yield_ty.is_some() {
228 mir.generator.as_mut().unwrap().yield_ty = yield_ty;
232 // Get the revealed type of this const. This is *not* the adjusted
233 // type of its body, which may be a subtype of this type. For
237 // static X: fn(&'static ()) = foo;
239 // The adjusted type of the body of X is `for<'a> fn(&'a ())` which
240 // is not the same as the type of X. We need the type of the return
241 // place to be the type of the constant because NLL typeck will
244 let return_ty = typeck_results.node_type(id);
246 let (thir, expr) = tcx
248 .unwrap_or_else(|_| (tcx.alloc_steal_thir(Thir::new()), ExprId::from_u32(0)));
249 // We ran all queries that depended on THIR at the beginning
250 // of `mir_build`, so now we can steal it
251 let thir = thir.steal();
253 build::construct_const(&thir, &infcx, expr, def, id, return_ty, return_ty_span)
256 lints::check(tcx, &body);
258 // The borrow checker will replace all the regions here with its own
259 // inference variables. There's no point having non-erased regions here.
260 // The exception is `body.user_type_annotations`, which is used unmodified
261 // by borrow checking.
263 !(body.local_decls.has_free_regions()
264 || body.basic_blocks().has_free_regions()
265 || body.var_debug_info.has_free_regions()
266 || body.yield_ty().has_free_regions()),
267 "Unexpected free regions in MIR: {:?}",
275 ///////////////////////////////////////////////////////////////////////////
276 // BuildMir -- walks a crate, looking for fn items and methods to build MIR from
278 fn liberated_closure_env_ty(
280 closure_expr_id: hir::HirId,
281 body_id: hir::BodyId,
283 let closure_ty = tcx.typeck_body(body_id).node_type(closure_expr_id);
285 let ty::Closure(closure_def_id, closure_substs) = *closure_ty.kind() else {
286 bug!("closure expr does not have closure type: {:?}", closure_ty);
290 tcx.mk_bound_variable_kinds(std::iter::once(ty::BoundVariableKind::Region(ty::BrEnv)));
292 ty::BoundRegion { var: ty::BoundVar::from_usize(bound_vars.len() - 1), kind: ty::BrEnv };
293 let env_region = ty::ReLateBound(ty::INNERMOST, br);
294 let closure_env_ty = tcx.closure_env_ty(closure_def_id, closure_substs, env_region).unwrap();
295 tcx.erase_late_bound_regions(ty::Binder::bind_with_vars(closure_env_ty, bound_vars))
298 #[derive(Debug, PartialEq, Eq)]
300 /// Evaluation is currently within a statement.
302 /// Examples include:
304 /// 2. `let _ = EXPR;`
305 /// 3. `let x = EXPR;`
307 /// If true, then statement discards result from evaluating
308 /// the expression (such as examples 1 and 2 above).
309 ignores_expr_result: bool,
312 /// Evaluation is currently within the tail expression of a block.
314 /// Example: `{ STMT_1; STMT_2; EXPR }`
316 /// If true, then the surrounding context of the block ignores
317 /// the result of evaluating the block's tail expression.
319 /// Example: `let _ = { STMT_1; EXPR };`
320 tail_result_is_ignored: bool,
322 /// `Span` of the tail expression.
326 /// Generic mark meaning that the block occurred as a subexpression
327 /// where the result might be used.
329 /// Examples: `foo(EXPR)`, `match EXPR { ... }`
334 fn is_tail_expr(&self) -> bool {
336 BlockFrame::TailExpr { .. } => true,
338 BlockFrame::Statement { .. } | BlockFrame::SubExpr => false,
341 fn is_statement(&self) -> bool {
343 BlockFrame::Statement { .. } => true,
345 BlockFrame::TailExpr { .. } | BlockFrame::SubExpr => false,
351 struct BlockContext(Vec<BlockFrame>);
353 struct Builder<'a, 'tcx> {
355 infcx: &'a InferCtxt<'a, 'tcx>,
356 typeck_results: &'tcx TypeckResults<'tcx>,
357 region_scope_tree: &'tcx region::ScopeTree,
358 param_env: ty::ParamEnv<'tcx>,
360 thir: &'a Thir<'tcx>,
365 parent_module: DefId,
366 check_overflow: bool,
369 generator_kind: Option<GeneratorKind>,
371 /// The current set of scopes, updated as we traverse;
372 /// see the `scope` module for more details.
373 scopes: scope::Scopes<'tcx>,
375 /// The block-context: each time we build the code within an thir::Block,
376 /// we push a frame here tracking whether we are building a statement or
377 /// if we are pushing the tail expression of the block. This is used to
378 /// embed information in generated temps about whether they were created
379 /// for a block tail expression or not.
381 /// It would be great if we could fold this into `self.scopes`
382 /// somehow, but right now I think that is very tightly tied to
383 /// the code generation in ways that we cannot (or should not)
384 /// start just throwing new entries onto that vector in order to
385 /// distinguish the context of EXPR1 from the context of EXPR2 in
386 /// `{ STMTS; EXPR1 } + EXPR2`.
387 block_context: BlockContext,
389 /// The current unsafe block in scope
390 in_scope_unsafe: Safety,
392 /// The vector of all scopes that we have created thus far;
393 /// we track this for debuginfo later.
394 source_scopes: IndexVec<SourceScope, SourceScopeData<'tcx>>,
395 source_scope: SourceScope,
397 /// The guard-context: each time we build the guard expression for
398 /// a match arm, we push onto this stack, and then pop when we
399 /// finish building it.
400 guard_context: Vec<GuardFrame>,
402 /// Maps `HirId`s of variable bindings to the `Local`s created for them.
403 /// (A match binding can have two locals; the 2nd is for the arm's guard.)
404 var_indices: FxHashMap<LocalVarId, LocalsForNode>,
405 local_decls: IndexVec<Local, LocalDecl<'tcx>>,
406 canonical_user_type_annotations: ty::CanonicalUserTypeAnnotations<'tcx>,
407 upvar_mutbls: Vec<Mutability>,
408 unit_temp: Option<Place<'tcx>>,
410 var_debug_info: Vec<VarDebugInfo<'tcx>>,
413 impl<'a, 'tcx> Builder<'a, 'tcx> {
414 fn is_bound_var_in_guard(&self, id: LocalVarId) -> bool {
415 self.guard_context.iter().any(|frame| frame.locals.iter().any(|local| local.id == id))
418 fn var_local_id(&self, id: LocalVarId, for_guard: ForGuard) -> Local {
419 self.var_indices[&id].local_id(for_guard)
427 fn push(&mut self, bf: BlockFrame) {
430 fn pop(&mut self) -> Option<BlockFrame> {
434 /// Traverses the frames on the `BlockContext`, searching for either
435 /// the first block-tail expression frame with no intervening
438 /// Notably, this skips over `SubExpr` frames; this method is
439 /// meant to be used in the context of understanding the
440 /// relationship of a temp (created within some complicated
441 /// expression) with its containing expression, and whether the
442 /// value of that *containing expression* (not the temp!) is
444 fn currently_in_block_tail(&self) -> Option<BlockTailInfo> {
445 for bf in self.0.iter().rev() {
447 BlockFrame::SubExpr => continue,
448 BlockFrame::Statement { .. } => break,
449 &BlockFrame::TailExpr { tail_result_is_ignored, span } => {
450 return Some(BlockTailInfo { tail_result_is_ignored, span });
458 /// Looks at the topmost frame on the BlockContext and reports
459 /// whether its one that would discard a block tail result.
461 /// Unlike `currently_within_ignored_tail_expression`, this does
462 /// *not* skip over `SubExpr` frames: here, we want to know
463 /// whether the block result itself is discarded.
464 fn currently_ignores_tail_results(&self) -> bool {
465 match self.0.last() {
466 // no context: conservatively assume result is read
469 // sub-expression: block result feeds into some computation
470 Some(BlockFrame::SubExpr) => false,
472 // otherwise: use accumulated is_ignored state.
474 BlockFrame::TailExpr { tail_result_is_ignored: ignored, .. }
475 | BlockFrame::Statement { ignores_expr_result: ignored },
483 /// In the usual case, a `HirId` for an identifier maps to at most
484 /// one `Local` declaration.
487 /// The exceptional case is identifiers in a match arm's pattern
488 /// that are referenced in a guard of that match arm. For these,
489 /// we have `2` Locals.
491 /// * `for_arm_body` is the Local used in the arm body (which is
492 /// just like the `One` case above),
494 /// * `ref_for_guard` is the Local used in the arm's guard (which
495 /// is a reference to a temp that is an alias of
497 ForGuard { ref_for_guard: Local, for_arm_body: Local },
501 struct GuardFrameLocal {
505 impl GuardFrameLocal {
506 fn new(id: LocalVarId, _binding_mode: BindingMode) -> Self {
507 GuardFrameLocal { id }
513 /// These are the id's of names that are bound by patterns of the
514 /// arm of *this* guard.
516 /// (Frames higher up the stack will have the id's bound in arms
517 /// further out, such as in a case like:
520 /// P1(id1) if (... (match E2 { P2(id2) if ... => B2 })) => B1,
523 /// here, when building for FIXME.
524 locals: Vec<GuardFrameLocal>,
527 /// `ForGuard` indicates whether we are talking about:
528 /// 1. The variable for use outside of guard expressions, or
529 /// 2. The temp that holds reference to (1.), which is actually what the
530 /// guard expressions see.
531 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
538 fn local_id(&self, for_guard: ForGuard) -> Local {
539 match (self, for_guard) {
540 (&LocalsForNode::One(local_id), ForGuard::OutsideGuard)
542 &LocalsForNode::ForGuard { ref_for_guard: local_id, .. },
543 ForGuard::RefWithinGuard,
545 | (&LocalsForNode::ForGuard { for_arm_body: local_id, .. }, ForGuard::OutsideGuard) => {
549 (&LocalsForNode::One(_), ForGuard::RefWithinGuard) => {
550 bug!("anything with one local should never be within a guard.")
557 basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
560 rustc_index::newtype_index! {
561 struct ScopeId { .. }
565 enum NeedsTemporary {
566 /// Use this variant when whatever you are converting with `as_operand`
567 /// is the last thing you are converting. This means that if we introduced
568 /// an intermediate temporary, we'd only read it immediately after, so we can
571 /// For all cases where you aren't sure or that are too expensive to compute
572 /// for now. It is always safe to fall back to this.
576 ///////////////////////////////////////////////////////////////////////////
577 /// The `BlockAnd` "monad" packages up the new basic block along with a
578 /// produced value (sometimes just unit, of course). The `unpack!`
579 /// macro (and methods below) makes working with `BlockAnd` much more
582 #[must_use = "if you don't use one of these results, you're leaving a dangling edge"]
583 struct BlockAnd<T>(BasicBlock, T);
585 trait BlockAndExtension {
586 fn and<T>(self, v: T) -> BlockAnd<T>;
587 fn unit(self) -> BlockAnd<()>;
590 impl BlockAndExtension for BasicBlock {
591 fn and<T>(self, v: T) -> BlockAnd<T> {
595 fn unit(self) -> BlockAnd<()> {
600 /// Update a block pointer and return the value.
601 /// Use it like `let x = unpack!(block = self.foo(block, foo))`.
602 macro_rules! unpack {
603 ($x:ident = $c:expr) => {{
604 let BlockAnd(b, v) = $c;
610 let BlockAnd(b, ()) = $c;
615 ///////////////////////////////////////////////////////////////////////////
616 /// the main entry point for building MIR for a function
618 struct ArgInfo<'tcx>(
621 Option<&'tcx hir::Param<'tcx>>,
622 Option<ImplicitSelfKind>,
625 fn construct_fn<'tcx, A>(
627 infcx: &InferCtxt<'_, 'tcx>,
628 fn_def: ty::WithOptConstParam<LocalDefId>,
634 return_ty_span: Span,
635 body: &'tcx hir::Body<'tcx>,
637 span_with_body: Span,
640 A: Iterator<Item = ArgInfo<'tcx>>,
642 let arguments: Vec<_> = arguments.collect();
645 let span = tcx.hir().span(fn_id);
647 let mut builder = Builder::new(
660 let call_site_scope =
661 region::Scope { id: body.value.hir_id.local_id, data: region::ScopeData::CallSite };
663 region::Scope { id: body.value.hir_id.local_id, data: region::ScopeData::Arguments };
664 let source_info = builder.source_info(span);
665 let call_site_s = (call_site_scope, source_info);
666 unpack!(builder.in_scope(call_site_s, LintLevel::Inherited, |builder| {
667 let arg_scope_s = (arg_scope, source_info);
668 // Attribute epilogue to function's closing brace
669 let fn_end = span_with_body.shrink_to_hi();
671 unpack!(builder.in_breakable_scope(None, Place::return_place(), fn_end, |builder| {
672 Some(builder.in_scope(arg_scope_s, LintLevel::Inherited, |builder| {
673 builder.args_and_body(
675 fn_def.did.to_def_id(),
682 let source_info = builder.source_info(fn_end);
683 builder.cfg.terminate(return_block, source_info, TerminatorKind::Return);
684 builder.build_drop_trees();
688 let spread_arg = if abi == Abi::RustCall {
689 // RustCall pseudo-ABI untuples the last argument.
690 Some(Local::new(arguments.len()))
695 let mut body = builder.finish();
696 body.spread_arg = spread_arg;
700 fn construct_const<'a, 'tcx>(
701 thir: &'a Thir<'tcx>,
702 infcx: &'a InferCtxt<'a, 'tcx>,
704 def: ty::WithOptConstParam<LocalDefId>,
710 let span = tcx.hir().span(hir_id);
711 let mut builder = Builder::new(
724 let mut block = START_BLOCK;
725 unpack!(block = builder.expr_into_dest(Place::return_place(), block, &thir[expr]));
727 let source_info = builder.source_info(span);
728 builder.cfg.terminate(block, source_info, TerminatorKind::Return);
730 builder.build_drop_trees();
735 /// Construct MIR for an item that has had errors in type checking.
737 /// This is required because we may still want to run MIR passes on an item
738 /// with type errors, but normal MIR construction can't handle that in general.
739 fn construct_error<'a, 'tcx>(
740 infcx: &'a InferCtxt<'a, 'tcx>,
741 def: ty::WithOptConstParam<LocalDefId>,
743 body_id: hir::BodyId,
744 body_owner_kind: hir::BodyOwnerKind,
745 err: ErrorGuaranteed,
748 let span = tcx.hir().span(hir_id);
749 let ty = tcx.ty_error();
750 let generator_kind = tcx.hir().body(body_id).generator_kind;
751 let num_params = match body_owner_kind {
752 hir::BodyOwnerKind::Fn => tcx.hir().fn_decl_by_hir_id(hir_id).unwrap().inputs.len(),
753 hir::BodyOwnerKind::Closure => {
754 if generator_kind.is_some() {
755 // Generators have an implicit `self` parameter *and* a possibly
756 // implicit resume parameter.
759 // The implicit self parameter adds another local in MIR.
760 1 + tcx.hir().fn_decl_by_hir_id(hir_id).unwrap().inputs.len()
763 hir::BodyOwnerKind::Const => 0,
764 hir::BodyOwnerKind::Static(_) => 0,
766 let mut cfg = CFG { basic_blocks: IndexVec::new() };
767 let mut source_scopes = IndexVec::new();
768 let mut local_decls = IndexVec::from_elem_n(LocalDecl::new(ty, span), 1);
770 cfg.start_new_block();
771 source_scopes.push(SourceScopeData {
775 inlined_parent_scope: None,
776 local_data: ClearCrossCrate::Set(SourceScopeLocalData {
778 safety: Safety::Safe,
781 let source_info = SourceInfo { span, scope: OUTERMOST_SOURCE_SCOPE };
783 // Some MIR passes will expect the number of parameters to match the
784 // function declaration.
785 for _ in 0..num_params {
786 local_decls.push(LocalDecl::with_source_info(ty, source_info));
788 cfg.terminate(START_BLOCK, source_info, TerminatorKind::Unreachable);
790 let mut body = Body::new(
791 MirSource::item(def.did.to_def_id()),
802 body.generator.as_mut().map(|gen| gen.yield_ty = Some(ty));
806 impl<'a, 'tcx> Builder<'a, 'tcx> {
808 thir: &'a Thir<'tcx>,
809 infcx: &'a InferCtxt<'a, 'tcx>,
810 def: ty::WithOptConstParam<LocalDefId>,
817 generator_kind: Option<GeneratorKind>,
818 ) -> Builder<'a, 'tcx> {
820 let attrs = tcx.hir().attrs(hir_id);
821 // Some functions always have overflow checks enabled,
822 // however, they may not get codegen'd, depending on
823 // the settings for the crate they are codegened in.
824 let mut check_overflow = tcx.sess.contains_name(attrs, sym::rustc_inherit_overflow_checks);
825 // Respect -C overflow-checks.
826 check_overflow |= tcx.sess.overflow_checks();
827 // Constants always need overflow checks.
828 check_overflow |= matches!(
829 tcx.hir().body_owner_kind(def.did),
830 hir::BodyOwnerKind::Const | hir::BodyOwnerKind::Static(_)
833 let lint_level = LintLevel::Explicit(hir_id);
834 let param_env = tcx.param_env(def.did);
835 let mut builder = Builder {
839 typeck_results: tcx.typeck_opt_const_arg(def),
840 region_scope_tree: tcx.region_scope_tree(def.did),
842 def_id: def.did.to_def_id(),
844 parent_module: tcx.parent_module(hir_id).to_def_id(),
846 cfg: CFG { basic_blocks: IndexVec::new() },
850 scopes: scope::Scopes::new(),
851 block_context: BlockContext::new(),
852 source_scopes: IndexVec::new(),
853 source_scope: OUTERMOST_SOURCE_SCOPE,
854 guard_context: vec![],
855 in_scope_unsafe: safety,
856 local_decls: IndexVec::from_elem_n(LocalDecl::new(return_ty, return_span), 1),
857 canonical_user_type_annotations: IndexVec::new(),
858 upvar_mutbls: vec![],
859 var_indices: Default::default(),
861 var_debug_info: vec![],
864 assert_eq!(builder.cfg.start_new_block(), START_BLOCK);
866 builder.new_source_scope(span, lint_level, Some(safety)),
867 OUTERMOST_SOURCE_SCOPE
869 builder.source_scopes[OUTERMOST_SOURCE_SCOPE].parent_scope = None;
874 fn finish(self) -> Body<'tcx> {
875 for (index, block) in self.cfg.basic_blocks.iter().enumerate() {
876 if block.terminator.is_none() {
877 span_bug!(self.fn_span, "no terminator on block {:?}", index);
882 MirSource::item(self.def_id),
883 self.cfg.basic_blocks,
886 self.canonical_user_type_annotations,
891 self.typeck_results.tainted_by_errors,
897 mut block: BasicBlock,
899 arguments: &[ArgInfo<'tcx>],
900 argument_scope: region::Scope,
903 // Allocate locals for the function arguments
904 for &ArgInfo(ty, _, arg_opt, _) in arguments.iter() {
906 SourceInfo::outermost(arg_opt.map_or(self.fn_span, |arg| arg.pat.span));
907 let arg_local = self.local_decls.push(LocalDecl::with_source_info(ty, source_info));
909 // If this is a simple binding pattern, give debuginfo a nice name.
910 if let Some(arg) = arg_opt && let Some(ident) = arg.pat.simple_ident() {
911 self.var_debug_info.push(VarDebugInfo {
914 value: VarDebugInfoContents::Place(arg_local.into()),
920 let tcx_hir = tcx.hir();
921 let hir_typeck_results = self.typeck_results;
923 // In analyze_closure() in upvar.rs we gathered a list of upvars used by an
924 // indexed closure and we stored in a map called closure_min_captures in TypeckResults
925 // with the closure's DefId. Here, we run through that vec of UpvarIds for
926 // the given closure and use the necessary information to create upvar
927 // debuginfo and to fill `self.upvar_mutbls`.
928 if hir_typeck_results.closure_min_captures.get(&fn_def_id).is_some() {
929 let mut closure_env_projs = vec![];
930 let mut closure_ty = self.local_decls[ty::CAPTURE_STRUCT_LOCAL].ty;
931 if let ty::Ref(_, ty, _) = closure_ty.kind() {
932 closure_env_projs.push(ProjectionElem::Deref);
935 let upvar_substs = match closure_ty.kind() {
936 ty::Closure(_, substs) => ty::UpvarSubsts::Closure(substs),
937 ty::Generator(_, substs, _) => ty::UpvarSubsts::Generator(substs),
938 _ => span_bug!(self.fn_span, "upvars with non-closure env ty {:?}", closure_ty),
940 let def_id = self.def_id.as_local().unwrap();
941 let capture_syms = tcx.symbols_for_closure_captures((def_id, fn_def_id));
942 let capture_tys = upvar_substs.upvar_tys();
943 let captures_with_tys = hir_typeck_results
944 .closure_min_captures_flattened(fn_def_id)
945 .zip(capture_tys.zip(capture_syms));
947 self.upvar_mutbls = captures_with_tys
949 .map(|(i, (captured_place, (ty, sym)))| {
950 let capture = captured_place.info.capture_kind;
951 let var_id = match captured_place.place.base {
952 HirPlaceBase::Upvar(upvar_id) => upvar_id.var_path.hir_id,
953 _ => bug!("Expected an upvar"),
956 let mutability = captured_place.mutability;
958 let mut projs = closure_env_projs.clone();
959 projs.push(ProjectionElem::Field(Field::new(i), ty));
961 ty::UpvarCapture::ByValue => {}
962 ty::UpvarCapture::ByRef(..) => {
963 projs.push(ProjectionElem::Deref);
967 self.var_debug_info.push(VarDebugInfo {
969 source_info: SourceInfo::outermost(tcx_hir.span(var_id)),
970 value: VarDebugInfoContents::Place(Place {
971 local: ty::CAPTURE_STRUCT_LOCAL,
972 projection: tcx.intern_place_elems(&projs),
981 let mut scope = None;
982 // Bind the argument patterns
983 for (index, arg_info) in arguments.iter().enumerate() {
984 // Function arguments always get the first Local indices after the return place
985 let local = Local::new(index + 1);
986 let place = Place::from(local);
987 let &ArgInfo(_, opt_ty_info, arg_opt, ref self_binding) = arg_info;
989 // Make sure we drop (parts of) the argument even when not matched on.
991 arg_opt.as_ref().map_or(expr.span, |arg| arg.pat.span),
997 let Some(arg) = arg_opt else {
1000 let pat = match tcx.hir().get(arg.pat.hir_id) {
1001 Node::Pat(pat) => pat,
1002 node => bug!("pattern became {:?}", node),
1004 let pattern = pat_from_hir(tcx, self.param_env, self.typeck_results, pat);
1005 let original_source_scope = self.source_scope;
1006 let span = pattern.span;
1007 self.set_correct_source_scope_for_arg(arg.hir_id, original_source_scope, span);
1008 match *pattern.kind {
1009 // Don't introduce extra copies for simple bindings
1013 mode: BindingMode::ByValue,
1017 self.local_decls[local].mutability = mutability;
1018 self.local_decls[local].source_info.scope = self.source_scope;
1019 self.local_decls[local].local_info = if let Some(kind) = self_binding {
1020 Some(Box::new(LocalInfo::User(ClearCrossCrate::Set(
1021 BindingForm::ImplicitSelf(*kind),
1024 let binding_mode = ty::BindingMode::BindByValue(mutability);
1025 Some(Box::new(LocalInfo::User(ClearCrossCrate::Set(BindingForm::Var(
1029 opt_match_place: Some((Some(place), span)),
1034 self.var_indices.insert(var, LocalsForNode::One(local));
1037 scope = self.declare_bindings(
1041 matches::ArmHasGuard(false),
1042 Some((Some(&place), span)),
1044 let place_builder = PlaceBuilder::from(local);
1045 unpack!(block = self.place_into_pattern(block, pattern, place_builder, false));
1048 self.source_scope = original_source_scope;
1051 // Enter the argument pattern bindings source scope, if it exists.
1052 if let Some(source_scope) = scope {
1053 self.source_scope = source_scope;
1056 self.expr_into_dest(Place::return_place(), block, &expr)
1059 fn set_correct_source_scope_for_arg(
1061 arg_hir_id: hir::HirId,
1062 original_source_scope: SourceScope,
1066 let current_root = tcx.maybe_lint_level_root_bounded(arg_hir_id, self.hir_id);
1067 let parent_root = tcx.maybe_lint_level_root_bounded(
1068 self.source_scopes[original_source_scope]
1071 .assert_crate_local()
1075 if current_root != parent_root {
1077 self.new_source_scope(pattern_span, LintLevel::Explicit(current_root), None);
1081 fn get_unit_temp(&mut self) -> Place<'tcx> {
1082 match self.unit_temp {
1085 let ty = self.tcx.mk_unit();
1086 let fn_span = self.fn_span;
1087 let tmp = self.temp(ty, fn_span);
1088 self.unit_temp = Some(tmp);
1095 fn parse_float_into_constval<'tcx>(
1097 float_ty: ty::FloatTy,
1099 ) -> Option<ConstValue<'tcx>> {
1100 parse_float_into_scalar(num, float_ty, neg).map(ConstValue::Scalar)
1103 pub(crate) fn parse_float_into_scalar(
1105 float_ty: ty::FloatTy,
1107 ) -> Option<Scalar> {
1108 let num = num.as_str();
1110 ty::FloatTy::F32 => {
1111 let Ok(rust_f) = num.parse::<f32>() else { return None };
1112 let mut f = num.parse::<Single>().unwrap_or_else(|e| {
1113 panic!("apfloat::ieee::Single failed to parse `{}`: {:?}", num, e)
1117 u128::from(rust_f.to_bits()) == f.to_bits(),
1118 "apfloat::ieee::Single gave different result for `{}`: \
1119 {}({:#x}) vs Rust's {}({:#x})",
1123 Single::from_bits(rust_f.to_bits().into()),
1131 Some(Scalar::from_f32(f))
1133 ty::FloatTy::F64 => {
1134 let Ok(rust_f) = num.parse::<f64>() else { return None };
1135 let mut f = num.parse::<Double>().unwrap_or_else(|e| {
1136 panic!("apfloat::ieee::Double failed to parse `{}`: {:?}", num, e)
1140 u128::from(rust_f.to_bits()) == f.to_bits(),
1141 "apfloat::ieee::Double gave different result for `{}`: \
1142 {}({:#x}) vs Rust's {}({:#x})",
1146 Double::from_bits(rust_f.to_bits().into()),
1154 Some(Scalar::from_f64(f))
1159 ///////////////////////////////////////////////////////////////////////////
1160 // Builder methods are broken up into modules, depending on what kind
1161 // of thing is being lowered. Note that they use the `unpack` macro
1162 // above extensively.
1171 pub(crate) use expr::category::Category as ExprCategory;