Skip to main content

rustc_codegen_ssa/mir/
block.rs

1use std::cmp;
2
3use rustc_abi::{Align, BackendRepr, ExternAbi, HasDataLayout, Reg, Size, WrappingRange};
4use rustc_ast as ast;
5use rustc_ast::{InlineAsmOptions, InlineAsmTemplatePiece};
6use rustc_data_structures::packed::Pu128;
7use rustc_hir::lang_items::LangItem;
8use rustc_lint_defs::builtin::TAIL_CALL_TRACK_CALLER;
9use rustc_middle::mir::{self, AssertKind, InlineAsmMacro, SwitchTargets, UnwindTerminateReason};
10use rustc_middle::ty::layout::{HasTyCtxt, LayoutOf, ValidityRequirement};
11use rustc_middle::ty::print::{with_no_trimmed_paths, with_no_visible_paths};
12use rustc_middle::ty::{self, Instance, Ty, TypeVisitableExt};
13use rustc_middle::{bug, span_bug};
14use rustc_session::config::OptLevel;
15use rustc_span::{Span, Spanned};
16use rustc_target::callconv::{ArgAbi, ArgAttributes, CastTarget, FnAbi, PassMode};
17use tracing::{debug, info};
18
19use super::operand::OperandRef;
20use super::operand::OperandValue::{Immediate, Pair, Ref, ZeroSized};
21use super::place::{PlaceRef, PlaceValue};
22use super::{CachedLlbb, FunctionCx, LocalRef};
23use crate::base::{self, is_call_from_compiler_builtins_to_upstream_monomorphization};
24use crate::common::{self, IntPredicate};
25use crate::errors::CompilerBuiltinsCannotCall;
26use crate::traits::*;
27use crate::{MemFlags, meth};
28
29// Indicates if we are in the middle of merging a BB's successor into it. This
30// can happen when BB jumps directly to its successor and the successor has no
31// other predecessors.
32#[derive(#[automatically_derived]
impl ::core::fmt::Debug for MergingSucc {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                MergingSucc::False => "False",
                MergingSucc::True => "True",
            })
    }
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for MergingSucc {
    #[inline]
    fn eq(&self, other: &MergingSucc) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq)]
33enum MergingSucc {
34    False,
35    True,
36}
37
38/// Indicates to the call terminator codegen whether a call
39/// is a normal call or an explicit tail call.
40#[derive(#[automatically_derived]
impl ::core::fmt::Debug for CallKind {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                CallKind::Normal => "Normal",
                CallKind::Tail => "Tail",
            })
    }
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for CallKind {
    #[inline]
    fn eq(&self, other: &CallKind) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq)]
41enum CallKind {
42    Normal,
43    Tail,
44}
45
46/// Used by `FunctionCx::codegen_terminator` for emitting common patterns
47/// e.g., creating a basic block, calling a function, etc.
48struct TerminatorCodegenHelper<'tcx> {
49    bb: mir::BasicBlock,
50    terminator: &'tcx mir::Terminator<'tcx>,
51}
52
53impl<'a, 'tcx> TerminatorCodegenHelper<'tcx> {
54    /// Returns the appropriate `Funclet` for the current funclet, if on MSVC,
55    /// either already previously cached, or newly created, by `landing_pad_for`.
56    fn funclet<'b, Bx: BuilderMethods<'a, 'tcx>>(
57        &self,
58        fx: &'b mut FunctionCx<'a, 'tcx, Bx>,
59    ) -> Option<&'b Bx::Funclet> {
60        let cleanup_kinds = fx.cleanup_kinds.as_ref()?;
61        let funclet_bb = cleanup_kinds[self.bb].funclet_bb(self.bb)?;
62        // If `landing_pad_for` hasn't been called yet to create the `Funclet`,
63        // it has to be now. This may not seem necessary, as RPO should lead
64        // to all the unwind edges being visited (and so to `landing_pad_for`
65        // getting called for them), before building any of the blocks inside
66        // the funclet itself - however, if MIR contains edges that end up not
67        // being needed in the LLVM IR after monomorphization, the funclet may
68        // be unreachable, and we don't have yet a way to skip building it in
69        // such an eventuality (which may be a better solution than this).
70        if fx.funclets[funclet_bb].is_none() {
71            fx.landing_pad_for(funclet_bb);
72        }
73        Some(
74            fx.funclets[funclet_bb]
75                .as_ref()
76                .expect("landing_pad_for didn't also create funclets entry"),
77        )
78    }
79
80    /// Get a basic block (creating it if necessary), possibly with cleanup
81    /// stuff in it or next to it.
82    fn llbb_with_cleanup<Bx: BuilderMethods<'a, 'tcx>>(
83        &self,
84        fx: &mut FunctionCx<'a, 'tcx, Bx>,
85        target: mir::BasicBlock,
86    ) -> Bx::BasicBlock {
87        let (needs_landing_pad, is_cleanupret) = self.llbb_characteristics(fx, target);
88        let mut lltarget = fx.llbb(target);
89        if needs_landing_pad {
90            lltarget = fx.landing_pad_for(target);
91        }
92        if is_cleanupret {
93            // Cross-funclet jump - need a trampoline
94            if !base::wants_new_eh_instructions(fx.cx.tcx().sess) {
    ::core::panicking::panic("assertion failed: base::wants_new_eh_instructions(fx.cx.tcx().sess)")
};assert!(base::wants_new_eh_instructions(fx.cx.tcx().sess));
95            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/mir/block.rs:95",
                        "rustc_codegen_ssa::mir::block", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/mir/block.rs"),
                        ::tracing_core::__macro_support::Option::Some(95u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir::block"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("llbb_with_cleanup: creating cleanup trampoline for {0:?}",
                                                    target) as &dyn Value))])
            });
    } else { ; }
};debug!("llbb_with_cleanup: creating cleanup trampoline for {:?}", target);
96            let name = &::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0:?}_cleanup_trampoline_{1:?}",
                self.bb, target))
    })format!("{:?}_cleanup_trampoline_{:?}", self.bb, target);
