1use itertools::Itertools;
24use rustc_abi::{ExternAbi, FieldIdx};
25use rustc_apfloat::Float;
26use rustc_apfloat::ieee::{Double, Half, Quad, Single};
27use rustc_data_structures::fx::FxHashMap;
28use rustc_data_structures::sorted_map::SortedIndexMultiMap;
29use rustc_errors::ErrorGuaranteed;
30use rustc_hir::def::DefKind;
31use rustc_hir::def_id::LocalDefId;
32use rustc_hir::{self as hir, BindingMode, ByRef, HirId, ItemLocalId, Node, find_attr};
33use rustc_index::bit_set::GrowableBitSet;
34use rustc_index::{Idx, IndexSlice, IndexVec};
35use rustc_infer::infer::{InferCtxt, TyCtxtInferExt};
36use rustc_middle::hir::place::PlaceBase as HirPlaceBase;
37use rustc_middle::middle::region;
38use rustc_middle::mir::*;
39use rustc_middle::thir::{self, ExprId, LocalVarId, Param, ParamId, PatKind, Thir};
40use rustc_middle::ty::{self, ScalarInt, Ty, TyCtxt, TypeVisitableExt, TypingMode};
41use rustc_middle::{bug, span_bug};
42use rustc_span::{Span, Symbol};
43
44use crate::builder::expr::as_place::PlaceBuilder;
45use crate::builder::scope::LintLevel;
46
47pub(crate) fn closure_saved_names_of_captured_variables<'tcx>(
48 tcx: TyCtxt<'tcx>,
49 def_id: LocalDefId,
50) -> IndexVec<FieldIdx, Symbol> {
51 tcx.closure_captures(def_id)
52 .iter()
53 .map(|captured_place| {
54 let name = captured_place.to_symbol();
55 match captured_place.info.capture_kind {
56 ty::UpvarCapture::ByValue | ty::UpvarCapture::ByUse => name,
57 ty::UpvarCapture::ByRef(..) => Symbol::intern(&::alloc::__export::must_use({
::alloc::fmt::format(format_args!("_ref__{0}", name))
})format!("_ref__{name}")),
58 }
59 })
60 .collect()
61}
62
63pub(crate) fn build_mir_inner_impl<'tcx>(tcx: TyCtxt<'tcx>, def: LocalDefId) -> Body<'tcx> {
68 tcx.ensure_done().thir_abstract_const(def);
69 if let Err(e) = tcx.ensure_result().check_match(def) {
70 return construct_error(tcx, def, e);
71 }
72
73 if let Err(err) = tcx.ensure_result().check_tail_calls(def) {
74 return construct_error(tcx, def, err);
75 }
76
77 let body = match tcx.thir_body(def) {
78 Err(error_reported) => construct_error(tcx, def, error_reported),
79 Ok((thir, expr)) => {
80 let build_mir = |thir: &Thir<'tcx>| match thir.body_type {
81 thir::BodyTy::Fn(fn_sig) => construct_fn(tcx, def, thir, expr, fn_sig),
82 thir::BodyTy::Const(ty) | thir::BodyTy::GlobalAsm(ty) => {
83 construct_const(tcx, def, thir, expr, ty)
84 }
85 };
86
87 build_mir(&thir.borrow())
91 }
92 };
93
94 if true {
if !!(body.local_decls.has_free_regions() ||
body.basic_blocks.has_free_regions() ||
body.var_debug_info.has_free_regions() ||
body.yield_ty().has_free_regions()) {
{
::core::panicking::panic_fmt(format_args!("Unexpected free regions in MIR: {0:?}",
body));
}
};
};debug_assert!(
99 !(body.local_decls.has_free_regions()
100 || body.basic_blocks.has_free_regions()
101 || body.var_debug_info.has_free_regions()
102 || body.yield_ty().has_free_regions()),
103 "Unexpected free regions in MIR: {body:?}",
104 );
105
106 body
107}
108
109#[derive(#[automatically_derived]
impl ::core::fmt::Debug for BlockFrame {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
BlockFrame::Statement { ignores_expr_result: __self_0 } =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"Statement", "ignores_expr_result", &__self_0),
BlockFrame::TailExpr { info: __self_0 } =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"TailExpr", "info", &__self_0),
BlockFrame::SubExpr =>
::core::fmt::Formatter::write_str(f, "SubExpr"),
}
}
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for BlockFrame {
#[inline]
fn eq(&self, other: &BlockFrame) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr &&
match (self, other) {
(BlockFrame::Statement { ignores_expr_result: __self_0 },
BlockFrame::Statement { ignores_expr_result: __arg1_0 }) =>
__self_0 == __arg1_0,
(BlockFrame::TailExpr { info: __self_0 },
BlockFrame::TailExpr { info: __arg1_0 }) =>
__self_0 == __arg1_0,
_ => true,
}
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for BlockFrame {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<bool>;
let _: ::core::cmp::AssertParamIsEq<BlockTailInfo>;
}
}Eq)]
113enum BlockFrame {
114 Statement {
121 ignores_expr_result: bool,
124 },
125
126 TailExpr { info: BlockTailInfo },
130
131 SubExpr,
136}
137
138impl BlockFrame {
139 fn is_tail_expr(&self) -> bool {
140 match *self {
141 BlockFrame::TailExpr { .. } => true,
142
143 BlockFrame::Statement { .. } | BlockFrame::SubExpr => false,
144 }
145 }
146 fn is_statement(&self) -> bool {
147 match *self {
148 BlockFrame::Statement { .. } => true,
149
150 BlockFrame::TailExpr { .. } | BlockFrame::SubExpr => false,
151 }
152 }
153}
154
155#[derive(#[automatically_derived]
impl ::core::fmt::Debug for BlockContext {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_tuple_field1_finish(f, "BlockContext",
&&self.0)
}
}Debug)]
156struct BlockContext(Vec<BlockFrame>);
157
158struct Builder<'a, 'tcx> {
159 tcx: TyCtxt<'tcx>,
160 infcx: InferCtxt<'tcx>,
165 region_scope_tree: &'tcx region::ScopeTree,
166 param_env: ty::ParamEnv<'tcx>,
167
168 thir: &'a Thir<'tcx>,
169 cfg: CFG<'tcx>,
170
171 def_id: LocalDefId,
172 hir_id: HirId,
173 check_overflow: bool,
174 fn_span: Span,
175 arg_count: usize,
176 coroutine: Option<Box<CoroutineInfo<'tcx>>>,
177
178 scopes: scope::Scopes<'tcx>,
181
182 block_context: BlockContext,
195
196 source_scopes: IndexVec<SourceScope, SourceScopeData<'tcx>>,
199 source_scope: SourceScope,
200
201 guard_context: Vec<GuardFrame>,
205
206 fixed_temps: FxHashMap<ExprId, Local>,
209 fixed_temps_scope: Option<region::Scope>,
211
212 var_indices: FxHashMap<LocalVarId, LocalsForNode>,
215 local_decls: IndexVec<Local, LocalDecl<'tcx>>,
216 canonical_user_type_annotations: ty::CanonicalUserTypeAnnotations<'tcx>,
217 upvars: CaptureMap<'tcx>,
218 unit_temp: Option<Place<'tcx>>,
219
220 var_debug_info: Vec<VarDebugInfo<'tcx>>,
221
222 lint_level_roots_cache: GrowableBitSet<hir::ItemLocalId>,
229
230 coverage_info: Option<coverageinfo::CoverageInfoBuilder>,
233}
234
235type CaptureMap<'tcx> = SortedIndexMultiMap<usize, ItemLocalId, Capture<'tcx>>;
236
237#[derive(#[automatically_derived]
impl<'tcx> ::core::fmt::Debug for Capture<'tcx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field3_finish(f, "Capture",
"captured_place", &self.captured_place, "use_place",
&self.use_place, "mutability", &&self.mutability)
}
}Debug)]
238struct Capture<'tcx> {
239 captured_place: &'tcx ty::CapturedPlace<'tcx>,
240 use_place: Place<'tcx>,
241 mutability: Mutability,
242}
243
244impl<'a, 'tcx> Builder<'a, 'tcx> {
245 fn typing_env(&self) -> ty::TypingEnv<'tcx> {
246 self.infcx.typing_env(self.param_env)
247 }
248
249 fn is_bound_var_in_guard(&self, id: LocalVarId) -> bool {
250 self.guard_context.iter().any(|frame| frame.locals.iter().any(|local| local.id == id))
251 }
252
253 fn var_local_id(&self, id: LocalVarId, for_guard: ForGuard) -> Local {
254 self.var_indices[&id].local_id(for_guard)
255 }
256}
257
258impl BlockContext {
259 fn new() -> Self {
260 BlockContext(::alloc::vec::Vec::new()vec![])
261 }
262 fn push(&mut self, bf: BlockFrame) {
263 self.0.push(bf);
264 }
265 fn pop(&mut self) -> Option<BlockFrame> {
266 self.0.pop()
267 }
268
269 fn currently_in_block_tail(&self) -> Option<BlockTailInfo> {
280 for bf in self.0.iter().rev() {
281 match bf {
282 BlockFrame::SubExpr => continue,
283 BlockFrame::Statement { .. } => break,
284 &BlockFrame::TailExpr { info } => return Some(info),
285 }
286 }
287
288 None
289 }
290
291 fn currently_ignores_tail_results(&self) -> bool {
298 match self.0.last() {
299 None => false,
301
302 Some(BlockFrame::SubExpr) => false,
304
305 Some(
307 BlockFrame::TailExpr { info: BlockTailInfo { tail_result_is_ignored: ign, .. } }
308 | BlockFrame::Statement { ignores_expr_result: ign },
309 ) => *ign,
310 }
311 }
312}
313
314#[derive(#[automatically_derived]
impl ::core::fmt::Debug for LocalsForNode {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
LocalsForNode::One(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "One",
&__self_0),
LocalsForNode::ForGuard {
ref_for_guard: __self_0, for_arm_body: __self_1 } =>
::core::fmt::Formatter::debug_struct_field2_finish(f,
"ForGuard", "ref_for_guard", __self_0, "for_arm_body",
&__self_1),
}
}
}Debug)]
315enum LocalsForNode {
316 One(Local),
319
320 ForGuard { ref_for_guard: Local, for_arm_body: Local },
331}
332
333#[derive(#[automatically_derived]
impl ::core::fmt::Debug for GuardFrameLocal {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field1_finish(f,
"GuardFrameLocal", "id", &&self.id)
}
}Debug)]
334struct GuardFrameLocal {
335 id: LocalVarId,
336}
337
338impl GuardFrameLocal {
339 fn new(id: LocalVarId) -> Self {
340 GuardFrameLocal { id }
341 }
342}
343
344#[derive(#[automatically_derived]
impl ::core::fmt::Debug for GuardFrame {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field1_finish(f, "GuardFrame",
"locals", &&self.locals)
}
}Debug)]
345struct GuardFrame {
346 locals: Vec<GuardFrameLocal>,
358}
359
360#[derive(#[automatically_derived]
impl ::core::marker::Copy for ForGuard { }Copy, #[automatically_derived]
impl ::core::clone::Clone for ForGuard {
#[inline]
fn clone(&self) -> ForGuard { *self }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for ForGuard {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
ForGuard::RefWithinGuard => "RefWithinGuard",
ForGuard::OutsideGuard => "OutsideGuard",
})
}
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for ForGuard {
#[inline]
fn eq(&self, other: &ForGuard) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for ForGuard {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {}
}Eq)]
365enum ForGuard {
366 RefWithinGuard,
367 OutsideGuard,
368}
369
370impl LocalsForNode {
371 fn local_id(&self, for_guard: ForGuard) -> Local {
372 match (self, for_guard) {
373 (&LocalsForNode::One(local_id), ForGuard::OutsideGuard)
374 | (
375 &LocalsForNode::ForGuard { ref_for_guard: local_id, .. },
376 ForGuard::RefWithinGuard,
377 )
378 | (&LocalsForNode::ForGuard { for_arm_body: local_id, .. }, ForGuard::OutsideGuard) => {
379 local_id
380 }
381
382 (&LocalsForNode::One(_), ForGuard::RefWithinGuard) => {
383 ::rustc_middle::util::bug::bug_fmt(format_args!("anything with one local should never be within a guard."))bug!("anything with one local should never be within a guard.")
384 }
385 }
386 }
387}
388
389struct CFG<'tcx> {
390 basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
391}
392
393impl ::std::fmt::Debug for ScopeId {
fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
fmt.write_fmt(format_args!("{0}", self.as_u32()))
}
}rustc_index::newtype_index! {
394 struct ScopeId {}
395}
396
397#[derive(#[automatically_derived]
impl ::core::fmt::Debug for NeedsTemporary {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
NeedsTemporary::No => "No",
NeedsTemporary::Maybe => "Maybe",
})
}
}Debug)]
398enum NeedsTemporary {
399 No,
404 Maybe,
407}
408
409#[must_use = "if you don't use one of these results, you're leaving a dangling edge"]
414struct BlockAnd<T>(BasicBlock, T);
415
416impl BlockAnd<()> {
417 #[must_use]
419 fn into_block(self) -> BasicBlock {
420 let Self(block, ()) = self;
421 block
422 }
423}
424
425trait BlockAndExtension {
426 fn and<T>(self, v: T) -> BlockAnd<T>;
427 fn unit(self) -> BlockAnd<()>;
428}
429
430impl BlockAndExtension for BasicBlock {
431 fn and<T>(self, v: T) -> BlockAnd<T> {
432 BlockAnd(self, v)
433 }
434
435 fn unit(self) -> BlockAnd<()> {
436 BlockAnd(self, ())
437 }
438}
439
440macro_rules! unpack {
443 ($x:ident = $c:expr) => {{
444 let BlockAnd(b, v) = $c;
445 $x = b;
446 v
447 }};
448}
449
450fn construct_fn<'tcx>(
452 tcx: TyCtxt<'tcx>,
453 fn_def: LocalDefId,
454 thir: &Thir<'tcx>,
455 expr: ExprId,
456 fn_sig: ty::FnSig<'tcx>,
457) -> Body<'tcx> {
458 let span = tcx.def_span(fn_def);
459 let fn_id = tcx.local_def_id_to_hir_id(fn_def);
460
461 let body = tcx.hir_body_owned_by(fn_def);
463 let span_with_body = tcx.hir_span_with_body(fn_id);
464 let return_ty_span = tcx
465 .hir_fn_decl_by_hir_id(fn_id)
466 .unwrap_or_else(|| ::rustc_middle::util::bug::span_bug_fmt(span,
format_args!("can\'t build MIR for {0:?}", fn_def))span_bug!(span, "can't build MIR for {:?}", fn_def))
467 .output
468 .span();
469
470 let mut abi = fn_sig.abi();
471 if let DefKind::Closure = tcx.def_kind(fn_def) {
472 abi = ExternAbi::Rust;
475 }
476
477 let arguments = &thir.params;
478
479 let return_ty = fn_sig.output();
480 let coroutine = match tcx.type_of(fn_def).instantiate_identity().skip_norm_wip().kind() {
481 ty::Coroutine(_, args) => Some(Box::new(CoroutineInfo::initial(
482 tcx.coroutine_kind(fn_def).unwrap(),
483 args.as_coroutine().yield_ty(),
484 args.as_coroutine().resume_ty(),
485 ))),
486 ty::Closure(..) | ty::CoroutineClosure(..) | ty::FnDef(..) => None,
487 ty => ::rustc_middle::util::bug::span_bug_fmt(span_with_body,
format_args!("unexpected type of body: {0:?}", ty))span_bug!(span_with_body, "unexpected type of body: {ty:?}"),
488 };
489
490 if let Some((dialect, phase)) =
491 {
{
'done:
{
for i in ::rustc_hir::attrs::HasAttrs::get_attrs(fn_id, &tcx) {
#[allow(unused_imports)]
use rustc_hir::attrs::AttributeKind::*;
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(CustomMir(dialect, phase)) => {
break 'done Some((dialect, phase));
}
rustc_hir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}find_attr!(tcx, fn_id, CustomMir(dialect, phase) => (dialect, phase))
492 {
493 return custom::build_custom_mir(
494 tcx,
495 fn_def.to_def_id(),
496 fn_id,
497 thir,
498 expr,
499 arguments,
500 return_ty,
501 return_ty_span,
502 span_with_body,
503 dialect.as_ref().map(|(d, _)| *d),
504 phase.as_ref().map(|(p, _)| *p),
505 );
506 }
507
508 let typing_mode = if tcx.use_typing_mode_post_typeck_until_borrowck() {
509 TypingMode::borrowck(tcx, fn_def)
510 } else {
511 TypingMode::non_body_analysis()
514 };
515
516 let infcx = tcx.infer_ctxt().build(typing_mode);
517 let mut builder = Builder::new(
518 thir,
519 infcx,
520 fn_def,
521 fn_id,
522 span_with_body,
523 arguments.len(),
524 return_ty,
525 return_ty_span,
526 coroutine,
527 );
528
529 let call_site_scope =
530 region::Scope { local_id: body.id().hir_id.local_id, data: region::ScopeData::CallSite };
531 let arg_scope =
532 region::Scope { local_id: body.id().hir_id.local_id, data: region::ScopeData::Arguments };
533 let source_info = builder.source_info(span);
534 let call_site_s = (call_site_scope, source_info);
535 let _: BlockAnd<()> = builder.in_scope(call_site_s, LintLevel::Inherited, |builder| {
536 let arg_scope_s = (arg_scope, source_info);
537 let fn_end = span_with_body.shrink_to_hi();
539 let return_block = builder
540 .in_breakable_scope(None, Place::return_place(), fn_end, |builder| {
541 Some(builder.in_scope(arg_scope_s, LintLevel::Inherited, |builder| {
542 builder.args_and_body(START_BLOCK, arguments, arg_scope, expr)
543 }))
544 })
545 .into_block();
546 let source_info = builder.source_info(fn_end);
547 builder.cfg.terminate(return_block, source_info, TerminatorKind::Return);
548 builder.build_drop_trees();
549 return_block.unit()
550 });
551
552 let mut body = builder.finish();
553
554 body.spread_arg = if abi == ExternAbi::RustCall {
555 Some(Local::new(arguments.len()))
558 } else {
559 None
560 };
561
562 body
563}
564
565fn construct_const<'a, 'tcx>(
566 tcx: TyCtxt<'tcx>,
567 def: LocalDefId,
568 thir: &'a Thir<'tcx>,
569 expr: ExprId,
570 const_ty: Ty<'tcx>,
571) -> Body<'tcx> {
572 let hir_id = tcx.local_def_id_to_hir_id(def);
573
574 let (span, const_ty_span) = match tcx.hir_node(hir_id) {
576 Node::Item(hir::Item {
577 kind: hir::ItemKind::Static(_, _, ty, _) | hir::ItemKind::Const(_, _, ty, _),
578 span,
579 ..
580 })
581 | Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Const(ty, _), span, .. })
582 | Node::TraitItem(hir::TraitItem {
583 kind: hir::TraitItemKind::Const(ty, Some(_)),
584 span,
585 ..
586 }) => (*span, ty.span),
587 Node::AnonConst(ct) => (ct.span, ct.span),
588 Node::ConstBlock(_) => {
589 let span = tcx.def_span(def);
590 (span, span)
591 }
592 Node::Item(hir::Item { kind: hir::ItemKind::GlobalAsm { .. }, span, .. }) => (*span, *span),
593 _ => ::rustc_middle::util::bug::span_bug_fmt(tcx.def_span(def),
format_args!("can\'t build MIR for {0:?}", def))span_bug!(tcx.def_span(def), "can't build MIR for {:?}", def),
594 };
595
596 let typing_mode = if tcx.use_typing_mode_post_typeck_until_borrowck() {
597 TypingMode::borrowck(tcx, def)
598 } else {
599 TypingMode::non_body_analysis()
602 };
603
604 let infcx = tcx.infer_ctxt().build(typing_mode);
605 let mut builder =
606 Builder::new(thir, infcx, def, hir_id, span, 0, const_ty, const_ty_span, None);
607
608 let mut block = START_BLOCK;
609 block = builder.expr_into_dest(Place::return_place(), block, expr).into_block();
610
611 let source_info = builder.source_info(span);
612 builder.cfg.terminate(block, source_info, TerminatorKind::Return);
613
614 builder.build_drop_trees();
615 builder.finish()
616}
617
618fn construct_error(tcx: TyCtxt<'_>, def_id: LocalDefId, guar: ErrorGuaranteed) -> Body<'_> {
623 let span = tcx.def_span(def_id);
624 let hir_id = tcx.local_def_id_to_hir_id(def_id);
625
626 let (inputs, output, coroutine) = match tcx.def_kind(def_id) {
627 DefKind::Const { .. }
628 | DefKind::AssocConst { .. }
629 | DefKind::AnonConst
630 | DefKind::Static { .. }
631 | DefKind::GlobalAsm => {
632 (::alloc::vec::Vec::new()vec![], tcx.type_of(def_id).instantiate_identity().skip_norm_wip(), None)
633 }
634 DefKind::Ctor(..) | DefKind::Fn | DefKind::AssocFn => {
635 let sig = tcx.liberate_late_bound_regions(
636 def_id.to_def_id(),
637 tcx.fn_sig(def_id).instantiate_identity().skip_norm_wip(),
638 );
639 (sig.inputs().to_vec(), sig.output(), None)
640 }
641 DefKind::Closure => {
642 let closure_ty = tcx.type_of(def_id).instantiate_identity().skip_norm_wip();
643 match closure_ty.kind() {
644 ty::Closure(_, args) => {
645 let args = args.as_closure();
646 let sig = tcx.liberate_late_bound_regions(def_id.to_def_id(), args.sig());
647 let self_ty = match args.kind() {
648 ty::ClosureKind::Fn => {
649 Ty::new_imm_ref(tcx, tcx.lifetimes.re_erased, closure_ty)
650 }
651 ty::ClosureKind::FnMut => {
652 Ty::new_mut_ref(tcx, tcx.lifetimes.re_erased, closure_ty)
653 }
654 ty::ClosureKind::FnOnce => closure_ty,
655 };
656 (
657 [self_ty].into_iter().chain(sig.inputs()[0].tuple_fields()).collect(),
658 sig.output(),
659 None,
660 )
661 }
662 ty::Coroutine(_, args) => {
663 let args = args.as_coroutine();
664 let resume_ty = args.resume_ty();
665 let yield_ty = args.yield_ty();
666 let return_ty = args.return_ty();
667 (
668 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[closure_ty, resume_ty]))vec![closure_ty, resume_ty],
669 return_ty,
670 Some(Box::new(CoroutineInfo::initial(
671 tcx.coroutine_kind(def_id).unwrap(),
672 yield_ty,
673 resume_ty,
674 ))),
675 )
676 }
677 ty::CoroutineClosure(did, args) => {
678 let args = args.as_coroutine_closure();
679 let sig = tcx.liberate_late_bound_regions(
680 def_id.to_def_id(),
681 args.coroutine_closure_sig(),
682 );
683 let self_ty = match args.kind() {
684 ty::ClosureKind::Fn => {
685 Ty::new_imm_ref(tcx, tcx.lifetimes.re_erased, closure_ty)
686 }
687 ty::ClosureKind::FnMut => {
688 Ty::new_mut_ref(tcx, tcx.lifetimes.re_erased, closure_ty)
689 }
690 ty::ClosureKind::FnOnce => closure_ty,
691 };
692 (
693 [self_ty].into_iter().chain(sig.tupled_inputs_ty.tuple_fields()).collect(),
694 sig.to_coroutine(
695 tcx,
696 args.parent_args(),
697 args.kind_ty(),
698 tcx.coroutine_for_closure(*did),
699 Ty::new_error(tcx, guar),
700 ),
701 None,
702 )
703 }
704 ty::Error(_) => (::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[closure_ty, closure_ty]))vec![closure_ty, closure_ty], closure_ty, None),
705 kind => {
706 ::rustc_middle::util::bug::span_bug_fmt(span,
format_args!("expected type of closure body to be a closure or coroutine, got {0:?}",
kind));span_bug!(
707 span,
708 "expected type of closure body to be a closure or coroutine, got {kind:?}"
709 );
710 }
711 }
712 }
713 dk => ::rustc_middle::util::bug::span_bug_fmt(span,
format_args!("{0:?} is not a body: {1:?}", def_id, dk))span_bug!(span, "{:?} is not a body: {:?}", def_id, dk),
714 };
715
716 let source_info = SourceInfo { span, scope: OUTERMOST_SOURCE_SCOPE };
717 let local_decls = IndexVec::from_iter(
718 [output].iter().chain(&inputs).map(|ty| LocalDecl::with_source_info(*ty, source_info)),
719 );
720 let mut cfg = CFG { basic_blocks: IndexVec::new() };
721 let mut source_scopes = IndexVec::new();
722
723 cfg.start_new_block();
724 source_scopes.push(SourceScopeData {
725 span,
726 parent_scope: None,
727 inlined: None,
728 inlined_parent_scope: None,
729 local_data: ClearCrossCrate::Set(SourceScopeLocalData { lint_root: hir_id }),
730 });
731
732 cfg.terminate(START_BLOCK, source_info, TerminatorKind::Unreachable);
733
734 Body::new(
735 MirSource::item(def_id.to_def_id()),
736 cfg.basic_blocks,
737 source_scopes,
738 local_decls,
739 IndexVec::new(),
740 inputs.len(),
741 ::alloc::vec::Vec::new()vec![],
742 span,
743 coroutine,
744 Some(guar),
745 )
746}
747
748impl<'a, 'tcx> Builder<'a, 'tcx> {
749 fn new(
750 thir: &'a Thir<'tcx>,
751 infcx: InferCtxt<'tcx>,
752 def: LocalDefId,
753 hir_id: HirId,
754 span: Span,
755 arg_count: usize,
756 return_ty: Ty<'tcx>,
757 return_span: Span,
758 coroutine: Option<Box<CoroutineInfo<'tcx>>>,
759 ) -> Builder<'a, 'tcx> {
760 let tcx = infcx.tcx;
761 let mut check_overflow = {
{
'done:
{
for i in tcx.hir_attrs(hir_id) {
#[allow(unused_imports)]
use rustc_hir::attrs::AttributeKind::*;
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(RustcInheritOverflowChecks) =>
{
break 'done Some(());
}
rustc_hir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}.is_some()
}find_attr!(tcx.hir_attrs(hir_id), RustcInheritOverflowChecks);
765 check_overflow |= tcx.sess.overflow_checks();
767 check_overflow |= #[allow(non_exhaustive_omitted_patterns)] match tcx.hir_body_owner_kind(def) {
hir::BodyOwnerKind::Const { .. } | hir::BodyOwnerKind::Static(_) => true,
_ => false,
}matches!(
769 tcx.hir_body_owner_kind(def),
770 hir::BodyOwnerKind::Const { .. } | hir::BodyOwnerKind::Static(_)
771 );
772
773 let lint_level = LintLevel::Explicit(hir_id);
774 let param_env = tcx.param_env(def);
775 let mut builder = Builder {
776 thir,
777 tcx,
778 infcx,
779 region_scope_tree: tcx.region_scope_tree(def),
780 param_env,
781 def_id: def,
782 hir_id,
783 check_overflow,
784 cfg: CFG { basic_blocks: IndexVec::new() },
785 fn_span: span,
786 arg_count,
787 coroutine,
788 scopes: scope::Scopes::new(),
789 block_context: BlockContext::new(),
790 source_scopes: IndexVec::new(),
791 source_scope: OUTERMOST_SOURCE_SCOPE,
792 guard_context: ::alloc::vec::Vec::new()vec![],
793 fixed_temps: Default::default(),
794 fixed_temps_scope: None,
795 local_decls: IndexVec::from_elem_n(LocalDecl::new(return_ty, return_span), 1),
796 canonical_user_type_annotations: IndexVec::new(),
797 upvars: CaptureMap::new(),
798 var_indices: Default::default(),
799 unit_temp: None,
800 var_debug_info: ::alloc::vec::Vec::new()vec![],
801 lint_level_roots_cache: GrowableBitSet::new_empty(),
802 coverage_info: coverageinfo::CoverageInfoBuilder::new_if_enabled(tcx, def),
803 };
804
805 {
match (&builder.cfg.start_new_block(), &START_BLOCK) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(builder.cfg.start_new_block(), START_BLOCK);
806 {
match (&builder.new_source_scope(span, lint_level),
&OUTERMOST_SOURCE_SCOPE) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(builder.new_source_scope(span, lint_level), OUTERMOST_SOURCE_SCOPE);
807 builder.source_scopes[OUTERMOST_SOURCE_SCOPE].parent_scope = None;
808
809 builder
810 }
811
812 #[allow(dead_code)]
813 fn dump_for_debugging(&self) {
814 let mut body = Body::new(
815 MirSource::item(self.def_id.to_def_id()),
816 self.cfg.basic_blocks.clone(),
817 self.source_scopes.clone(),
818 self.local_decls.clone(),
819 self.canonical_user_type_annotations.clone(),
820 self.arg_count.clone(),
821 self.var_debug_info.clone(),
822 self.fn_span.clone(),
823 self.coroutine.clone(),
824 None,
825 );
826 body.coverage_info_hi = self.coverage_info.as_ref().map(|b| b.as_done());
827
828 let writer = pretty::MirWriter::new(self.tcx);
829 writer.write_mir_fn(&body, &mut std::io::stdout()).unwrap();
830 }
831
832 fn finish(self) -> Body<'tcx> {
833 let mut body = Body::new(
834 MirSource::item(self.def_id.to_def_id()),
835 self.cfg.basic_blocks,
836 self.source_scopes,
837 self.local_decls,
838 self.canonical_user_type_annotations,
839 self.arg_count,
840 self.var_debug_info,
841 self.fn_span,
842 self.coroutine,
843 None,
844 );
845 body.coverage_info_hi = self.coverage_info.map(|b| b.into_done());
846
847 let writer = pretty::MirWriter::new(self.tcx);
848 for (index, block) in body.basic_blocks.iter().enumerate() {
849 if block.terminator.is_none() {
850 writer.write_mir_fn(&body, &mut std::io::stdout()).unwrap();
851 ::rustc_middle::util::bug::span_bug_fmt(self.fn_span,
format_args!("no terminator on block {0:?}", index));span_bug!(self.fn_span, "no terminator on block {:?}", index);
852 }
853 }
854
855 body
856 }
857
858 fn insert_upvar_arg(&mut self) {
859 let Some(closure_arg) = self.local_decls.get(ty::CAPTURE_STRUCT_LOCAL) else { return };
860
861 let mut closure_ty = closure_arg.ty;
862 let mut closure_env_projs = ::alloc::vec::Vec::new()vec![];
863 if let ty::Ref(_, ty, _) = closure_ty.kind() {
864 closure_env_projs.push(ProjectionElem::Deref);
865 closure_ty = *ty;
866 }
867
868 let upvar_args = match closure_ty.kind() {
869 ty::Closure(_, args) => ty::UpvarArgs::Closure(args),
870 ty::Coroutine(_, args) => ty::UpvarArgs::Coroutine(args),
871 ty::CoroutineClosure(_, args) => ty::UpvarArgs::CoroutineClosure(args),
872 _ => return,
873 };
874
875 let capture_tys = upvar_args.upvar_tys();
881
882 let tcx = self.tcx;
883 let mut upvar_owner = None;
884 self.upvars = tcx
885 .closure_captures(self.def_id)
886 .iter()
887 .zip_eq(capture_tys)
888 .enumerate()
889 .map(|(i, (captured_place, ty))| {
890 let name = captured_place.to_symbol();
891
892 let capture = captured_place.info.capture_kind;
893 let var_id = match captured_place.place.base {
894 HirPlaceBase::Upvar(upvar_id) => upvar_id.var_path.hir_id,
895 _ => ::rustc_middle::util::bug::bug_fmt(format_args!("Expected an upvar"))bug!("Expected an upvar"),
896 };
897 let upvar_base = upvar_owner.get_or_insert(var_id.owner);
898 {
match (&*upvar_base, &var_id.owner) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(*upvar_base, var_id.owner);
899 let var_id = var_id.local_id;
900
901 let mutability = captured_place.mutability;
902
903 let mut projs = closure_env_projs.clone();
904 projs.push(ProjectionElem::Field(FieldIdx::new(i), ty));
905 match capture {
906 ty::UpvarCapture::ByValue | ty::UpvarCapture::ByUse => {}
907 ty::UpvarCapture::ByRef(..) => {
908 projs.push(ProjectionElem::Deref);
909 }
910 };
911
912 let use_place = Place {
913 local: ty::CAPTURE_STRUCT_LOCAL,
914 projection: tcx.mk_place_elems(&projs),
915 };
916 self.var_debug_info.push(VarDebugInfo {
917 name,
918 source_info: SourceInfo::outermost(captured_place.var_ident.span),
919 value: VarDebugInfoContents::Place(use_place),
920 composite: None,
921 argument_index: None,
922 });
923
924 let capture = Capture { captured_place, use_place, mutability };
925 (var_id, capture)
926 })
927 .collect();
928 }
929
930 fn args_and_body(
931 &mut self,
932 mut block: BasicBlock,
933 arguments: &IndexSlice<ParamId, Param<'tcx>>,
934 argument_scope: region::Scope,
935 expr_id: ExprId,
936 ) -> BlockAnd<()> {
937 let expr_span = self.thir[expr_id].span;
938 for (argument_index, param) in arguments.iter().enumerate() {
940 let source_info =
941 SourceInfo::outermost(param.pat.as_ref().map_or(self.fn_span, |pat| pat.span));
942 let arg_local =
943 self.local_decls.push(LocalDecl::with_source_info(param.ty, source_info));
944
945 if let Some(ref pat) = param.pat
947 && let Some(name) = pat.simple_ident()
948 {
949 self.var_debug_info.push(VarDebugInfo {
950 name,
951 source_info,
952 value: VarDebugInfoContents::Place(arg_local.into()),
953 composite: None,
954 argument_index: Some(argument_index as u16 + 1),
955 });
956 }
957 }
958
959 self.insert_upvar_arg();
960
961 let mut scope = None;
962 for (index, param) in arguments.iter().enumerate() {
964 let local = Local::arg(index);
966 let place = Place::from(local);
967
968 self.schedule_drop_value(
970 param.pat.as_ref().map_or(expr_span, |pat| pat.span),
971 argument_scope,
972 local,
973 );
974
975 let Some(ref pat) = param.pat else {
976 continue;
977 };
978 let original_source_scope = self.source_scope;
979 let span = pat.span;
980 if let Some(arg_hir_id) = param.hir_id {
981 self.set_correct_source_scope_for_arg(arg_hir_id, original_source_scope, span);
982 }
983 match pat.kind {
984 PatKind::Binding {
986 var,
987 mode: BindingMode(ByRef::No, mutability),
988 subpattern: None,
989 ..
990 } => {
991 self.local_decls[local].mutability = mutability;
992 self.local_decls[local].source_info.scope = self.source_scope;
993 **self.local_decls[local].local_info.as_mut().unwrap_crate_local() =
994 if let Some(kind) = param.self_kind {
995 LocalInfo::User(BindingForm::ImplicitSelf(kind))
996 } else {
997 let binding_mode = BindingMode(ByRef::No, mutability);
998 LocalInfo::User(BindingForm::Var(VarBindingForm {
999 binding_mode,
1000 opt_ty_info: param.ty_span,
1001 opt_match_place: Some((None, span)),
1002 pat_span: span,
1003 introductions: ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[VarBindingIntroduction { span, is_shorthand: false }]))vec![VarBindingIntroduction {
1004 span,
1005 is_shorthand: false,
1006 }],
1007 }))
1008 };
1009 self.var_indices.insert(var, LocalsForNode::One(local));
1010 }
1011 _ => {
1012 scope = self.declare_bindings(
1013 scope,
1014 expr_span,
1015 &pat,
1016 None,
1017 Some((Some(&place), span)),
1018 );
1019 let place_builder = PlaceBuilder::from(local);
1020 block = self.place_into_pattern(block, pat, place_builder, false).into_block();
1021 }
1022 }
1023 self.source_scope = original_source_scope;
1024 }
1025
1026 if let Some(source_scope) = scope {
1028 self.source_scope = source_scope;
1029 }
1030
1031 if self.tcx.intrinsic(self.def_id).is_some_and(|i| i.must_be_overridden)
1032 || self.tcx.is_sdylib_interface_build()
1033 {
1034 let source_info = self.source_info(rustc_span::DUMMY_SP);
1035 self.cfg.terminate(block, source_info, TerminatorKind::Unreachable);
1036 self.cfg.start_new_block().unit()
1037 } else {
1038 match self.tcx.hir_node(self.hir_id) {
1040 hir::Node::Item(hir::Item {
1041 kind: hir::ItemKind::Fn { has_body: false, .. },
1042 ..
1043 }) => {
1044 self.tcx.dcx().span_delayed_bug(
1045 expr_span,
1046 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("fn item without body has reached MIR building: {0:?}",
self.def_id))
})format!("fn item without body has reached MIR building: {:?}", self.def_id),
1047 );
1048 }
1049 _ => {}
1050 }
1051 self.expr_into_dest(Place::return_place(), block, expr_id)
1052 }
1053 }
1054
1055 fn set_correct_source_scope_for_arg(
1056 &mut self,
1057 arg_hir_id: HirId,
1058 original_source_scope: SourceScope,
1059 pattern_span: Span,
1060 ) {
1061 let parent_id = self.source_scopes[original_source_scope]
1062 .local_data
1063 .as_ref()
1064 .unwrap_crate_local()
1065 .lint_root;
1066 self.maybe_new_source_scope(pattern_span, arg_hir_id, parent_id);
1067 }
1068
1069 fn get_unit_temp(&mut self) -> Place<'tcx> {
1070 match self.unit_temp {
1071 Some(tmp) => tmp,
1072 None => {
1073 let ty = self.tcx.types.unit;
1074 let fn_span = self.fn_span;
1075 let tmp = self.temp(ty, fn_span);
1076 self.unit_temp = Some(tmp);
1077 tmp
1078 }
1079 }
1080 }
1081}
1082
1083fn parse_float_into_constval(num: Symbol, float_ty: ty::FloatTy, neg: bool) -> Option<ConstValue> {
1084 parse_float_into_scalar(num, float_ty, neg).map(|s| ConstValue::Scalar(s.into()))
1085}
1086
1087pub(crate) fn parse_float_into_scalar(
1088 num: Symbol,
1089 float_ty: ty::FloatTy,
1090 neg: bool,
1091) -> Option<ScalarInt> {
1092 let num = num.as_str();
1093 match float_ty {
1094 ty::FloatTy::F16 => {
1096 let mut f = num.parse::<Half>().ok()?;
1097 if neg {
1098 f = -f;
1099 }
1100 Some(ScalarInt::from(f))
1101 }
1102 ty::FloatTy::F32 => {
1103 let Ok(rust_f) = num.parse::<f32>() else { return None };
1104 let mut f = num
1105 .parse::<Single>()
1106 .unwrap_or_else(|e| {
::core::panicking::panic_fmt(format_args!("apfloat::ieee::Single failed to parse `{0}`: {1:?}",
num, e));
}panic!("apfloat::ieee::Single failed to parse `{num}`: {e:?}"));
1107
1108 if !(u128::from(rust_f.to_bits()) == f.to_bits()) {
{
::core::panicking::panic_fmt(format_args!("apfloat::ieee::Single gave different result for `{0}`: {1}({2:#x}) vs Rust\'s {3}({4:#x})",
rust_f, f, f.to_bits(),
Single::from_bits(rust_f.to_bits().into()),
rust_f.to_bits()));
}
};assert!(
1109 u128::from(rust_f.to_bits()) == f.to_bits(),
1110 "apfloat::ieee::Single gave different result for `{}`: \
1111 {}({:#x}) vs Rust's {}({:#x})",
1112 rust_f,
1113 f,
1114 f.to_bits(),
1115 Single::from_bits(rust_f.to_bits().into()),
1116 rust_f.to_bits()
1117 );
1118
1119 if neg {
1120 f = -f;
1121 }
1122
1123 Some(ScalarInt::from(f))
1124 }
1125 ty::FloatTy::F64 => {
1126 let Ok(rust_f) = num.parse::<f64>() else { return None };
1127 let mut f = num
1128 .parse::<Double>()
1129 .unwrap_or_else(|e| {
::core::panicking::panic_fmt(format_args!("apfloat::ieee::Double failed to parse `{0}`: {1:?}",
num, e));
}panic!("apfloat::ieee::Double failed to parse `{num}`: {e:?}"));
1130
1131 if !(u128::from(rust_f.to_bits()) == f.to_bits()) {
{
::core::panicking::panic_fmt(format_args!("apfloat::ieee::Double gave different result for `{0}`: {1}({2:#x}) vs Rust\'s {3}({4:#x})",
rust_f, f, f.to_bits(),
Double::from_bits(rust_f.to_bits().into()),
rust_f.to_bits()));
}
};assert!(
1132 u128::from(rust_f.to_bits()) == f.to_bits(),
1133 "apfloat::ieee::Double gave different result for `{}`: \
1134 {}({:#x}) vs Rust's {}({:#x})",
1135 rust_f,
1136 f,
1137 f.to_bits(),
1138 Double::from_bits(rust_f.to_bits().into()),
1139 rust_f.to_bits()
1140 );
1141
1142 if neg {
1143 f = -f;
1144 }
1145
1146 Some(ScalarInt::from(f))
1147 }
1148 ty::FloatTy::F128 => {
1150 let mut f = num.parse::<Quad>().ok()?;
1151 if neg {
1152 f = -f;
1153 }
1154 Some(ScalarInt::from(f))
1155 }
1156 }
1157}
1158
1159mod block;
1165mod cfg;
1166mod coverageinfo;
1167mod custom;
1168mod expr;
1169mod matches;
1170mod misc;
1171mod scope;