97            let trampoline_llbb = Bx::append_block(fx.cx, fx.llfn, name);
98            let mut trampoline_bx = Bx::build(fx.cx, trampoline_llbb);
99            trampoline_bx.cleanup_ret(self.funclet(fx).unwrap(), Some(lltarget));
100            trampoline_llbb
101        } else {
102            lltarget
103        }
104    }
105
106    fn llbb_characteristics<Bx: BuilderMethods<'a, 'tcx>>(
107        &self,
108        fx: &mut FunctionCx<'a, 'tcx, Bx>,
109        target: mir::BasicBlock,
110    ) -> (bool, bool) {
111        if let Some(ref cleanup_kinds) = fx.cleanup_kinds {
112            let funclet_bb = cleanup_kinds[self.bb].funclet_bb(self.bb);
113            let target_funclet = cleanup_kinds[target].funclet_bb(target);
114            let (needs_landing_pad, is_cleanupret) = match (funclet_bb, target_funclet) {
115                (None, None) => (false, false),
116                (None, Some(_)) => (true, false),
117                (Some(f), Some(t_f)) => (f != t_f, f != t_f),
118                (Some(_), None) => {
119                    let span = self.terminator.source_info.span;
120                    ::rustc_middle::util::bug::span_bug_fmt(span,
    format_args!("{0:?} - jump out of cleanup?", self.terminator));span_bug!(span, "{:?} - jump out of cleanup?", self.terminator);
121                }
122            };
123            (needs_landing_pad, is_cleanupret)
124        } else {
125            let needs_landing_pad = !fx.mir[self.bb].is_cleanup && fx.mir[target].is_cleanup;
126            let is_cleanupret = false;
127            (needs_landing_pad, is_cleanupret)
128        }
129    }
130
131    fn funclet_br<Bx: BuilderMethods<'a, 'tcx>>(
132        &self,
133        fx: &mut FunctionCx<'a, 'tcx, Bx>,
134        bx: &mut Bx,
135        target: mir::BasicBlock,
136        mergeable_succ: bool,
137    ) -> MergingSucc {
138        let (needs_landing_pad, is_cleanupret) = self.llbb_characteristics(fx, target);
139        if mergeable_succ && !needs_landing_pad && !is_cleanupret {
140            // We can merge the successor into this bb, so no need for a `br`.
141            MergingSucc::True
142        } else {
143            let mut lltarget = fx.llbb(target);
144            if needs_landing_pad {
145                lltarget = fx.landing_pad_for(target);
146            }
147            if is_cleanupret {
148                // micro-optimization: generate a `ret` rather than a jump
149                // to a trampoline.
150                bx.cleanup_ret(self.funclet(fx).unwrap(), Some(lltarget));
151            } else {
152                bx.br(lltarget);
153            }
154            MergingSucc::False
155        }
156    }
157
158    /// Call `fn_ptr` of `fn_abi` with the arguments `llargs`, the optional
159    /// return destination `destination` and the unwind action `unwind`.
160    fn do_call<Bx: BuilderMethods<'a, 'tcx>>(
161        &self,
162        fx: &mut FunctionCx<'a, 'tcx, Bx>,
163        bx: &mut Bx,
164        fn_abi: &'tcx FnAbi<'tcx, Ty<'tcx>>,
165        fn_ptr: Bx::Value,
166        llargs: &[Bx::Value],
167        destination: Option<(ReturnDest<'tcx, Bx::Value>, mir::BasicBlock)>,
168        mut unwind: mir::UnwindAction,
169        lifetime_ends_after_call: &[(Bx::Value, Size)],
170        instance: Option<Instance<'tcx>>,
171        kind: CallKind,
172        mergeable_succ: bool,
173    ) -> MergingSucc {
174        let tcx = bx.tcx();
175        if let Some(instance) = instance
176            && is_call_from_compiler_builtins_to_upstream_monomorphization(tcx, instance)
177        {
178            if destination.is_some() {
179                let caller_def = fx.instance.def_id();
180                let e = CompilerBuiltinsCannotCall {
181                    span: tcx.def_span(caller_def),
182                    caller: { let _guard = NoTrimmedGuard::new(); tcx.def_path_str(caller_def) }with_no_trimmed_paths!(tcx.def_path_str(caller_def)),
183                    callee: { let _guard = NoTrimmedGuard::new(); tcx.def_path_str(instance.def_id()) }with_no_trimmed_paths!(tcx.def_path_str(instance.def_id())),
184                };
185                tcx.dcx().emit_err(e);
186            } else {
187                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/mir/block.rs:187",
                        "rustc_codegen_ssa::mir::block", ::tracing::Level::INFO,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/mir/block.rs"),
                        ::tracing_core::__macro_support::Option::Some(187u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir::block"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::INFO <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("compiler_builtins call to diverging function {0:?} replaced with abort",
                                                    instance.def_id()) as &dyn Value))])
            });
    } else { ; }
};info!(
188                    "compiler_builtins call to diverging function {:?} replaced with abort",
189                    instance.def_id()
190                );
191                bx.abort();
192                bx.unreachable();
193                return MergingSucc::False;
194            }
195        }
196
197        // If there is a cleanup block and the function we're calling can unwind, then
198        // do an invoke, otherwise do a call.
199        let fn_ty = bx.fn_decl_backend_type(fn_abi);
200
201        let caller_attrs = if bx.tcx().def_kind(fx.instance.def_id()).has_codegen_attrs() {
202            Some(bx.tcx().codegen_instance_attrs(fx.instance.def))
203        } else {
204            None
205        };
206        let caller_attrs = caller_attrs.as_deref();
207
208        if !fn_abi.can_unwind {
209            unwind = mir::UnwindAction::Unreachable;
210        }
211
212        let unwind_block = match unwind {
213            mir::UnwindAction::Cleanup(cleanup) => Some(self.llbb_with_cleanup(fx, cleanup)),
214            mir::UnwindAction::Continue => None,
215            mir::UnwindAction::Unreachable => None,
216            mir::UnwindAction::Terminate(reason) => {
217                if fx.mir[self.bb].is_cleanup && base::wants_new_eh_instructions(fx.cx.tcx().sess) {
218                    // MSVC SEH will abort automatically if an exception tries to
219                    // propagate out from cleanup.
220
221                    // FIXME(@mirkootter): For wasm, we currently do not support terminate during
222                    // cleanup, because this requires a few more changes: The current code
223                    // caches the `terminate_block` for each function; funclet based code - however -
224                    // requires a different terminate_block for each funclet
225                    // Until this is implemented, we just do not unwind inside cleanup blocks
226
227                    None
228                } else {
229                    Some(fx.terminate_block(reason))
230                }
231            }
232        };
233
234        if kind == CallKind::Tail {
235            bx.tail_call(fn_ty, caller_attrs, fn_abi, fn_ptr, llargs, self.funclet(fx), instance);
236            return MergingSucc::False;
237        }
238
239        if let Some(unwind_block) = unwind_block {
240            let ret_llbb = if let Some((_, target)) = destination {
241                fx.llbb(target)
242            } else {
243                fx.unreachable_block()
244            };
245            let invokeret = bx.invoke(
246                fn_ty,
247                caller_attrs,
248                Some(fn_abi),
249                fn_ptr,
250                llargs,
251                ret_llbb,
252                unwind_block,
253                self.funclet(fx),
254                instance,
255            );
256            if fx.mir[self.bb].is_cleanup {
257                bx.apply_attrs_to_cleanup_callsite(invokeret);
258            }
259
260            if let Some((ret_dest, target)) = destination {
261                bx.switch_to_block(fx.llbb(target));
262                fx.set_debug_loc(bx, self.terminator.source_info);
263                for &(tmp, size) in lifetime_ends_after_call {
264                    bx.lifetime_end(tmp, size);
265                }
266                fx.store_return(bx, ret_dest, &fn_abi.ret, invokeret);
267            }
268            MergingSucc::False
269        } else {
270            let llret = bx.call(
271                fn_ty,
272                caller_attrs,
273                Some(fn_abi),
274                fn_ptr,
275                llargs,
276                self.funclet(fx),
277                instance,
278            );
279            if fx.mir[self.bb].is_cleanup {
280                bx.apply_attrs_to_cleanup_callsite(llret);
281            }
282
283            if let Some((ret_dest, target)) = destination {
284                for &(tmp, size) in lifetime_ends_after_call {
285                    bx.lifetime_end(tmp, size);
286                }
287                fx.store_return(bx, ret_dest, &fn_abi.ret, llret);
288                self.funclet_br(fx, bx, target, mergeable_succ)
289            } else {
290                bx.unreachable();
291                MergingSucc::False
292            }
293        }
294    }
295
296    /// Generates inline assembly with optional `destination` and `unwind`.
297    fn do_inlineasm<Bx: BuilderMethods<'a, 'tcx>>(
298        &self,
299        fx: &mut FunctionCx<'a, 'tcx, Bx>,
300        bx: &mut Bx,
301        template: &[InlineAsmTemplatePiece],
302        operands: &[InlineAsmOperandRef<'tcx, Bx>],
303        options: InlineAsmOptions,
304        line_spans: &[Span],
305        destination: Option<mir::BasicBlock>,
306        unwind: mir::UnwindAction,
307        instance: Instance<'_>,
308        mergeable_succ: bool,
309    ) -> MergingSucc {
310        let unwind_target = match unwind {
311            mir::UnwindAction::Cleanup(cleanup) => Some(self.llbb_with_cleanup(fx, cleanup)),
312            mir::UnwindAction::Terminate(reason) => Some(fx.terminate_block(reason)),
313            mir::UnwindAction::Continue => None,
314            mir::UnwindAction::Unreachable => None,
315        };
316
317        if operands.iter().any(|x| #[allow(non_exhaustive_omitted_patterns)] match x {
    InlineAsmOperandRef::Label { .. } => true,
    _ => false,
}matches!(x, InlineAsmOperandRef::Label { .. })) {
318            if !unwind_target.is_none() {
    ::core::panicking::panic("assertion failed: unwind_target.is_none()")
};assert!(unwind_target.is_none());
319            let ret_llbb = if let Some(target) = destination {
320                fx.llbb(target)
321            } else {
322                fx.unreachable_block()
323            };
324
325            bx.codegen_inline_asm(
326                template,
327                operands,
328                options,
329                line_spans,
330                instance,
331                Some(ret_llbb),
332                None,
333            );
334            MergingSucc::False
335        } else if let Some(cleanup) = unwind_target {
336            let ret_llbb = if let Some(target) = destination {
337                fx.llbb(target)
338            } else {
339                fx.unreachable_block()
340            };
341
342            bx.codegen_inline_asm(
343                template,
344                operands,
345                options,
346                line_spans,
347                instance,
348                Some(ret_llbb),
349                Some((cleanup, self.funclet(fx))),
350            );
351            MergingSucc::False
352        } else {
353            bx.codegen_inline_asm(template, operands, options, line_spans, instance, None, None);
354
355            if let Some(target) = destination {
356                self.funclet_br(fx, bx, target, mergeable_succ)
357            } else {
358                bx.unreachable();
359                MergingSucc::False
360            }
361        }
362    }
363}
364
365/// Codegen implementations for some terminator variants.
366impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
367    /// Generates code for a `Resume` terminator.
368    fn codegen_resume_terminator(&mut self, helper: TerminatorCodegenHelper<'tcx>, bx: &mut Bx) {
369        if let Some(funclet) = helper.funclet(self) {
370            bx.cleanup_ret(funclet, None);
371        } else {
372            let slot = self.get_personality_slot(bx);
373            let exn0 = slot.project_field(bx, 0);
374            let exn0 = bx.load_operand(exn0).immediate();
375            let exn1 = slot.project_field(bx, 1);
376            let exn1 = bx.load_operand(exn1).immediate();
377            slot.storage_dead(bx);
378
379            bx.resume(exn0, exn1);
380        }
381    }
382
383    fn codegen_switchint_terminator(
384        &mut self,
385        helper: TerminatorCodegenHelper<'tcx>,
386        bx: &mut Bx,
387        discr: &mir::Operand<'tcx>,
388        targets: &SwitchTargets,
389    ) {
390        let discr = self.codegen_operand(bx, discr);
391        let discr_value = discr.immediate();
392        let switch_ty = discr.layout.ty;
393        // If our discriminant is a constant we can branch directly
394        if let Some(const_discr) = bx.const_to_opt_u128(discr_value, false) {
395            let target = targets.target_for_value(const_discr);
396            bx.br(helper.llbb_with_cleanup(self, target));
397            return;
398        };
399
400        let mut target_iter = targets.iter();
401        if target_iter.len() == 1 {
402            // If there are two targets (one conditional, one fallback), emit `br` instead of
403            // `switch`.
404            let (test_value, target) = target_iter.next().unwrap();
405            let otherwise = targets.otherwise();
406            let lltarget = helper.llbb_with_cleanup(self, target);
407            let llotherwise = helper.llbb_with_cleanup(self, otherwise);
408            let target_cold = self.cold_blocks[target];
409            let otherwise_cold = self.cold_blocks[otherwise];
410            // If `target_cold == otherwise_cold`, the branches have the same weight
411            // so there is no expectation. If they differ, the `target` branch is expected
412            // when the `otherwise` branch is cold.
413            let expect = if target_cold == otherwise_cold { None } else { Some(otherwise_cold) };
414            if switch_ty == bx.tcx().types.bool {
415                // Don't generate trivial icmps when switching on bool.
416                match test_value {
417                    0 => {
418                        let expect = expect.map(|e| !e);
419                        bx.cond_br_with_expect(discr_value, llotherwise, lltarget, expect);
420                    }
421                    1 => {
422                        bx.cond_br_with_expect(discr_value, lltarget, llotherwise, expect);
423                    }
424                    _ => ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!(),
425                }
426            } else {
427                let switch_llty = bx.immediate_backend_type(bx.layout_of(switch_ty));
428                let llval = bx.const_uint_big(switch_llty, test_value);
429                let cmp = bx.icmp(IntPredicate::IntEQ, discr_value, llval);
430                bx.cond_br_with_expect(cmp, lltarget, llotherwise, expect);
431            }
432        } else if target_iter.len() == 2
433            && self.mir[targets.otherwise()].is_empty_unreachable()
434            && targets.all_values().contains(&Pu128(0))
435            && targets.all_values().contains(&Pu128(1))
436        {
437            // This is the really common case for `bool`, `Option`, etc.
438            // By using `trunc nuw` we communicate that other values are
439            // impossible without needing `switch` or `assume`s.
440            let true_bb = targets.target_for_value(1);
441            let false_bb = targets.target_for_value(0);
442            let true_ll = helper.llbb_with_cleanup(self, true_bb);
443            let false_ll = helper.llbb_with_cleanup(self, false_bb);
444
445            let expected_cond_value = if self.cx.sess().opts.optimize == OptLevel::No {
446                None
447            } else {
448                match (self.cold_blocks[true_bb], self.cold_blocks[false_bb]) {
449                    // Same coldness, no expectation
450                    (true, true) | (false, false) => None,
451                    // Different coldness, expect the non-cold one
452                    (true, false) => Some(false),
453                    (false, true) => Some(true),
454                }
455            };
456
457            let bool_ty = bx.tcx().types.bool;
458            let cond = if switch_ty == bool_ty {
459                discr_value
460            } else {
461                let bool_llty = bx.immediate_backend_type(bx.layout_of(bool_ty));
462                bx.unchecked_utrunc(discr_value, bool_llty)
463            };
464            bx.cond_br_with_expect(cond, true_ll, false_ll, expected_cond_value);
465        } else if self.cx.sess().opts.optimize == OptLevel::No
466            && target_iter.len() == 2
467            && self.mir[targets.otherwise()].is_empty_unreachable()
468        {
469            // In unoptimized builds, if there are two normal targets and the `otherwise` target is
470            // an unreachable BB, emit `br` instead of `switch`. This leaves behind the unreachable
471            // BB, which will usually (but not always) be dead code.
472            //
473            // Why only in unoptimized builds?
474            // - In unoptimized builds LLVM uses FastISel which does not support switches, so it
475            //   must fall back to the slower SelectionDAG isel. Therefore, using `br` gives
476            //   significant compile time speedups for unoptimized builds.
477            // - In optimized builds the above doesn't hold, and using `br` sometimes results in
478            //   worse generated code because LLVM can no longer tell that the value being switched
479            //   on can only have two values, e.g. 0 and 1.
480            //
481            let (test_value1, target1) = target_iter.next().unwrap();
482            let (_test_value2, target2) = target_iter.next().unwrap();
483            let ll1 = helper.llbb_with_cleanup(self, target1);
484            let ll2 = helper.llbb_with_cleanup(self, target2);
485            let switch_llty = bx.immediate_backend_type(bx.layout_of(switch_ty));
486            let llval = bx.const_uint_big(switch_llty, test_value1);
487            let cmp = bx.icmp(IntPredicate::IntEQ, discr_value, llval);
488            bx.cond_br(cmp, ll1, ll2);
489        } else {
490            let otherwise = targets.otherwise();
491            let otherwise_cold = self.cold_blocks[otherwise];
492            let otherwise_unreachable = self.mir[otherwise].is_empty_unreachable();
493            let cold_count = targets.iter().filter(|(_, target)| self.cold_blocks[*target]).count();
494            let none_cold = cold_count == 0;
495            let all_cold = cold_count == targets.iter().len();
496            if (none_cold && (!otherwise_cold || otherwise_unreachable))
497                || (all_cold && (otherwise_cold || otherwise_unreachable))
498            {
499                // All targets have the same weight,
500                // or `otherwise` is unreachable and it's the only target with a different weight.
501                bx.switch(
502                    discr_value,
503                    helper.llbb_with_cleanup(self, targets.otherwise()),
504                    target_iter
505                        .map(|(value, target)| (value, helper.llbb_with_cleanup(self, target))),
506                );
507            } else {
508                // Targets have different weights
509                bx.switch_with_weights(
510                    discr_value,
511                    helper.llbb_with_cleanup(self, targets.otherwise()),
512                    otherwise_cold,
513                    target_iter.map(|(value, target)| {
514                        (value, helper.llbb_with_cleanup(self, target), self.cold_blocks[target])
515                    }),
516                );
517            }
518        }
519    }
520
521    fn codegen_return_terminator(&mut self, bx: &mut Bx) {
522        // Call `va_end` if this is the definition of a C-variadic function.
523        if self.fn_abi.c_variadic {
524            // The `VaList` "spoofed" argument is just after all the real arguments.
525            let va_list_arg_idx = self.fn_abi.args.len();
526            match self.locals[mir::Local::from_usize(1 + va_list_arg_idx)] {
527                LocalRef::Place(va_list) => {
528                    bx.va_end(va_list.val.llval);
529
530                    // Explicitly end the lifetime of the `va_list`, improves LLVM codegen.
531                    bx.lifetime_end(va_list.val.llval, va_list.layout.size);
532                }
533                _ => ::rustc_middle::util::bug::bug_fmt(format_args!("C-variadic function must have a `VaList` place"))bug!("C-variadic function must have a `VaList` place"),
534            }
535        }
536        if self.fn_abi.ret.layout.is_uninhabited() {
537            // Functions with uninhabited return values are marked `noreturn`,
538            // so we should make sure that we never actually do.
539            // We play it safe by using a well-defined `abort`, but we could go for immediate UB
540            // if that turns out to be helpful.
541            bx.abort();
542            // `abort` does not terminate the block, so we still need to generate
543            // an `unreachable` terminator after it.
544            bx.unreachable();
545            return;
546        }
547        let llval = match &self.fn_abi.ret.mode {
548            PassMode::Ignore | PassMode::Indirect { .. } => {
549                bx.ret_void();
550                return;
551            }
552
553            PassMode::Direct(_) | PassMode::Pair(..) => {
554                let op = self.codegen_consume(bx, mir::Place::return_place().as_ref());
555                if let Ref(place_val) = op.val {
556                    bx.load_from_place(bx.backend_type(op.layout), place_val)
557                } else {
558                    op.immediate_or_packed_pair(bx)
559                }
560            }
561
562            PassMode::Cast { cast: cast_ty, pad_i32: _ } => {
563                let op = match self.locals[mir::RETURN_PLACE] {
564                    LocalRef::Operand(op) => op,
565                    LocalRef::PendingOperand => ::rustc_middle::util::bug::bug_fmt(format_args!("use of return before def"))bug!("use of return before def"),
566                    LocalRef::Place(cg_place) => OperandRef {
567                        val: Ref(cg_place.val),
568                        layout: cg_place.layout,
569                        move_annotation: None,
570                    },
571                    LocalRef::UnsizedPlace(_) => ::rustc_middle::util::bug::bug_fmt(format_args!("return type must be sized"))bug!("return type must be sized"),
572                };
573                let llslot = match op.val {
574                    Immediate(_) | Pair(..) => {
575                        let scratch = PlaceRef::alloca(bx, self.fn_abi.ret.layout);
576                        op.val.store(bx, scratch);
577                        scratch.val.llval
578                    }
579                    Ref(place_val) => {
580                        match (&place_val.align, &op.layout.align.abi) {
    (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::Some(format_args!("return place is unaligned!")));
        }
    }
};assert_eq!(
581                            place_val.align, op.layout.align.abi,
582                            "return place is unaligned!"
583                        );
584                        place_val.llval
585                    }
586                    ZeroSized => ::rustc_middle::util::bug::bug_fmt(format_args!("ZST return value shouldn\'t be in PassMode::Cast"))bug!("ZST return value shouldn't be in PassMode::Cast"),
587                };
588                load_cast(bx, cast_ty, llslot, self.fn_abi.ret.layout.align.abi)
589            }
590        };
591        bx.ret(llval);
592    }
593
594    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("codegen_drop_terminator",
                                    "rustc_codegen_ssa::mir::block", ::tracing::Level::TRACE,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/mir/block.rs"),
                                    ::tracing_core::__macro_support::Option::Some(594u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir::block"),
                                    ::tracing_core::field::FieldSet::new(&["source_info",
                                                    "location", "target", "unwind", "mergeable_succ"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&source_info)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&location)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&target)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&unwind)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&mergeable_succ as
                                                            &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: MergingSucc = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let ty = location.ty(self.mir, bx.tcx()).ty;
            let ty = self.monomorphize(ty);
            let drop_fn = Instance::resolve_drop_in_place(bx.tcx(), ty);
            if let ty::InstanceKind::DropGlue(_, None) = drop_fn.def {
                return helper.funclet_br(self, bx, target, mergeable_succ);
            }
            let place = self.codegen_place(bx, location.as_ref());
            let (args1, args2);
            let mut args =
                if let Some(llextra) = place.val.llextra {
                    args2 = [place.val.llval, llextra];
                    &args2[..]
                } else { args1 = [place.val.llval]; &args1[..] };
            let (maybe_null, drop_fn, fn_abi, drop_instance) =
                match ty.kind() {
                    ty::Dynamic(_, _) => {
                        let virtual_drop =
                            Instance {
                                def: ty::InstanceKind::Virtual(drop_fn.def_id(), 0),
                                args: drop_fn.args,
                            };
                        {
                            use ::tracing::__macro_support::Callsite as _;
                            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                {
                                    static META: ::tracing::Metadata<'static> =
                                        {
                                            ::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/mir/block.rs:643",
                                                "rustc_codegen_ssa::mir::block", ::tracing::Level::DEBUG,
                                                ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/mir/block.rs"),
                                                ::tracing_core::__macro_support::Option::Some(643u32),
                                                ::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir::block"),
                                                ::tracing_core::field::FieldSet::new(&["message"],
                                                    ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                ::tracing::metadata::Kind::EVENT)
                                        };
                                    ::tracing::callsite::DefaultCallsite::new(&META)
                                };
                            let enabled =
                                ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                        ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::LevelFilter::current() &&
                                    {
                                        let interest = __CALLSITE.interest();
                                        !interest.is_never() &&
                                            ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                interest)
                                    };
                            if enabled {
                                (|value_set: ::tracing::field::ValueSet|
                                            {
                                                let meta = __CALLSITE.metadata();
                                                ::tracing::Event::dispatch(meta, &value_set);
                                                ;
                                            })({
                                        #[allow(unused_imports)]
                                        use ::tracing::field::{debug, display, Value};
                                        let mut iter = __CALLSITE.metadata().fields().iter();
                                        __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                            ::tracing::__macro_support::Option::Some(&format_args!("ty = {0:?}",
                                                                            ty) as &dyn Value))])
                                    });
                            } else { ; }
                        };
                        {
                            use ::tracing::__macro_support::Callsite as _;
                            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                {
                                    static META: ::tracing::Metadata<'static> =
                                        {
                                            ::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/mir/block.rs:644",
                                                "rustc_codegen_ssa::mir::block", ::tracing::Level::DEBUG,
                                                ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/mir/block.rs"),
                                                ::tracing_core::__macro_support::Option::Some(644u32),
                                                ::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir::block"),
                                                ::tracing_core::field::FieldSet::new(&["message"],
                                                    ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                ::tracing::metadata::Kind::EVENT)
                                        };
                                    ::tracing::callsite::DefaultCallsite::new(&META)
                                };
                            let enabled =
                                ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                        ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::LevelFilter::current() &&
                                    {
                                        let interest = __CALLSITE.interest();
                                        !interest.is_never() &&
                                            ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                interest)
                                    };
                            if enabled {
                                (|value_set: ::tracing::field::ValueSet|
                                            {
                                                let meta = __CALLSITE.metadata();
                                                ::tracing::Event::dispatch(meta, &value_set);
                                                ;
                                            })({
                                        #[allow(unused_imports)]
                                        use ::tracing::field::{debug, display, Value};
                                        let mut iter = __CALLSITE.metadata().fields().iter();
                                        __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                            ::tracing::__macro_support::Option::Some(&format_args!("drop_fn = {0:?}",
                                                                            drop_fn) as &dyn Value))])
                                    });
                            } else { ; }
                        };
                        {
                            use ::tracing::__macro_support::Callsite as _;
                            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                {
                                    static META: ::tracing::Metadata<'static> =
                                        {
                                            ::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/mir/block.rs:645",
                                                "rustc_codegen_ssa::mir::block", ::tracing::Level::DEBUG,
                                                ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/mir/block.rs"),
                                                ::tracing_core::__macro_support::Option::Some(645u32),
                                                ::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir::block"),
                                                ::tracing_core::field::FieldSet::new(&["message"],
                                                    ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                ::tracing::metadata::Kind::EVENT)
                                        };
                                    ::tracing::callsite::DefaultCallsite::new(&META)
                                };
                            let enabled =
                                ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                        ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::LevelFilter::current() &&
                                    {
                                        let interest = __CALLSITE.interest();
                                        !interest.is_never() &&
                                            ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                interest)
                                    };
                            if enabled {
                                (|value_set: ::tracing::field::ValueSet|
                                            {
                                                let meta = __CALLSITE.metadata();
                                                ::tracing::Event::dispatch(meta, &value_set);
                                                ;
                                            })({
                                        #[allow(unused_imports)]
                                        use ::tracing::field::{debug, display, Value};
                                        let mut iter = __CALLSITE.metadata().fields().iter();
                                        __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                            ::tracing::__macro_support::Option::Some(&format_args!("args = {0:?}",
                                                                            args) as &dyn Value))])
                                    });
                            } else { ; }
                        };
                        let fn_abi =
                            bx.fn_abi_of_instance(virtual_drop, ty::List::empty());
                        let vtable = args[1];
                        args = &args[..1];
                        (true,
                            meth::VirtualIndex::from_index(ty::COMMON_VTABLE_ENTRIES_DROPINPLACE).get_optional_fn(bx,
                                vtable, ty, fn_abi), fn_abi, virtual_drop)
                    }
                    _ =>
                        (false, bx.get_fn_addr(drop_fn),
                            bx.fn_abi_of_instance(drop_fn, ty::List::empty()), drop_fn),
                };
            if maybe_null {
                let is_not_null = bx.append_sibling_block("is_not_null");
                let llty = bx.fn_ptr_backend_type(fn_abi);
                let null = bx.const_null(llty);
                let non_null =
                    bx.icmp(base::bin_op_to_icmp_predicate(mir::BinOp::Ne,
                            false), drop_fn, null);
                bx.cond_br(non_null, is_not_null,
                    helper.llbb_with_cleanup(self, target));
                bx.switch_to_block(is_not_null);
                self.set_debug_loc(bx, *source_info);
            }
            helper.do_call(self, bx, fn_abi, drop_fn, args,
                Some((ReturnDest::Nothing, target)), unwind, &[],
                Some(drop_instance), CallKind::Normal,
                !maybe_null && mergeable_succ)
        }
    }
}#[tracing::instrument(level = "trace", skip(self, helper, bx))]
595    fn codegen_drop_terminator(
596        &mut self,
597        helper: TerminatorCodegenHelper<'tcx>,
598        bx: &mut Bx,
599        source_info: &mir::SourceInfo,
600        location: mir::Place<'tcx>,
601        target: mir::BasicBlock,
602        unwind: mir::UnwindAction,
603        mergeable_succ: bool,
604    ) -> MergingSucc {
605        let ty = location.ty(self.mir, bx.tcx()).ty;
606        let ty = self.monomorphize(ty);
607        let drop_fn = Instance::resolve_drop_in_place(bx.tcx(), ty);
608
609        if let ty::InstanceKind::DropGlue(_, None) = drop_fn.def {
610            // we don't actually need to drop anything.
611            return helper.funclet_br(self, bx, target, mergeable_succ);
612        }
613
614        let place = self.codegen_place(bx, location.as_ref());
615        let (args1, args2);
616        let mut args = if let Some(llextra) = place.val.llextra {
617            args2 = [place.val.llval, llextra];
618            &args2[..]
619        } else {
620            args1 = [place.val.llval];
621            &args1[..]
622        };
623        let (maybe_null, drop_fn, fn_abi, drop_instance) = match ty.kind() {
624            // FIXME(eddyb) perhaps move some of this logic into
625            // `Instance::resolve_drop_in_place`?
626            ty::Dynamic(_, _) => {
627                // IN THIS ARM, WE HAVE:
628                // ty = *mut (dyn Trait)
629                // which is: exists<T> ( *mut T,    Vtable<T: Trait> )
630                //                       args[0]    args[1]
631                //
632                // args = ( Data, Vtable )
633                //                  |
634                //                  v
635                //                /-------\
636                //                | ...   |
637                //                \-------/
638                //
639                let virtual_drop = Instance {
640                    def: ty::InstanceKind::Virtual(drop_fn.def_id(), 0), // idx 0: the drop function
641                    args: drop_fn.args,
642                };
643                debug!("ty = {:?}", ty);
644                debug!("drop_fn = {:?}", drop_fn);
645                debug!("args = {:?}", args);
646                let fn_abi = bx.fn_abi_of_instance(virtual_drop, ty::List::empty());
647                let vtable = args[1];
648                // Truncate vtable off of args list
649                args = &args[..1];
650                (
651                    true,
652                    meth::VirtualIndex::from_index(ty::COMMON_VTABLE_ENTRIES_DROPINPLACE)
653                        .get_optional_fn(bx, vtable, ty, fn_abi),
654                    fn_abi,
655                    virtual_drop,
656                )
657            }
658            _ => (
659                false,
660                bx.get_fn_addr(drop_fn),
661                bx.fn_abi_of_instance(drop_fn, ty::List::empty()),
662                drop_fn,
663            ),
664        };
665
666        // We generate a null check for the drop_fn. This saves a bunch of relocations being
667        // generated for no-op drops.
668        if maybe_null {
669            let is_not_null = bx.append_sibling_block("is_not_null");
670            let llty = bx.fn_ptr_backend_type(fn_abi);
671            let null = bx.const_null(llty);
672            let non_null =
673                bx.icmp(base::bin_op_to_icmp_predicate(mir::BinOp::Ne, false), drop_fn, null);
674            bx.cond_br(non_null, is_not_null, helper.llbb_with_cleanup(self, target));
675            bx.switch_to_block(is_not_null);
676            self.set_debug_loc(bx, *source_info);
677        }
678
679        helper.do_call(
680            self,
681            bx,
682            fn_abi,
683            drop_fn,
684            args,
685            Some((ReturnDest::Nothing, target)),
686            unwind,
687            &[],
688            Some(drop_instance),
689            CallKind::Normal,
690            !maybe_null && mergeable_succ,
691        )
692    }
693
694    fn codegen_assert_terminator(
695        &mut self,
696        helper: TerminatorCodegenHelper<'tcx>,
697        bx: &mut Bx,
698        terminator: &mir::Terminator<'tcx>,
699        cond: &mir::Operand<'tcx>,
700        expected: bool,
701        msg: &mir::AssertMessage<'tcx>,
702        target: mir::BasicBlock,
703        unwind: mir::UnwindAction,
704        mergeable_succ: bool,
705    ) -> MergingSucc {
706        let span = terminator.source_info.span;
707        let cond = self.codegen_operand(bx, cond).immediate();
708        let mut const_cond = bx.const_to_opt_u128(cond, false).map(|c| c == 1);
709
710        // This case can currently arise only from functions marked
711        // with #[rustc_inherit_overflow_checks] and inlined from
712        // another crate (mostly core::num generic/#[inline] fns),
713        // while the current crate doesn't use overflow checks.
714        if !bx.sess().overflow_checks() && msg.is_optional_overflow_check() {
715            const_cond = Some(expected);
716        }
717
718        // Don't codegen the panic block if success if known.
719        if const_cond == Some(expected) {
720            return helper.funclet_br(self, bx, target, mergeable_succ);
721        }
722
723        // Because we're branching to a panic block (either a `#[cold]` one
724        // or an inlined abort), there's no need to `expect` it.
725
726        // Create the failure block and the conditional branch to it.
727        let lltarget = helper.llbb_with_cleanup(self, target);
728        let panic_block = bx.append_sibling_block("panic");
729        if expected {
730            bx.cond_br(cond, lltarget, panic_block);
731        } else {
732            bx.cond_br(cond, panic_block, lltarget);
733        }
734
735        // After this point, bx is the block for the call to panic.
736        bx.switch_to_block(panic_block);
737        self.set_debug_loc(bx, terminator.source_info);
738
739        // Get the location information.
740        let location = self.get_caller_location(bx, terminator.source_info).immediate();
741
742        // Put together the arguments to the panic entry point.
743        let (lang_item, args) = match msg {
744            AssertKind::BoundsCheck { len, index } => {
745                let len = self.codegen_operand(bx, len).immediate();
746                let index = self.codegen_operand(bx, index).immediate();
747                // It's `fn panic_bounds_check(index: usize, len: usize)`,
748                // and `#[track_caller]` adds an implicit third argument.
749                (LangItem::PanicBoundsCheck, ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [index, len, location]))vec![index, len, location])
750            }
751            AssertKind::MisalignedPointerDereference { required, found } => {
752                let required = self.codegen_operand(bx, required).immediate();
753                let found = self.codegen_operand(bx, found).immediate();
754                // It's `fn panic_misaligned_pointer_dereference(required: usize, found: usize)`,
755                // and `#[track_caller]` adds an implicit third argument.
756                (LangItem::PanicMisalignedPointerDereference, ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [required, found, location]))vec![required, found, location])
757            }
758            AssertKind::NullPointerDereference => {
759                // It's `fn panic_null_pointer_dereference()`,
760                // `#[track_caller]` adds an implicit argument.
761                (LangItem::PanicNullPointerDereference, ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [location]))vec![location])
762            }
763            AssertKind::InvalidEnumConstruction(source) => {
764                let source = self.codegen_operand(bx, source).immediate();
765                // It's `fn panic_invalid_enum_construction(source: u128)`,
766                // `#[track_caller]` adds an implicit argument.
767                (LangItem::PanicInvalidEnumConstruction, ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [source, location]))vec![source, location])
768            }
769            _ => {
770                // It's `pub fn panic_...()` and `#[track_caller]` adds an implicit argument.
771                (msg.panic_function(), ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [location]))vec![location])
772            }
773        };
774
775        let (fn_abi, llfn, instance) = common::build_langcall(bx, span, lang_item);
776
777        // Codegen the actual panic invoke/call.
778        let merging_succ = helper.do_call(
779            self,
780            bx,
781            fn_abi,
782            llfn,
783            &args,
784            None,
785            unwind,
786            &[],
787            Some(instance),
788            CallKind::Normal,
789            false,
790        );
791        match (&merging_succ, &MergingSucc::False) {
    (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!(merging_succ, MergingSucc::False);
792        MergingSucc::False
793    }
794
795    fn codegen_terminate_terminator(
796        &mut self,
797        helper: TerminatorCodegenHelper<'tcx>,
798        bx: &mut Bx,
799        terminator: &mir::Terminator<'tcx>,
800        reason: UnwindTerminateReason,
801    ) {
802        let span = terminator.source_info.span;
803        self.set_debug_loc(bx, terminator.source_info);
804
805        // Obtain the panic entry point.
806        let (fn_abi, llfn, instance) = common::build_langcall(bx, span, reason.lang_item());
807
808        // Codegen the actual panic invoke/call.
809        let merging_succ = helper.do_call(
810            self,
811            bx,
812            fn_abi,
813            llfn,
814            &[],
815            None,
816            mir::UnwindAction::Unreachable,
817            &[],
818            Some(instance),
819            CallKind::Normal,
820            false,
821        );
822        match (&merging_succ, &MergingSucc::False) {
    (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!(merging_succ, MergingSucc::False);
823    }
824
825    /// Returns `Some` if this is indeed a panic intrinsic and codegen is done.
826    fn codegen_panic_intrinsic(
827        &mut self,
828        helper: &TerminatorCodegenHelper<'tcx>,
829        bx: &mut Bx,
830        intrinsic: ty::IntrinsicDef,
831        instance: Instance<'tcx>,
832        source_info: mir::SourceInfo,
833        target: Option<mir::BasicBlock>,
834        unwind: mir::UnwindAction,
835        mergeable_succ: bool,
836    ) -> Option<MergingSucc> {
837        // Emit a panic or a no-op for `assert_*` intrinsics.
838        // These are intrinsics that compile to panics so that we can get a message
839        // which mentions the offending type, even from a const context.
840        let Some(requirement) = ValidityRequirement::from_intrinsic(intrinsic.name) else {
841            return None;
842        };
843
844        let ty = instance.args.type_at(0);
845
846        let is_valid = bx
847            .tcx()
848            .check_validity_requirement((requirement, bx.typing_env().as_query_input(ty)))
849            .expect("expect to have layout during codegen");
850
851        if is_valid {
852            // a NOP
853            let target = target.unwrap();
854            return Some(helper.funclet_br(self, bx, target, mergeable_succ));
855        }
856
857        let layout = bx.layout_of(ty);
858
859        let msg_str = {
    let _guard = NoVisibleGuard::new();
    {
        {
            let _guard = NoTrimmedGuard::new();
            {
                if layout.is_uninhabited() {
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("attempted to instantiate uninhabited type `{0}`",
                                    ty))
                        })
                } else if requirement == ValidityRequirement::Zero {
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("attempted to zero-initialize type `{0}`, which is invalid",
                                    ty))
                        })
                } else {
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("attempted to leave type `{0}` uninitialized, which is invalid",
                                    ty))
                        })
                }
            }
        }
    }
}with_no_visible_paths!({
860            with_no_trimmed_paths!({
861                if layout.is_uninhabited() {
862                    // Use this error even for the other intrinsics as it is more precise.
863                    format!("attempted to instantiate uninhabited type `{ty}`")
864                } else if requirement == ValidityRequirement::Zero {
865                    format!("attempted to zero-initialize type `{ty}`, which is invalid")
866                } else {
867                    format!("attempted to leave type `{ty}` uninitialized, which is invalid")
868                }
869            })
870        });
871        let msg = bx.const_str(&msg_str);
872
873        // Obtain the panic entry point.
874        let (fn_abi, llfn, instance) =
875            common::build_langcall(bx, source_info.span, LangItem::PanicNounwind);
876
877        // Codegen the actual panic invoke/call.
878        Some(helper.do_call(
879            self,
880            bx,
881            fn_abi,
882            llfn,
883            &[msg.0, msg.1],
884            target.as_ref().map(|bb| (ReturnDest::Nothing, *bb)),
885            unwind,
886            &[],
887            Some(instance),
888            CallKind::Normal,
889            mergeable_succ,
890        ))
891    }
892
893    fn codegen_call_terminator(
894        &mut self,
895        helper: TerminatorCodegenHelper<'tcx>,
896        bx: &mut Bx,
897        terminator: &mir::Terminator<'tcx>,
898        func: &mir::Operand<'tcx>,
899        args: &[Spanned<mir::Operand<'tcx>>],
900        destination: mir::Place<'tcx>,
901        target: Option<mir::BasicBlock>,
902        unwind: mir::UnwindAction,
903        fn_span: Span,
904        kind: CallKind,
905        mergeable_succ: bool,
906    ) -> MergingSucc {
907        let source_info = mir::SourceInfo { span: fn_span, ..terminator.source_info };
908
909        // Create the callee. This is a fn ptr or zero-sized and hence a kind of scalar.
910        let callee = self.codegen_operand(bx, func);
911
912        let (instance, mut llfn) = match *callee.layout.ty.kind() {
913            ty::FnDef(def_id, generic_args) => {
914                let instance = ty::Instance::expect_resolve(
915                    bx.tcx(),
916                    bx.typing_env(),
917                    def_id,
918                    generic_args,
919                    fn_span,
920                );
921
922                match instance.def {
923                    // We don't need AsyncDropGlueCtorShim here because it is not `noop func`,
924                    // it is `func returning noop future`
925                    ty::InstanceKind::DropGlue(_, None) => {
926                        // Empty drop glue; a no-op.
927                        let target = target.unwrap();
928                        return helper.funclet_br(self, bx, target, mergeable_succ);
929                    }
930                    ty::InstanceKind::Intrinsic(def_id) => {
931                        let intrinsic = bx.tcx().intrinsic(def_id).unwrap();
932                        if let Some(merging_succ) = self.codegen_panic_intrinsic(
933                            &helper,
934                            bx,
935                            intrinsic,
936                            instance,
937                            source_info,
938                            target,
939                            unwind,
940                            mergeable_succ,
941                        ) {
942                            return merging_succ;
943                        }
944
945                        let result_layout =
946                            self.cx.layout_of(self.monomorphized_place_ty(destination.as_ref()));
947
948                        let (result, store_in_local) = if result_layout.is_zst() {
949                            (
950                                PlaceRef::new_sized(bx.const_undef(bx.type_ptr()), result_layout),
951                                None,
952                            )
953                        } else if let Some(local) = destination.as_local() {
954                            match self.locals[local] {
955                                LocalRef::Place(dest) => (dest, None),
956                                LocalRef::UnsizedPlace(_) => ::rustc_middle::util::bug::bug_fmt(format_args!("return type must be sized"))bug!("return type must be sized"),
957                                LocalRef::PendingOperand => {
958                                    // Currently, intrinsics always need a location to store
959                                    // the result, so we create a temporary `alloca` for the
960                                    // result.
961                                    let tmp = PlaceRef::alloca(bx, result_layout);
962                                    tmp.storage_live(bx);
963                                    (tmp, Some(local))
964                                }
965                                LocalRef::Operand(_) => {
966                                    ::rustc_middle::util::bug::bug_fmt(format_args!("place local already assigned to"));bug!("place local already assigned to");
967                                }
968                            }
969                        } else {
970                            (self.codegen_place(bx, destination.as_ref()), None)
971                        };
972
973                        if result.val.align < result.layout.align.abi {
974                            // Currently, MIR code generation does not create calls
975                            // that store directly to fields of packed structs (in
976                            // fact, the calls it creates write only to temps).
977                            //
978                            // If someone changes that, please update this code path
979                            // to create a temporary.
980                            ::rustc_middle::util::bug::span_bug_fmt(self.mir.span,
    format_args!("can\'t directly store to unaligned value"));span_bug!(self.mir.span, "can't directly store to unaligned value");
981                        }
982
983                        let args: Vec<_> =
984                            args.iter().map(|arg| self.codegen_operand(bx, &arg.node)).collect();
985
986                        match self.codegen_intrinsic_call(bx, instance, &args, result, source_info)
987                        {
988                            Ok(()) => {
989                                if let Some(local) = store_in_local {
990                                    let op = bx.load_operand(result);
991                                    result.storage_dead(bx);
992                                    self.overwrite_local(local, LocalRef::Operand(op));
993                                    self.debug_introduce_local(bx, local);
994                                }
995
996                                return if let Some(target) = target {
997                                    helper.funclet_br(self, bx, target, mergeable_succ)
998                                } else {
999                                    bx.unreachable();
1000                                    MergingSucc::False
1001                                };
1002                            }
1003                            Err(instance) => {
1004                                if intrinsic.must_be_overridden {
1005                                    ::rustc_middle::util::bug::span_bug_fmt(fn_span,
    format_args!("intrinsic {0} must be overridden by codegen backend, but isn\'t",
        intrinsic.name));span_bug!(
1006                                        fn_span,
1007                                        "intrinsic {} must be overridden by codegen backend, but isn't",
1008                                        intrinsic.name,
1009                                    );
1010                                }
1011                                (Some(instance), None)
1012                            }
1013                        }
1014                    }
1015
1016                    _ if kind == CallKind::Tail
1017                        && instance.def.requires_caller_location(bx.tcx()) =>
1018                    {
1019                        if let Some(hir_id) =
1020                            terminator.source_info.scope.lint_root(&self.mir.source_scopes)
1021                        {
1022                            bx.tcx().emit_node_lint(TAIL_CALL_TRACK_CALLER, hir_id, rustc_errors::DiagDecorator(|d| {
1023                                _ = d.primary_message("tail calling a function marked with `#[track_caller]` has no special effect").span(fn_span)
1024                            }));
1025                        }
1026
1027                        let instance = ty::Instance::resolve_for_fn_ptr(
1028                            bx.tcx(),
1029                            bx.typing_env(),
1030                            def_id,
1031                            generic_args,
1032                        )
1033                        .unwrap();
1034
1035                        (None, Some(bx.get_fn_addr(instance)))
1036                    }
1037                    _ => (Some(instance), None),
1038                }
1039            }
1040            ty::FnPtr(..) => (None, Some(callee.immediate())),
1041            _ => ::rustc_middle::util::bug::bug_fmt(format_args!("{0} is not callable",
        callee.layout.ty))bug!("{} is not callable", callee.layout.ty),
1042        };
1043
1044        if let Some(instance) = instance
1045            && let Some(name) = bx.tcx().codegen_fn_attrs(instance.def_id()).symbol_name
1046            && name.as_str().starts_with("llvm.")
1047            // This is the only LLVM intrinsic we use that unwinds
1048            // FIXME either add unwind support to codegen_llvm_intrinsic_call or replace usage of
1049            // this intrinsic with something else
1050            && name.as_str() != "llvm.wasm.throw"
1051        {
1052            if !!instance.args.has_infer() {
    ::core::panicking::panic("assertion failed: !instance.args.has_infer()")
};assert!(!instance.args.has_infer());
1053            if !!instance.args.has_escaping_bound_vars() {
    ::core::panicking::panic("assertion failed: !instance.args.has_escaping_bound_vars()")
};assert!(!instance.args.has_escaping_bound_vars());
1054
1055            let result_layout =
1056                self.cx.layout_of(self.monomorphized_place_ty(destination.as_ref()));
1057
1058            let return_dest = if result_layout.is_zst() {
1059                ReturnDest::Nothing
1060            } else if let Some(index) = destination.as_local() {
1061                match self.locals[index] {
1062                    LocalRef::Place(dest) => ReturnDest::Store(dest),
1063                    LocalRef::UnsizedPlace(_) => ::rustc_middle::util::bug::bug_fmt(format_args!("return type must be sized"))bug!("return type must be sized"),
1064                    LocalRef::PendingOperand => {
1065                        // Handle temporary places, specifically `Operand` ones, as
1066                        // they don't have `alloca`s.
1067                        ReturnDest::DirectOperand(index)
1068                    }
1069                    LocalRef::Operand(_) => ::rustc_middle::util::bug::bug_fmt(format_args!("place local already assigned to"))bug!("place local already assigned to"),
1070                }
1071            } else {
1072                ReturnDest::Store(self.codegen_place(bx, destination.as_ref()))
1073            };
1074
1075            let args =
1076                args.into_iter().map(|arg| self.codegen_operand(bx, &arg.node)).collect::<Vec<_>>();
1077
1078            self.set_debug_loc(bx, source_info);
1079
1080            let llret =
1081                bx.codegen_llvm_intrinsic_call(instance, &args, self.mir[helper.bb].is_cleanup);
1082
1083            if let Some(target) = target {
1084                self.store_return(
1085                    bx,
1086                    return_dest,
1087                    &ArgAbi { layout: result_layout, mode: PassMode::Direct(ArgAttributes::new()) },
1088                    llret,
1089                );
1090                return helper.funclet_br(self, bx, target, mergeable_succ);
1091            } else {
1092                bx.unreachable();
1093                return MergingSucc::False;
1094            }
1095        }
1096
1097        // FIXME(eddyb) avoid computing this if possible, when `instance` is
1098        // available - right now `sig` is only needed for getting the `abi`
1099        // and figuring out how many extra args were passed to a C-variadic `fn`.
1100        let sig = callee.layout.ty.fn_sig(bx.tcx());
1101
1102        let extra_args = &args[sig.inputs().skip_binder().len()..];
1103        let extra_args = bx.tcx().mk_type_list_from_iter(extra_args.iter().map(|op_arg| {
1104            let op_ty = op_arg.node.ty(self.mir, bx.tcx());
1105            self.monomorphize(op_ty)
1106        }));
1107
1108        let fn_abi = match instance {
1109            Some(instance) => bx.fn_abi_of_instance(instance, extra_args),
1110            None => bx.fn_abi_of_fn_ptr(sig, extra_args),
1111        };
1112
1113        // The arguments we'll be passing. Plus one to account for outptr, if used.
1114        let arg_count = fn_abi.args.len() + fn_abi.ret.is_indirect() as usize;
1115
1116        let mut llargs = Vec::with_capacity(arg_count);
1117
1118        // We still need to call `make_return_dest` even if there's no `target`, since
1119        // `fn_abi.ret` could be `PassMode::Indirect`, even if it is uninhabited,
1120        // and `make_return_dest` adds the return-place indirect pointer to `llargs`.
1121        let destination = match kind {
1122            CallKind::Normal => {
1123                let return_dest = self.make_return_dest(bx, destination, &fn_abi.ret, &mut llargs);
1124                target.map(|target| (return_dest, target))
1125            }
1126            CallKind::Tail => {
1127                if fn_abi.ret.is_indirect() {
1128                    match self.make_return_dest(bx, destination, &fn_abi.ret, &mut llargs) {
1129                        ReturnDest::Nothing => {}
1130                        _ => ::rustc_middle::util::bug::bug_fmt(format_args!("tail calls to functions with indirect returns cannot store into a destination"))bug!(
1131                            "tail calls to functions with indirect returns cannot store into a destination"
1132                        ),
1133                    }
1134                }
1135                None
1136            }
1137        };
1138
1139        // Split the rust-call tupled arguments off.
1140        let (first_args, untuple) = if sig.abi() == ExternAbi::RustCall
1141            && let Some((tup, args)) = args.split_last()
1142        {
1143            (args, Some(tup))
1144        } else {
1145            (args, None)
1146        };
1147
1148        // Special logic for tail calls with `PassMode::Indirect { on_stack: false, .. }` arguments.
1149        //
1150        // Normally an indirect argument with `on_stack: false` would be passed as a pointer into
1151        // the caller's stack frame. For tail calls, that would be unsound, because the caller's
1152        // stack frame is overwritten by the callee's stack frame.
1153        //
1154        // Therefore we store the argument for the callee in the corresponding caller's slot.
1155        // Because guaranteed tail calls demand that the caller's signature matches the callee's,
1156        // the corresponding slot has the correct type.
1157        //
1158        // To handle cases like the one below, the tail call arguments must first be copied to a
1159        // temporary, and only then copied to the caller's argument slots.
1160        //
1161        // ```
1162        // // A struct big enough that it is not passed via registers.
1163        // pub struct Big([u64; 4]);
1164        //
1165        // fn swapper(a: Big, b: Big) -> (Big, Big) {
1166        //     become swapper_helper(b, a);
1167        // }
1168        // ```
1169        let mut tail_call_temporaries = ::alloc::vec::Vec::new()vec![];
1170        if kind == CallKind::Tail {
1171            tail_call_temporaries = ::alloc::vec::from_elem(None, first_args.len())vec![None; first_args.len()];
1172            // Copy the arguments that use `PassMode::Indirect { on_stack: false , ..}`
1173            // to temporary stack allocations. See the comment above.
1174            for (i, arg) in first_args.iter().enumerate() {
1175                if !#[allow(non_exhaustive_omitted_patterns)] match fn_abi.args[i].mode {
    PassMode::Indirect { on_stack: false, .. } => true,
    _ => false,
}matches!(fn_abi.args[i].mode, PassMode::Indirect { on_stack: false, .. }) {
1176                    continue;
1177                }
1178
1179                let op = self.codegen_operand(bx, &arg.node);
1180                let tmp = PlaceRef::alloca(bx, op.layout);
1181                bx.lifetime_start(tmp.val.llval, tmp.layout.size);
1182                op.store_with_annotation(bx, tmp);
1183
1184                tail_call_temporaries[i] = Some(tmp);
1185            }
1186        }
1187
1188        // When generating arguments we sometimes introduce temporary allocations with lifetime
1189        // that extend for the duration of a call. Keep track of those allocations and their sizes
1190        // to generate `lifetime_end` when the call returns.
1191        let mut lifetime_ends_after_call: Vec<(Bx::Value, Size)> = Vec::new();
1192        'make_args: for (i, arg) in first_args.iter().enumerate() {
1193            let mut op = self.codegen_operand(bx, &arg.node);
1194
1195            if let (0, Some(ty::InstanceKind::Virtual(_, idx))) = (i, instance.map(|i| i.def)) {
1196                match op.val {
1197                    Pair(data_ptr, meta) => {
1198                        // In the case of Rc<Self>, we need to explicitly pass a
1199                        // *mut RcInner<Self> with a Scalar (not ScalarPair) ABI. This is a hack
1200                        // that is understood elsewhere in the compiler as a method on
1201                        // `dyn Trait`.
1202                        // To get a `*mut RcInner<Self>`, we just keep unwrapping newtypes until
1203                        // we get a value of a built-in pointer type.
1204                        //
1205                        // This is also relevant for `Pin<&mut Self>`, where we need to peel the
1206                        // `Pin`.
1207                        while !op.layout.ty.is_raw_ptr() && !op.layout.ty.is_ref() {
1208                            let (idx, _) = op.layout.non_1zst_field(bx).expect(
1209                                "not exactly one non-1-ZST field in a `DispatchFromDyn` type",
1210                            );
1211                            op = op.extract_field(self, bx, idx.as_usize());
1212                        }
1213
1214                        // Now that we have `*dyn Trait` or `&dyn Trait`, split it up into its
1215                        // data pointer and vtable. Look up the method in the vtable, and pass
1216                        // the data pointer as the first argument.
1217                        llfn = Some(meth::VirtualIndex::from_index(idx).get_fn(
1218                            bx,
1219                            meta,
1220                            op.layout.ty,
1221                            fn_abi,
1222                        ));
1223                        llargs.push(data_ptr);
1224                        continue 'make_args;
1225                    }
1226                    Ref(PlaceValue { llval: data_ptr, llextra: Some(meta), .. }) => {
1227                        // by-value dynamic dispatch
1228                        llfn = Some(meth::VirtualIndex::from_index(idx).get_fn(
1229                            bx,
1230                            meta,
1231                            op.layout.ty,
1232                            fn_abi,
1233                        ));
1234                        llargs.push(data_ptr);
1235                        continue;
1236                    }
1237                    _ => {
1238                        ::rustc_middle::util::bug::span_bug_fmt(fn_span,
    format_args!("can\'t codegen a virtual call on {0:#?}", op));span_bug!(fn_span, "can't codegen a virtual call on {:#?}", op);
1239                    }
1240                }
1241            }
1242
1243            match kind {
1244                CallKind::Normal => {
1245                    // The callee needs to own the argument memory if we pass it
1246                    // by-ref, so make a local copy of non-immediate constants.
1247                    if let &mir::Operand::Copy(_) | &mir::Operand::Constant(_) = &arg.node
1248                        && let Ref(PlaceValue { llextra: None, .. }) = op.val
1249                    {
1250                        let tmp = PlaceRef::alloca(bx, op.layout);
1251                        bx.lifetime_start(tmp.val.llval, tmp.layout.size);
1252                        op.store_with_annotation(bx, tmp);
1253                        op.val = Ref(tmp.val);
1254                        lifetime_ends_after_call.push((tmp.val.llval, tmp.layout.size));
1255                    }
1256                }
1257                CallKind::Tail => {
1258                    if let PassMode::Indirect { on_stack: false, .. } = fn_abi.args[i].mode {
1259                        let Some(tmp) = tail_call_temporaries[i].take() else {
1260                            ::rustc_middle::util::bug::span_bug_fmt(fn_span,
    format_args!("missing temporary for indirect tail call argument #{0}", i))span_bug!(
1261                                fn_span,
1262                                "missing temporary for indirect tail call argument #{i}"
1263                            )
1264                        };
1265
1266                        let local = self.mir.args_iter().nth(i).unwrap();
1267
1268                        match &self.locals[local] {
1269                            LocalRef::Place(arg) => {
1270                                bx.typed_place_copy(arg.val, tmp.val, fn_abi.args[i].layout);
1271                                op.val = Ref(arg.val);
1272                            }
1273                            LocalRef::Operand(arg) => {
1274                                let Ref(place_value) = arg.val else {
1275                                    ::rustc_middle::util::bug::bug_fmt(format_args!("only `Ref` should use `PassMode::Indirect`"));bug!("only `Ref` should use `PassMode::Indirect`");
1276                                };
1277                                bx.typed_place_copy(place_value, tmp.val, fn_abi.args[i].layout);
1278                                op.val = arg.val;
1279                            }
1280                            LocalRef::UnsizedPlace(_) => {
1281                                ::rustc_middle::util::bug::span_bug_fmt(fn_span,
    format_args!("unsized types are not supported"))span_bug!(fn_span, "unsized types are not supported")
1282                            }
1283                            LocalRef::PendingOperand => {
1284                                ::rustc_middle::util::bug::span_bug_fmt(fn_span,
    format_args!("argument local should not be pending"))span_bug!(fn_span, "argument local should not be pending")
1285                            }
1286                        };
1287
1288                        bx.lifetime_end(tmp.val.llval, tmp.layout.size);
1289                    }
1290                }
1291            }
1292
1293            self.codegen_argument(
1294                bx,
1295                op,
1296                &mut llargs,
1297                &fn_abi.args[i],
1298                &mut lifetime_ends_after_call,
1299            );
1300        }
1301        let num_untupled = untuple.map(|tup| {
1302            self.codegen_arguments_untupled(
1303                bx,
1304                &tup.node,
1305                &mut llargs,
1306                &fn_abi.args[first_args.len()..],
1307                &mut lifetime_ends_after_call,
1308            )
1309        });
1310
1311        let needs_location =
1312            instance.is_some_and(|i| i.def.requires_caller_location(self.cx.tcx()));
1313        if needs_location {
1314            let mir_args = if let Some(num_untupled) = num_untupled {
1315                first_args.len() + num_untupled
1316            } else {
1317                args.len()
1318            };
1319            match (&fn_abi.args.len(), &(mir_args + 1)) {
    (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::Some(format_args!("#[track_caller] fn\'s must have 1 more argument in their ABI than in their MIR: {0:?} {1:?} {2:?}",
                        instance, fn_span, fn_abi)));
        }
    }
};assert_eq!(
1320                fn_abi.args.len(),
1321                mir_args + 1,
1322                "#[track_caller] fn's must have 1 more argument in their ABI than in their MIR: {instance:?} {fn_span:?} {fn_abi:?}",
1323            );
1324            let location = self.get_caller_location(bx, source_info);
1325            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/mir/block.rs:1325",
                        "rustc_codegen_ssa::mir::block", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/mir/block.rs"),
                        ::tracing_core::__macro_support::Option::Some(1325u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir::block"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("codegen_call_terminator({0:?}): location={1:?} (fn_span {2:?})",
                                                    terminator, location, fn_span) as &dyn Value))])
            });
    } else { ; }
};debug!(
1326                "codegen_call_terminator({:?}): location={:?} (fn_span {:?})",
1327                terminator, location, fn_span
1328            );
1329
1330            let last_arg = fn_abi.args.last().unwrap();
1331            self.codegen_argument(
1332                bx,
1333                location,
1334                &mut llargs,
1335                last_arg,
1336                &mut lifetime_ends_after_call,
1337            );
1338        }
1339
1340        let fn_ptr = match (instance, llfn) {
1341            (Some(instance), None) => bx.get_fn_addr(instance),
1342            (_, Some(llfn)) => llfn,
1343            _ => ::rustc_middle::util::bug::span_bug_fmt(fn_span,
    format_args!("no instance or llfn for call"))span_bug!(fn_span, "no instance or llfn for call"),
1344        };
1345        self.set_debug_loc(bx, source_info);
1346        helper.do_call(
1347            self,
1348            bx,
1349            fn_abi,
1350            fn_ptr,
1351            &llargs,
1352            destination,
1353            unwind,
1354            &lifetime_ends_after_call,
1355            instance,
1356            kind,
1357            mergeable_succ,
1358        )
1359    }
1360
1361    fn codegen_asm_terminator(
1362        &mut self,
1363        helper: TerminatorCodegenHelper<'tcx>,
1364        bx: &mut Bx,
1365        asm_macro: InlineAsmMacro,
1366        terminator: &mir::Terminator<'tcx>,
1367        template: &[ast::InlineAsmTemplatePiece],
1368        operands: &[mir::InlineAsmOperand<'tcx>],
1369        options: ast::InlineAsmOptions,
1370        line_spans: &[Span],
1371        targets: &[mir::BasicBlock],
1372        unwind: mir::UnwindAction,
1373        instance: Instance<'_>,
1374        mergeable_succ: bool,
1375    ) -> MergingSucc {
1376        let span = terminator.source_info.span;
1377
1378        let operands: Vec<_> = operands
1379            .iter()
1380            .map(|op| match *op {
1381                mir::InlineAsmOperand::In { reg, ref value } => {
1382                    let value = self.codegen_operand(bx, value);
1383                    InlineAsmOperandRef::In { reg, value }
1384                }
1385                mir::InlineAsmOperand::Out { reg, late, ref place } => {
1386                    let place = place.map(|place| self.codegen_place(bx, place.as_ref()));
1387                    InlineAsmOperandRef::Out { reg, late, place }
1388                }
1389                mir::InlineAsmOperand::InOut { reg, late, ref in_value, ref out_place } => {
1390                    let in_value = self.codegen_operand(bx, in_value);
1391                    let out_place =
1392                        out_place.map(|out_place| self.codegen_place(bx, out_place.as_ref()));
1393                    InlineAsmOperandRef::InOut { reg, late, in_value, out_place }
1394                }
1395                mir::InlineAsmOperand::Const { ref value } => {
1396                    let const_value = self.eval_mir_constant(value);
1397                    let string = common::asm_const_to_str(
1398                        bx.tcx(),
1399                        span,
1400                        const_value,
1401                        bx.layout_of(value.ty()),
1402                    );
1403                    InlineAsmOperandRef::Const { string }
1404                }
1405                mir::InlineAsmOperand::SymFn { ref value } => {
1406                    let const_ = self.monomorphize(value.const_);
1407                    if let ty::FnDef(def_id, args) = *const_.ty().kind() {
1408                        let instance = ty::Instance::resolve_for_fn_ptr(
1409                            bx.tcx(),
1410                            bx.typing_env(),
1411                            def_id,
1412                            args,
1413                        )
1414                        .unwrap();
1415                        InlineAsmOperandRef::SymFn { instance }
1416                    } else {
1417                        ::rustc_middle::util::bug::span_bug_fmt(span,
    format_args!("invalid type for asm sym (fn)"));span_bug!(span, "invalid type for asm sym (fn)");
1418                    }
1419                }
1420                mir::InlineAsmOperand::SymStatic { def_id } => {
1421                    InlineAsmOperandRef::SymStatic { def_id }
1422                }
1423                mir::InlineAsmOperand::Label { target_index } => {
1424                    InlineAsmOperandRef::Label { label: self.llbb(targets[target_index]) }
1425                }
1426            })
1427            .collect();
1428
1429        helper.do_inlineasm(
1430            self,
1431            bx,
1432            template,
1433            &operands,
1434            options,
1435            line_spans,
1436            if asm_macro.diverges(options) { None } else { targets.get(0).copied() },
1437            unwind,
1438            instance,
1439            mergeable_succ,
1440        )
1441    }
1442
1443    pub(crate) fn codegen_block(&mut self, mut bb: mir::BasicBlock) {
1444        let llbb = match self.try_llbb(bb) {
1445            Some(llbb) => llbb,
1446            None => return,
1447        };
1448        let bx = &mut Bx::build(self.cx, llbb);
1449        let mir = self.mir;
1450
1451        // MIR basic blocks stop at any function call. This may not be the case
1452        // for the backend's basic blocks, in which case we might be able to
1453        // combine multiple MIR basic blocks into a single backend basic block.
1454        loop {
1455            let data = &mir[bb];
1456
1457            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/mir/block.rs:1457",
                        "rustc_codegen_ssa::mir::block", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/mir/block.rs"),
                        ::tracing_core::__macro_support::Option::Some(1457u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir::block"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("codegen_block({0:?}={1:?})",
                                                    bb, data) as &dyn Value))])
            });
    } else { ; }
};debug!("codegen_block({:?}={:?})", bb, data);
1458
1459            for statement in &data.statements {
1460                self.codegen_statement(bx, statement);
1461            }
1462            self.codegen_stmt_debuginfos(bx, &data.after_last_stmt_debuginfos);
1463
1464            let merging_succ = self.codegen_terminator(bx, bb, data.terminator());
1465            if let MergingSucc::False = merging_succ {
1466                break;
1467            }
1468
1469            // We are merging the successor into the produced backend basic
1470            // block. Record that the successor should be skipped when it is
1471            // reached.
1472            //
1473            // Note: we must not have already generated code for the successor.
1474            // This is implicitly ensured by the reverse postorder traversal,
1475            // and the assertion explicitly guarantees that.
1476            let mut successors = data.terminator().successors();
1477            let succ = successors.next().unwrap();
1478            if !#[allow(non_exhaustive_omitted_patterns)] match self.cached_llbbs[succ] {
            CachedLlbb::None => true,
            _ => false,
        } {
    ::core::panicking::panic("assertion failed: matches!(self.cached_llbbs[succ], CachedLlbb::None)")
};assert!(matches!(self.cached_llbbs[succ], CachedLlbb::None));
1479            self.cached_llbbs[succ] = CachedLlbb::Skip;
1480            bb = succ;
1481        }
1482    }
1483
1484    pub(crate) fn codegen_block_as_unreachable(&mut self, bb: mir::BasicBlock) {
1485        let llbb = match self.try_llbb(bb) {
1486            Some(llbb) => llbb,
1487            None => return,
1488        };
1489        let bx = &mut Bx::build(self.cx, llbb);
1490        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/mir/block.rs:1490",
                        "rustc_codegen_ssa::mir::block", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/mir/block.rs"),
                        ::tracing_core::__macro_support::Option::Some(1490u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir::block"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("codegen_block_as_unreachable({0:?})",
                                                    bb) as &dyn Value))])
            });
    } else { ; }
};debug!("codegen_block_as_unreachable({:?})", bb);
1491        bx.unreachable();
1492    }
1493
1494    fn codegen_terminator(
1495        &mut self,
1496        bx: &mut Bx,
1497        bb: mir::BasicBlock,
1498        terminator: &'tcx mir::Terminator<'tcx>,
1499    ) -> MergingSucc {
1500        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/mir/block.rs:1500",
                        "rustc_codegen_ssa::mir::block", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/mir/block.rs"),
                        ::tracing_core::__macro_support::Option::Some(1500u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir::block"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("codegen_terminator: {0:?}",
                                                    terminator) as &dyn Value))])
            });
    } else { ; }
};debug!("codegen_terminator: {:?}", terminator);
1501
1502        let helper = TerminatorCodegenHelper { bb, terminator };
1503
1504        let mergeable_succ = || {
1505            // Note: any call to `switch_to_block` will invalidate a `true` value
1506            // of `mergeable_succ`.
1507            let mut successors = terminator.successors();
1508            if let Some(succ) = successors.next()
1509                && successors.next().is_none()
1510                && let &[succ_pred] = self.mir.basic_blocks.predecessors()[succ].as_slice()
1511            {
1512                // bb has a single successor, and bb is its only predecessor. This
1513                // makes it a candidate for merging.
1514                match (&succ_pred, &bb) {
    (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!(succ_pred, bb);
1515                true
1516            } else {
1517                false
1518            }
1519        };
1520
1521        self.set_debug_loc(bx, terminator.source_info);
1522        match terminator.kind {
1523            mir::TerminatorKind::UnwindResume => {
1524                self.codegen_resume_terminator(helper, bx);
1525                MergingSucc::False
1526            }
1527
1528            mir::TerminatorKind::UnwindTerminate(reason) => {
1529                self.codegen_terminate_terminator(helper, bx, terminator, reason);
1530                MergingSucc::False
1531            }
1532
1533            mir::TerminatorKind::Goto { target } => {
1534                helper.funclet_br(self, bx, target, mergeable_succ())
1535            }
1536
1537            mir::TerminatorKind::SwitchInt { ref discr, ref targets } => {
1538                self.codegen_switchint_terminator(helper, bx, discr, targets);
1539                MergingSucc::False
1540            }
1541
1542            mir::TerminatorKind::Return => {
1543                self.codegen_return_terminator(bx);
1544                MergingSucc::False
1545            }
1546
1547            mir::TerminatorKind::Unreachable => {
1548                bx.unreachable();
1549                MergingSucc::False
1550            }
1551
1552            mir::TerminatorKind::Drop { place, target, unwind, replace: _, drop, async_fut } => {
1553                if !(async_fut.is_none() && drop.is_none()) {
    {
        ::core::panicking::panic_fmt(format_args!("Async Drop must be expanded or reset to sync before codegen"));
    }
};assert!(
1554                    async_fut.is_none() && drop.is_none(),
1555                    "Async Drop must be expanded or reset to sync before codegen"
1556                );
1557                self.codegen_drop_terminator(
1558                    helper,
1559                    bx,
1560                    &terminator.source_info,
1561                    place,
1562                    target,
1563                    unwind,
1564                    mergeable_succ(),
1565                )
1566            }
1567
1568            mir::TerminatorKind::Assert { ref cond, expected, ref msg, target, unwind } => self
1569                .codegen_assert_terminator(
1570                    helper,
1571                    bx,
1572                    terminator,
1573                    cond,
1574                    expected,
1575                    msg,
1576                    target,
1577                    unwind,
1578                    mergeable_succ(),
1579                ),
1580
1581            mir::TerminatorKind::Call {
1582                ref func,
1583                ref args,
1584                destination,
1585                target,
1586                unwind,
1587                call_source: _,
1588                fn_span,
1589            } => self.codegen_call_terminator(
1590                helper,
1591                bx,
1592                terminator,
1593                func,
1594                args,
1595                destination,
1596                target,
1597                unwind,
1598                fn_span,
1599                CallKind::Normal,
1600                mergeable_succ(),
1601            ),
1602            mir::TerminatorKind::TailCall { ref func, ref args, fn_span } => self
1603                .codegen_call_terminator(
1604                    helper,
1605                    bx,
1606                    terminator,
1607                    func,
1608                    args,
1609                    mir::Place::from(mir::RETURN_PLACE),
1610                    None,
1611                    mir::UnwindAction::Unreachable,
1612                    fn_span,
1613                    CallKind::Tail,
1614                    mergeable_succ(),
1615                ),
1616            mir::TerminatorKind::CoroutineDrop | mir::TerminatorKind::Yield { .. } => {
1617                ::rustc_middle::util::bug::bug_fmt(format_args!("coroutine ops in codegen"))bug!("coroutine ops in codegen")
1618            }
1619            mir::TerminatorKind::FalseEdge { .. } | mir::TerminatorKind::FalseUnwind { .. } => {
1620                ::rustc_middle::util::bug::bug_fmt(format_args!("borrowck false edges in codegen"))bug!("borrowck false edges in codegen")
1621            }
1622
1623            mir::TerminatorKind::InlineAsm {
1624                asm_macro,
1625                template,
1626                ref operands,
1627                options,
1628                line_spans,
1629                ref targets,
1630                unwind,
1631            } => self.codegen_asm_terminator(
1632                helper,
1633                bx,
1634                asm_macro,
1635                terminator,
1636                template,
1637                operands,
1638                options,
1639                line_spans,
1640                targets,
1641                unwind,
1642                self.instance,
1643                mergeable_succ(),
1644            ),
1645        }
1646    }
1647
1648    fn codegen_argument(
1649        &mut self,
1650        bx: &mut Bx,
1651        op: OperandRef<'tcx, Bx::Value>,
1652        llargs: &mut Vec<Bx::Value>,
1653        arg: &ArgAbi<'tcx, Ty<'tcx>>,
1654        lifetime_ends_after_call: &mut Vec<(Bx::Value, Size)>,
1655    ) {
1656        match arg.mode {
1657            PassMode::Ignore => return,
1658            PassMode::Cast { pad_i32: true, .. } => {
1659                // Fill padding with undef value, where applicable.
1660                llargs.push(bx.const_undef(bx.reg_backend_type(&Reg::i32())));
1661            }
1662            PassMode::Pair(..) => match op.val {
1663                Pair(a, b) => {
1664                    llargs.push(a);
1665                    llargs.push(b);
1666                    return;
1667                }
1668                _ => ::rustc_middle::util::bug::bug_fmt(format_args!("codegen_argument: {0:?} invalid for pair argument",
        op))bug!("codegen_argument: {:?} invalid for pair argument", op),
1669            },
1670            PassMode::Indirect { attrs: _, meta_attrs: Some(_), on_stack: _ } => match op.val {
1671                Ref(PlaceValue { llval: a, llextra: Some(b), .. }) => {
1672                    llargs.push(a);
1673                    llargs.push(b);
1674                    return;
1675                }
1676                _ => ::rustc_middle::util::bug::bug_fmt(format_args!("codegen_argument: {0:?} invalid for unsized indirect argument",
        op))bug!("codegen_argument: {:?} invalid for unsized indirect argument", op),
1677            },
1678            _ => {}
1679        }
1680
1681        // Force by-ref if we have to load through a cast pointer.
1682        let (mut llval, align, by_ref) = match op.val {
1683            Immediate(_) | Pair(..) => match arg.mode {
1684                PassMode::Indirect { attrs, .. } => {
1685                    // Indirect argument may have higher alignment requirements than the type's
1686                    // alignment. This can happen, e.g. when passing types with <4 byte alignment
1687                    // on the stack on x86.
1688                    let required_align = match attrs.pointee_align {
1689                        Some(pointee_align) => cmp::max(pointee_align, arg.layout.align.abi),
1690                        None => arg.layout.align.abi,
1691                    };
1692                    let scratch = PlaceValue::alloca(bx, arg.layout.size, required_align);
1693                    bx.lifetime_start(scratch.llval, arg.layout.size);
1694                    op.store_with_annotation(bx, scratch.with_type(arg.layout));
1695                    lifetime_ends_after_call.push((scratch.llval, arg.layout.size));
1696                    (scratch.llval, scratch.align, true)
1697                }
1698                PassMode::Cast { .. } => {
1699                    let scratch = PlaceRef::alloca(bx, arg.layout);
1700                    op.store_with_annotation(bx, scratch);
1701                    (scratch.val.llval, scratch.val.align, true)
1702                }
1703                _ => (op.immediate_or_packed_pair(bx), arg.layout.align.abi, false),
1704            },
1705            Ref(op_place_val) => match arg.mode {
1706                PassMode::Indirect { attrs, .. } => {
1707                    let required_align = match attrs.pointee_align {
1708                        Some(pointee_align) => cmp::max(pointee_align, arg.layout.align.abi),
1709                        None => arg.layout.align.abi,
1710                    };
1711                    if op_place_val.align < required_align {
1712                        // For `foo(packed.large_field)`, and types with <4 byte alignment on x86,
1713                        // alignment requirements may be higher than the type's alignment, so copy
1714                        // to a higher-aligned alloca.
1715                        let scratch = PlaceValue::alloca(bx, arg.layout.size, required_align);
1716                        bx.lifetime_start(scratch.llval, arg.layout.size);
1717                        bx.typed_place_copy(scratch, op_place_val, op.layout);
1718                        lifetime_ends_after_call.push((scratch.llval, arg.layout.size));
1719                        (scratch.llval, scratch.align, true)
1720                    } else {
1721                        (op_place_val.llval, op_place_val.align, true)
1722                    }
1723                }
1724                _ => (op_place_val.llval, op_place_val.align, true),
1725            },
1726            ZeroSized => match arg.mode {
1727                PassMode::Indirect { on_stack, .. } => {
1728                    if on_stack {
1729                        // It doesn't seem like any target can have `byval` ZSTs, so this assert
1730                        // is here to replace a would-be untested codepath.
1731                        ::rustc_middle::util::bug::bug_fmt(format_args!("ZST {0:?} passed on stack with abi {1:?}",
        op, arg));bug!("ZST {op:?} passed on stack with abi {arg:?}");
1732                    }
1733                    // Though `extern "Rust"` doesn't pass ZSTs, some ABIs pass
1734                    // a pointer for `repr(C)` structs even when empty, so get
1735                    // one from an `alloca` (which can be left uninitialized).
1736                    let scratch = PlaceRef::alloca(bx, arg.layout);
1737                    (scratch.val.llval, scratch.val.align, true)
1738                }
1739                _ => ::rustc_middle::util::bug::bug_fmt(format_args!("ZST {0:?} wasn\'t ignored, but was passed with abi {1:?}",
        op, arg))bug!("ZST {op:?} wasn't ignored, but was passed with abi {arg:?}"),
1740            },
1741        };
1742
1743        if by_ref && !arg.is_indirect() {
1744            // Have to load the argument, maybe while casting it.
1745            if let PassMode::Cast { cast, pad_i32: _ } = &arg.mode {
1746                // The ABI mandates that the value is passed as a different struct representation.
1747                // Spill and reload it from the stack to convert from the Rust representation to
1748                // the ABI representation.
1749                let scratch_size = cast.size(bx);
1750                let scratch_align = cast.align(bx);
1751                // Note that the ABI type may be either larger or smaller than the Rust type,
1752                // due to the presence or absence of trailing padding. For example:
1753                // - On some ABIs, the Rust layout { f64, f32, <f32 padding> } may omit padding
1754                //   when passed by value, making it smaller.
1755                // - On some ABIs, the Rust layout { u16, u16, u16 } may be padded up to 8 bytes
1756                //   when passed by value, making it larger.
1757                let copy_bytes = cmp::min(cast.unaligned_size(bx).bytes(), arg.layout.size.bytes());
1758                // Allocate some scratch space...
1759                let llscratch = bx.alloca(scratch_size, scratch_align);
1760                bx.lifetime_start(llscratch, scratch_size);
1761                // ...memcpy the value...
1762                bx.memcpy(
1763                    llscratch,
1764                    scratch_align,
1765                    llval,
1766                    align,
1767                    bx.const_usize(copy_bytes),
1768                    MemFlags::empty(),
1769                    None,
1770                );
1771                // ...and then load it with the ABI type.
1772                llval = load_cast(bx, cast, llscratch, scratch_align);
1773                bx.lifetime_end(llscratch, scratch_size);
1774            } else {
1775                // We can't use `PlaceRef::load` here because the argument
1776                // may have a type we don't treat as immediate, but the ABI
1777                // used for this call is passing it by-value. In that case,
1778                // the load would just produce `OperandValue::Ref` instead
1779                // of the `OperandValue::Immediate` we need for the call.
1780                llval = bx.load(bx.backend_type(arg.layout), llval, align);
1781                if let BackendRepr::Scalar(scalar) = arg.layout.backend_repr {
1782                    if scalar.is_bool() {
1783                        bx.range_metadata(llval, WrappingRange { start: 0, end: 1 });
1784                    }
1785                    // We store bools as `i8` so we need to truncate to `i1`.
1786                    llval = bx.to_immediate_scalar(llval, scalar);
1787                }
1788            }
1789        }
1790
1791        llargs.push(llval);
1792    }
1793
1794    fn codegen_arguments_untupled(
1795        &mut self,
1796        bx: &mut Bx,
1797        operand: &mir::Operand<'tcx>,
1798        llargs: &mut Vec<Bx::Value>,
1799        args: &[ArgAbi<'tcx, Ty<'tcx>>],
1800        lifetime_ends_after_call: &mut Vec<(Bx::Value, Size)>,
1801    ) -> usize {
1802        let tuple = self.codegen_operand(bx, operand);
1803
1804        // Handle both by-ref and immediate tuples.
1805        if let Ref(place_val) = tuple.val {
1806            if place_val.llextra.is_some() {
1807                ::rustc_middle::util::bug::bug_fmt(format_args!("closure arguments must be sized"));bug!("closure arguments must be sized");
1808            }
1809            let tuple_ptr = place_val.with_type(tuple.layout);
1810            for i in 0..tuple.layout.fields.count() {
1811                let field_ptr = tuple_ptr.project_field(bx, i);
1812                let field = bx.load_operand(field_ptr);
1813                self.codegen_argument(bx, field, llargs, &args[i], lifetime_ends_after_call);
1814            }
1815        } else {
1816            // If the tuple is immediate, the elements are as well.
1817            for i in 0..tuple.layout.fields.count() {
1818                let op = tuple.extract_field(self, bx, i);
1819                self.codegen_argument(bx, op, llargs, &args[i], lifetime_ends_after_call);
1820            }
1821        }
1822        tuple.layout.fields.count()
1823    }
1824
1825    pub(super) fn get_caller_location(
1826        &mut self,
1827        bx: &mut Bx,
1828        source_info: mir::SourceInfo,
1829    ) -> OperandRef<'tcx, Bx::Value> {
1830        self.mir.caller_location_span(source_info, self.caller_location, bx.tcx(), |span: Span| {
1831            let const_loc = bx.tcx().span_as_caller_location(span);
1832            OperandRef::from_const(bx, const_loc, bx.tcx().caller_location_ty())
1833        })
1834    }
1835
1836    fn get_personality_slot(&mut self, bx: &mut Bx) -> PlaceRef<'tcx, Bx::Value> {
1837        let cx = bx.cx();
1838        if let Some(slot) = self.personality_slot {
1839            slot
1840        } else {
1841            let layout = cx.layout_of(Ty::new_tup(
1842                cx.tcx(),
1843                &[Ty::new_mut_ptr(cx.tcx(), cx.tcx().types.u8), cx.tcx().types.i32],
1844            ));
1845            let slot = PlaceRef::alloca(bx, layout);
1846            self.personality_slot = Some(slot);
1847            slot
1848        }
1849    }
1850
1851    /// Returns the landing/cleanup pad wrapper around the given basic block.
1852    // FIXME(eddyb) rename this to `eh_pad_for`.
1853    fn landing_pad_for(&mut self, bb: mir::BasicBlock) -> Bx::BasicBlock {
1854        if let Some(landing_pad) = self.landing_pads[bb] {
1855            return landing_pad;
1856        }
1857
1858        let landing_pad = self.landing_pad_for_uncached(bb);
1859        self.landing_pads[bb] = Some(landing_pad);
1860        landing_pad
1861    }
1862
1863    // FIXME(eddyb) rename this to `eh_pad_for_uncached`.
1864    fn landing_pad_for_uncached(&mut self, bb: mir::BasicBlock) -> Bx::BasicBlock {
1865        let llbb = self.llbb(bb);
1866        if base::wants_new_eh_instructions(self.cx.sess()) {
1867            let cleanup_bb = Bx::append_block(self.cx, self.llfn, &::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("funclet_{0:?}", bb))
    })format!("funclet_{bb:?}"));
1868            let mut cleanup_bx = Bx::build(self.cx, cleanup_bb);
1869            let funclet = cleanup_bx.cleanup_pad(None, &[]);
1870            cleanup_bx.br(llbb);
1871            self.funclets[bb] = Some(funclet);
1872            cleanup_bb
1873        } else {
1874            let cleanup_llbb = Bx::append_block(self.cx, self.llfn, "cleanup");
1875            let mut cleanup_bx = Bx::build(self.cx, cleanup_llbb);
1876
1877            let llpersonality = self.cx.eh_personality();
1878            let (exn0, exn1) = cleanup_bx.cleanup_landing_pad(llpersonality);
1879
1880            let slot = self.get_personality_slot(&mut cleanup_bx);
1881            slot.storage_live(&mut cleanup_bx);
1882            Pair(exn0, exn1).store(&mut cleanup_bx, slot);
1883
1884            cleanup_bx.br(llbb);
1885            cleanup_llbb
1886        }
1887    }
1888
1889    fn unreachable_block(&mut self) -> Bx::BasicBlock {
1890        self.unreachable_block.unwrap_or_else(|| {
1891            let llbb = Bx::append_block(self.cx, self.llfn, "unreachable");
1892            let mut bx = Bx::build(self.cx, llbb);
1893            bx.unreachable();
1894            self.unreachable_block = Some(llbb);
1895            llbb
1896        })
1897    }
1898
1899    fn terminate_block(&mut self, reason: UnwindTerminateReason) -> Bx::BasicBlock {
1900        if let Some((cached_bb, cached_reason)) = self.terminate_block
1901            && reason == cached_reason
1902        {
1903            return cached_bb;
1904        }
1905
1906        let funclet;
1907        let llbb;
1908        let mut bx;
1909        if base::wants_new_eh_instructions(self.cx.sess()) {
1910            // This is a basic block that we're aborting the program for,
1911            // notably in an `extern` function. These basic blocks are inserted
1912            // so that we assert that `extern` functions do indeed not panic,
1913            // and if they do we abort the process.
1914            //
1915            // On MSVC these are tricky though (where we're doing funclets). If
1916            // we were to do a cleanuppad (like below) the normal functions like
1917            // `longjmp` would trigger the abort logic, terminating the
1918            // program. Instead we insert the equivalent of `catch(...)` for C++
1919            // which magically doesn't trigger when `longjmp` files over this
1920            // frame.
1921            //
1922            // Lots more discussion can be found on #48251 but this codegen is
1923            // modeled after clang's for:
1924            //
1925            //      try {
1926            //          foo();
1927            //      } catch (...) {
1928            //          bar();
1929            //      }
1930            //
1931            // which creates an IR snippet like
1932            //
1933            //      cs_terminate:
1934            //         %cs = catchswitch within none [%cp_terminate] unwind to caller
1935            //      cp_terminate:
1936            //         %cp = catchpad within %cs [null, i32 64, null]
1937            //         ...
1938
1939            llbb = Bx::append_block(self.cx, self.llfn, "cs_terminate");
1940            let cp_llbb = Bx::append_block(self.cx, self.llfn, "cp_terminate");
1941
1942            let mut cs_bx = Bx::build(self.cx, llbb);
1943            let cs = cs_bx.catch_switch(None, None, &[cp_llbb]);
1944
1945            bx = Bx::build(self.cx, cp_llbb);
1946            let null =
1947                bx.const_null(bx.type_ptr_ext(bx.cx().data_layout().instruction_address_space));
1948
1949            // The `null` in first argument here is actually a RTTI type
1950            // descriptor for the C++ personality function, but `catch (...)`
1951            // has no type so it's null.
1952            let args = if base::wants_msvc_seh(self.cx.sess()) {
1953                // This bitmask is a single `HT_IsStdDotDot` flag, which
1954                // represents that this is a C++-style `catch (...)` block that
1955                // only captures programmatic exceptions, not all SEH
1956                // exceptions. The second `null` points to a non-existent
1957                // `alloca` instruction, which an LLVM pass would inline into
1958                // the initial SEH frame allocation.
1959                let adjectives = bx.const_i32(0x40);
1960                &[null, adjectives, null] as &[_]
1961            } else {
1962                // Specifying more arguments than necessary usually doesn't
1963                // hurt, but the `WasmEHPrepare` LLVM pass does not recognize
1964                // anything other than a single `null` as a `catch (...)` block,
1965                // leading to problems down the line during instruction
1966                // selection.
1967                &[null] as &[_]
1968            };
1969
1970            funclet = Some(bx.catch_pad(cs, args));
1971        } else {
1972            llbb = Bx::append_block(self.cx, self.llfn, "terminate");
1973            bx = Bx::build(self.cx, llbb);
1974
1975            let llpersonality = self.cx.eh_personality();
1976            bx.filter_landing_pad(llpersonality);
1977
1978            funclet = None;
1979        }
1980
1981        self.set_debug_loc(&mut bx, mir::SourceInfo::outermost(self.mir.span));
1982
1983        let (fn_abi, fn_ptr, instance) =
1984            common::build_langcall(&bx, self.mir.span, reason.lang_item());
1985        if is_call_from_compiler_builtins_to_upstream_monomorphization(bx.tcx(), instance) {
1986            bx.abort();
1987        } else {
1988            let fn_ty = bx.fn_decl_backend_type(fn_abi);
1989
1990            let llret = bx.call(fn_ty, None, Some(fn_abi), fn_ptr, &[], funclet.as_ref(), None);
1991            bx.apply_attrs_to_cleanup_callsite(llret);
1992        }
1993
1994        bx.unreachable();
1995
1996        self.terminate_block = Some((llbb, reason));
1997        llbb
1998    }
1999
2000    /// Get the backend `BasicBlock` for a MIR `BasicBlock`, either already
2001    /// cached in `self.cached_llbbs`, or created on demand (and cached).
2002    // FIXME(eddyb) rename `llbb` and other `ll`-prefixed things to use a
2003    // more backend-agnostic prefix such as `cg` (i.e. this would be `cgbb`).
2004    pub fn llbb(&mut self, bb: mir::BasicBlock) -> Bx::BasicBlock {
2005        self.try_llbb(bb).unwrap()
2006    }
2007
2008    /// Like `llbb`, but may fail if the basic block should be skipped.
2009    pub(crate) fn try_llbb(&mut self, bb: mir::BasicBlock) -> Option<Bx::BasicBlock> {
2010        match self.cached_llbbs[bb] {
2011            CachedLlbb::None => {
2012                let llbb = Bx::append_block(self.cx, self.llfn, &::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0:?}", bb))
    })format!("{bb:?}"));
2013                self.cached_llbbs[bb] = CachedLlbb::Some(llbb);
2014                Some(llbb)
2015            }
2016            CachedLlbb::Some(llbb) => Some(llbb),
2017            CachedLlbb::Skip => None,
2018        }
2019    }
2020
2021    fn make_return_dest(
2022        &mut self,
2023        bx: &mut Bx,
2024        dest: mir::Place<'tcx>,
2025        fn_ret: &ArgAbi<'tcx, Ty<'tcx>>,
2026        llargs: &mut Vec<Bx::Value>,
2027    ) -> ReturnDest<'tcx, Bx::Value> {
2028        // If the return is ignored, we can just return a do-nothing `ReturnDest`.
2029        if fn_ret.is_ignore() {
2030            return ReturnDest::Nothing;
2031        }
2032        let dest = if let Some(index) = dest.as_local() {
2033            match self.locals[index] {
2034                LocalRef::Place(dest) => dest,
2035                LocalRef::UnsizedPlace(_) => ::rustc_middle::util::bug::bug_fmt(format_args!("return type must be sized"))bug!("return type must be sized"),
2036                LocalRef::PendingOperand => {
2037                    // Handle temporary places, specifically `Operand` ones, as
2038                    // they don't have `alloca`s.
2039                    return if fn_ret.is_indirect() {
2040                        // Odd, but possible, case, we have an operand temporary,
2041                        // but the calling convention has an indirect return.
2042                        let tmp = PlaceRef::alloca(bx, fn_ret.layout);
2043                        tmp.storage_live(bx);
2044                        llargs.push(tmp.val.llval);
2045                        ReturnDest::IndirectOperand(tmp, index)
2046                    } else {
2047                        ReturnDest::DirectOperand(index)
2048                    };
2049                }
2050                LocalRef::Operand(_) => {
2051                    ::rustc_middle::util::bug::bug_fmt(format_args!("place local already assigned to"));bug!("place local already assigned to");
2052                }
2053            }
2054        } else {
2055            self.codegen_place(bx, dest.as_ref())
2056        };
2057        if fn_ret.is_indirect() {
2058            if dest.val.align < dest.layout.align.abi {
2059                // Currently, MIR code generation does not create calls
2060                // that store directly to fields of packed structs (in
2061                // fact, the calls it creates write only to temps).
2062                //
2063                // If someone changes that, please update this code path
2064                // to create a temporary.
2065                ::rustc_middle::util::bug::span_bug_fmt(self.mir.span,
    format_args!("can\'t directly store to unaligned value"));span_bug!(self.mir.span, "can't directly store to unaligned value");
2066            }
2067            llargs.push(dest.val.llval);
2068            ReturnDest::Nothing
2069        } else {
2070            ReturnDest::Store(dest)
2071        }
2072    }
2073
2074    // Stores the return value of a function call into it's final location.
2075    fn store_return(
2076        &mut self,
2077        bx: &mut Bx,
2078        dest: ReturnDest<'tcx, Bx::Value>,
2079        ret_abi: &ArgAbi<'tcx, Ty<'tcx>>,
2080        llval: Bx::Value,
2081    ) {
2082        use self::ReturnDest::*;
2083
2084        match dest {
2085            Nothing => (),
2086            Store(dst) => bx.store_arg(ret_abi, llval, dst),
2087            IndirectOperand(tmp, index) => {
2088                let op = bx.load_operand(tmp);
2089                tmp.storage_dead(bx);
2090                self.overwrite_local(index, LocalRef::Operand(op));
2091                self.debug_introduce_local(bx, index);
2092            }
2093            DirectOperand(index) => {
2094                // If there is a cast, we have to store and reload.
2095                let op = if let PassMode::Cast { .. } = ret_abi.mode {
2096                    let tmp = PlaceRef::alloca(bx, ret_abi.layout);
2097                    tmp.storage_live(bx);
2098                    bx.store_arg(ret_abi, llval, tmp);
2099                    let op = bx.load_operand(tmp);
2100                    tmp.storage_dead(bx);
2101                    op
2102                } else {
2103                    OperandRef::from_immediate_or_packed_pair(bx, llval, ret_abi.layout)
2104                };
2105                self.overwrite_local(index, LocalRef::Operand(op));
2106                self.debug_introduce_local(bx, index);
2107            }
2108        }
2109    }
2110}
2111
2112enum ReturnDest<'tcx, V> {
2113    /// Do nothing; the return value is indirect or ignored.
2114    Nothing,
2115    /// Store the return value to the pointer.
2116    Store(PlaceRef<'tcx, V>),
2117    /// Store an indirect return value to an operand local place.
2118    IndirectOperand(PlaceRef<'tcx, V>, mir::Local),
2119    /// Store a direct return value to an operand local place.
2120    DirectOperand(mir::Local),
2121}
2122
2123fn load_cast<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
2124    bx: &mut Bx,
2125    cast: &CastTarget,
2126    ptr: Bx::Value,
2127    align: Align,
2128) -> Bx::Value {
2129    let cast_ty = bx.cast_backend_type(cast);
2130    if let Some(offset_from_start) = cast.rest_offset {
2131        if !cast.prefix[1..].iter().all(|p| p.is_none()) {
    ::core::panicking::panic("assertion failed: cast.prefix[1..].iter().all(|p| p.is_none())")
};assert!(cast.prefix[1..].iter().all(|p| p.is_none()));
2132        match (&cast.rest.unit.size, &cast.rest.total) {
    (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!(cast.rest.unit.size, cast.rest.total);
2133        let first_ty = bx.reg_backend_type(&cast.prefix[0].unwrap());
2134        let second_ty = bx.reg_backend_type(&cast.rest.unit);
2135        let first = bx.load(first_ty, ptr, align);
2136        let second_ptr = bx.inbounds_ptradd(ptr, bx.const_usize(offset_from_start.bytes()));
2137        let second = bx.load(second_ty, second_ptr, align.restrict_for_offset(offset_from_start));
2138        let res = bx.cx().const_poison(cast_ty);
2139        let res = bx.insert_value(res, first, 0);
2140        bx.insert_value(res, second, 1)
2141    } else {
2142        bx.load(cast_ty, ptr, align)
2143    }
2144}
2145
2146pub fn store_cast<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
2147    bx: &mut Bx,
2148    cast: &CastTarget,
2149    value: Bx::Value,
2150    ptr: Bx::Value,
2151    align: Align,
2152) {
2153    if let Some(offset_from_start) = cast.rest_offset {
2154        if !cast.prefix[1..].iter().all(|p| p.is_none()) {
    ::core::panicking::panic("assertion failed: cast.prefix[1..].iter().all(|p| p.is_none())")
};assert!(cast.prefix[1..].iter().all(|p| p.is_none()));
2155        match (&cast.rest.unit.size, &cast.rest.total) {
    (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!(cast.rest.unit.size, cast.rest.total);
2156        if !cast.prefix[0].is_some() {
    ::core::panicking::panic("assertion failed: cast.prefix[0].is_some()")
};assert!(cast.prefix[0].is_some());
2157        let first = bx.extract_value(value, 0);
2158        let second = bx.extract_value(value, 1);
2159        bx.store(first, ptr, align);
2160        let second_ptr = bx.inbounds_ptradd(ptr, bx.const_usize(offset_from_start.bytes()));
2161        bx.store(second, second_ptr, align.restrict_for_offset(offset_from_start));
2162    } else {
2163        bx.store(value, ptr, align);
2164    };
2165}