Skip to main content

rustc_codegen_ssa/mir/
block.rs

1use std::cmp;
2use std::ops::Range;
3
4use rustc_abi::{
5    Align, ArmCall, BackendRepr, CanonAbi, ExternAbi, FieldsShape, HasDataLayout, Reg, Size,
6    VariantIdx, Variants, WrappingRange,
7};
8use rustc_ast as ast;
9use rustc_ast::{InlineAsmOptions, InlineAsmTemplatePiece};
10use rustc_data_structures::packed::Pu128;
11use rustc_hir::attrs::AttributeKind;
12use rustc_hir::attrs::lang_items::LangItem;
13use rustc_lint_defs::builtin::TAIL_CALL_TRACK_CALLER;
14use rustc_middle::mir::interpret::{CTFE_ALLOC_SALT, Scalar};
15use rustc_middle::mir::{self, AssertKind, InlineAsmMacro, SwitchTargets, UnwindTerminateReason};
16use rustc_middle::ty::layout::{HasTyCtxt, LayoutOf, TyAndLayout, ValidityRequirement};
17use rustc_middle::ty::print::{with_no_trimmed_paths, with_no_visible_paths};
18use rustc_middle::ty::{self, Instance, Ty, TypeVisitableExt};
19use rustc_session::config::OptLevel;
20use rustc_span::{Span, Spanned, bug, span_bug};
21use rustc_target::callconv::{ArgAbi, ArgAttributes, CastTarget, FnAbi, IndirectMode, PassMode};
22use tracing::{debug, info};
23
24use super::operand::OperandRef;
25use super::operand::OperandValue::{self, Immediate, Pair, Ref, ZeroSized};
26use super::place::{PlaceRef, PlaceValue};
27use super::{CachedLlbb, FunctionCx, LocalRef};
28use crate::base::{self, is_call_from_compiler_builtins_to_upstream_monomorphization};
29use crate::common::{self, IntPredicate};
30use crate::diagnostics::CompilerBuiltinsCannotCall;
31use crate::mir::IntrinsicResult;
32use crate::traits::*;
33use crate::{MemFlags, meth};
34
35// Indicates if we are in the middle of merging a BB's successor into it. This
36// can happen when BB jumps directly to its successor and the successor has no
37// other predecessors.
38#[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::marker::StructuralPartialEq for MergingSucc { }
#[automatically_derived]
impl ::core::cmp::PartialEq for MergingSucc {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
            ::core::intrinsics::discriminant_value(other)
    }
}PartialEq)]
39enum MergingSucc {
40    False,
41    True,
42}
43
44/// Indicates to the call terminator codegen whether a call
45/// is a normal call or an explicit tail call.
46#[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::marker::StructuralPartialEq for CallKind { }
#[automatically_derived]
impl ::core::cmp::PartialEq for CallKind {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
            ::core::intrinsics::discriminant_value(other)
    }
}PartialEq)]
47enum CallKind {
48    Normal,
49    Tail,
50}
51
52/// Used by `FunctionCx::codegen_terminator` for emitting common patterns
53/// e.g., creating a basic block, calling a function, etc.
54struct TerminatorCodegenHelper<'tcx> {
55    bb: mir::BasicBlock,
56    terminator: &'tcx mir::Terminator<'tcx>,
57}
58
59impl<'a, 'tcx> TerminatorCodegenHelper<'tcx> {
60    /// Returns the appropriate `Funclet` for the current funclet, if on MSVC,
61    /// either already previously cached, or newly created, by `landing_pad_for`.
62    fn funclet<'b, Bx: BuilderMethods<'a, 'tcx>>(
63        &self,
64        fx: &'b mut FunctionCx<'a, 'tcx, Bx>,
65    ) -> Option<&'b Bx::Funclet> {
66        let cleanup_kinds = fx.cleanup_kinds.as_ref()?;
67        let funclet_bb = cleanup_kinds[self.bb].funclet_bb(self.bb)?;
68        // If `landing_pad_for` hasn't been called yet to create the `Funclet`,
69        // it has to be now. This may not seem necessary, as RPO should lead
70        // to all the unwind edges being visited (and so to `landing_pad_for`
71        // getting called for them), before building any of the blocks inside
72        // the funclet itself - however, if MIR contains edges that end up not
73        // being needed in the LLVM IR after monomorphization, the funclet may
74        // be unreachable, and we don't have yet a way to skip building it in
75        // such an eventuality (which may be a better solution than this).
76        if fx.funclets[funclet_bb].is_none() {
77            fx.landing_pad_for(funclet_bb);
78        }
79        Some(
80            fx.funclets[funclet_bb]
81                .as_ref()
82                .expect("landing_pad_for didn't also create funclets entry"),
83        )
84    }
85
86    /// Get a basic block (creating it if necessary), possibly with cleanup
87    /// stuff in it or next to it.
88    fn llbb_with_cleanup<Bx: BuilderMethods<'a, 'tcx>>(
89        &self,
90        fx: &mut FunctionCx<'a, 'tcx, Bx>,
91        target: mir::BasicBlock,
92    ) -> Bx::BasicBlock {
93        let (needs_landing_pad, is_cleanupret) = self.llbb_characteristics(fx, target);
94        let mut lltarget = fx.llbb(target);
95        if needs_landing_pad {
96            lltarget = fx.landing_pad_for(target);
97        }
98        if is_cleanupret {
99            // Cross-funclet jump - need a trampoline
100            if !base::wants_new_eh_instructions(&fx.cx.tcx().sess.target) {
    ::core::panicking::panic("assertion failed: base::wants_new_eh_instructions(&fx.cx.tcx().sess.target)")
};assert!(base::wants_new_eh_instructions(&fx.cx.tcx().sess.target));
101            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_codegen_ssa/src/mir/block.rs:101",
                        "rustc_codegen_ssa::mir::block", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_codegen_ssa/src/mir/block.rs"),
                        ::tracing_core::__macro_support::Option::Some(101u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("llbb_with_cleanup: creating cleanup trampoline for {0:?}",
                                                    target) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("llbb_with_cleanup: creating cleanup trampoline for {:?}", target);
102            let name = &::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0:?}_cleanup_trampoline_{1:?}",
                self.bb, target))
    })format!("{:?}_cleanup_trampoline_{:?}", self.bb, target);
103            let trampoline_llbb = Bx::append_block(fx.cx, fx.llfn, name);
104            let mut trampoline_bx = Bx::build(fx.cx, trampoline_llbb);
105            trampoline_bx.cleanup_ret(self.funclet(fx).unwrap(), Some(lltarget));
106            trampoline_llbb
107        } else {
108            lltarget
109        }
110    }
111
112    fn llbb_characteristics<Bx: BuilderMethods<'a, 'tcx>>(
113        &self,
114        fx: &mut FunctionCx<'a, 'tcx, Bx>,
115        target: mir::BasicBlock,
116    ) -> (bool, bool) {
117        if let Some(ref cleanup_kinds) = fx.cleanup_kinds {
118            let funclet_bb = cleanup_kinds[self.bb].funclet_bb(self.bb);
119            let target_funclet = cleanup_kinds[target].funclet_bb(target);
120            let (needs_landing_pad, is_cleanupret) = match (funclet_bb, target_funclet) {
121                (None, None) => (false, false),
122                (None, Some(_)) => (true, false),
123                (Some(f), Some(t_f)) => (f != t_f, f != t_f),
124                (Some(_), None) => {
125                    let span = self.terminator.source_info.span;
126                    ::rustc_span::macros::bug_impl(Some(span),
    format_args!("{0:?} - jump out of cleanup?", self.terminator),
    Location::caller());span_bug!(span, "{:?} - jump out of cleanup?", self.terminator);
127                }
128            };
129            (needs_landing_pad, is_cleanupret)
130        } else {
131            let needs_landing_pad = !fx.mir[self.bb].is_cleanup && fx.mir[target].is_cleanup;
132            let is_cleanupret = false;
133            (needs_landing_pad, is_cleanupret)
134        }
135    }
136
137    fn funclet_br<Bx: BuilderMethods<'a, 'tcx>>(
138        &self,
139        fx: &mut FunctionCx<'a, 'tcx, Bx>,
140        bx: &mut Bx,
141        target: mir::BasicBlock,
142        mergeable_succ: bool,
143        attributes: &[AttributeKind],
144    ) -> MergingSucc {
145        let (needs_landing_pad, is_cleanupret) = self.llbb_characteristics(fx, target);
146        if mergeable_succ && !needs_landing_pad && !is_cleanupret {
147            // We can merge the successor into this bb, so no need for a `br`.
148            MergingSucc::True
149        } else {
150            let mut lltarget = fx.llbb(target);
151            if needs_landing_pad {
152                lltarget = fx.landing_pad_for(target);
153            }
154            if is_cleanupret {
155                // micro-optimization: generate a `ret` rather than a jump
156                // to a trampoline.
157                bx.cleanup_ret(self.funclet(fx).unwrap(), Some(lltarget));
158            } else {
159                bx.br_with_attrs(lltarget, attributes);
160            }
161            MergingSucc::False
162        }
163    }
164
165    /// Call `fn_ptr` of `fn_abi` with the arguments `llargs`, the optional
166    /// return destination `destination` and the unwind action `unwind`.
167    /// The `return_slot` is [`ReturnSlot::Indirect`] for functions returning
168    /// via `PassMode::Indirect`, and points to a buffer where the return value
169    /// shall be stored.
170    fn do_call<Bx: BuilderMethods<'a, 'tcx>>(
171        &self,
172        fx: &mut FunctionCx<'a, 'tcx, Bx>,
173        bx: &mut Bx,
174        fn_abi: &'tcx FnAbi<'tcx, Ty<'tcx>>,
175        fn_ptr: Bx::Value,
176        return_slot: ReturnSlot<Bx::Value>,
177        llargs: &[Bx::Value],
178        destination: Option<(ReturnDest<'tcx, Bx::Value>, mir::BasicBlock)>,
179        mut unwind: mir::UnwindAction,
180        lifetime_ends_after_call: &[(Bx::Value, Size)],
181        instance: Option<Instance<'tcx>>,
182        kind: CallKind,
183        mergeable_succ: bool,
184    ) -> MergingSucc {
185        let tcx = bx.tcx();
186        if let Some(instance) = instance
187            && is_call_from_compiler_builtins_to_upstream_monomorphization(tcx, instance)
188        {
189            if destination.is_some() {
190                let caller_def = fx.instance.def_id();
191                let e = CompilerBuiltinsCannotCall {
192                    span: tcx.def_span(caller_def),
193                    caller: { let _guard = NoTrimmedGuard::new(); tcx.def_path_str(caller_def) }with_no_trimmed_paths!(tcx.def_path_str(caller_def)),
194                    callee: { let _guard = NoTrimmedGuard::new(); tcx.def_path_str(instance.def_id()) }with_no_trimmed_paths!(tcx.def_path_str(instance.def_id())),
195                };
196                tcx.dcx().emit_err(e);
197            } else {
198                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_codegen_ssa/src/mir/block.rs:198",
                        "rustc_codegen_ssa::mir::block", ::tracing::Level::INFO,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_codegen_ssa/src/mir/block.rs"),
                        ::tracing_core::__macro_support::Option::Some(198u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("compiler_builtins call to diverging function {0:?} replaced with abort",
                                                    instance.def_id()) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};info!(
199                    "compiler_builtins call to diverging function {:?} replaced with abort",
200                    instance.def_id()
201                );
202                bx.abort();
203                bx.unreachable();
204                return MergingSucc::False;
205            }
206        }
207
208        // If there is a cleanup block and the function we're calling can unwind, then
209        // do an invoke, otherwise do a call.
210        let fn_ty = bx.fn_decl_backend_type(fn_abi);
211
212        let caller_attrs = if bx.tcx().def_kind(fx.instance.def_id()).has_codegen_attrs() {
213            Some(bx.tcx().codegen_instance_attrs(fx.instance.def))
214        } else {
215            None
216        };
217        let caller_attrs = caller_attrs.as_deref();
218
219        if !fn_abi.can_unwind {
220            unwind = mir::UnwindAction::Unreachable;
221        }
222
223        let unwind_block = match unwind {
224            mir::UnwindAction::Cleanup(cleanup) => {
225                if !fx.nop_landing_pads.contains(cleanup) {
226                    Some(self.llbb_with_cleanup(fx, cleanup))
227                } else {
228                    None
229                }
230            }
231            mir::UnwindAction::Continue => None,
232            mir::UnwindAction::Unreachable => None,
233            mir::UnwindAction::Terminate(reason) => {
234                if fx.mir[self.bb].is_cleanup && base::wants_wasm_eh(&fx.cx.tcx().sess.target) {
235                    // For wasm, we need to generate a nested `cleanuppad within %outer_pad`
236                    // to catch exceptions during cleanup and call `panic_in_cleanup`.
237                    Some(fx.terminate_block(reason, Some(self.bb)))
238                } else if fx.mir[self.bb].is_cleanup
239                    && base::wants_new_eh_instructions(&fx.cx.tcx().sess.target)
240                {
241                    // MSVC SEH will abort automatically if an exception tries to
242                    // propagate out from cleanup.
243                    None
244                } else {
245                    Some(fx.terminate_block(reason, None))
246                }
247            }
248        };
249
250        if true {
    {
        match (&return_slot.is_indirect(), &fn_abi.ret.is_indirect()) {
            (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!("a return slot must be provided if and only if the return is `PassMode::Indirect`")));
                }
            }
        }
    };
};debug_assert_eq!(
251            return_slot.is_indirect(),
252            fn_abi.ret.is_indirect(),
253            "a return slot must be provided if and only if the return is `PassMode::Indirect`",
254        );
255
256        if kind == CallKind::Tail {
257            bx.tail_call(
258                fn_ty,
259                caller_attrs,
260                fn_abi,
261                fn_ptr,
262                return_slot,
263                llargs,
264                self.funclet(fx),
265                instance,
266            );
267            return MergingSucc::False;
268        }
269
270        if let Some(unwind_block) = unwind_block {
271            let ret_llbb = if let Some((_, target)) = destination {
272                self.llbb_with_cleanup(fx, target)
273            } else {
274                fx.unreachable_block()
275            };
276            let invokeret = bx.invoke(
277                fn_ty,
278                caller_attrs,
279                Some(fn_abi),
280                fn_ptr,
281                return_slot,
282                llargs,
283                ret_llbb,
284                unwind_block,
285                self.funclet(fx),
286                instance,
287            );
288            if fx.mir[self.bb].is_cleanup {
289                bx.apply_attrs_to_cleanup_callsite(invokeret);
290            }
291
292            if let Some((ret_dest, target)) = destination {
293                bx.switch_to_block(fx.llbb(target));
294                fx.set_debug_loc(bx, self.terminator.source_info);
295                for &(tmp, size) in lifetime_ends_after_call {
296                    bx.lifetime_end(tmp, size);
297                }
298                fx.store_return(bx, ret_dest, &fn_abi.ret, invokeret);
299
300                // If the return value was retagged as it was stored,
301                // then we might be in a different basic block now.
302                // Update the cached block for `target` to point to this new
303                // block, where codegen will continue.
304                fx.cached_llbbs[target] = CachedLlbb::Some(bx.llbb());
305            }
306            MergingSucc::False
307        } else {
308            let llret = bx.call(
309                fn_ty,
310                caller_attrs,
311                Some(fn_abi),
312                fn_ptr,
313                return_slot,
314                llargs,
315                self.funclet(fx),
316                instance,
317            );
318            if fx.mir[self.bb].is_cleanup {
319                bx.apply_attrs_to_cleanup_callsite(llret);
320            }
321
322            if let Some((ret_dest, target)) = destination {
323                for &(tmp, size) in lifetime_ends_after_call {
324                    bx.lifetime_end(tmp, size);
325                }
326                fx.store_return(bx, ret_dest, &fn_abi.ret, llret);
327                self.funclet_br(fx, bx, target, mergeable_succ, &[])
328            } else {
329                bx.unreachable();
330                MergingSucc::False
331            }
332        }
333    }
334
335    /// Generates inline assembly with optional `destination` and `unwind`.
336    fn do_inlineasm<Bx: BuilderMethods<'a, 'tcx>>(
337        &self,
338        fx: &mut FunctionCx<'a, 'tcx, Bx>,
339        bx: &mut Bx,
340        template: &[InlineAsmTemplatePiece],
341        operands: &[InlineAsmOperandRef<'tcx, Bx>],
342        options: InlineAsmOptions,
343        line_spans: &[Span],
344        destination: Option<mir::BasicBlock>,
345        unwind: mir::UnwindAction,
346        instance: Instance<'_>,
347        mergeable_succ: bool,
348    ) -> MergingSucc {
349        let unwind_target = match unwind {
350            mir::UnwindAction::Cleanup(cleanup) => {
351                if !fx.nop_landing_pads.contains(cleanup) {
352                    Some(self.llbb_with_cleanup(fx, cleanup))
353                } else {
354                    None
355                }
356            }
357            mir::UnwindAction::Terminate(reason) => Some(fx.terminate_block(reason, None)),
358            mir::UnwindAction::Continue => None,
359            mir::UnwindAction::Unreachable => None,
360        };
361
362        if operands.iter().any(|x| #[allow(non_exhaustive_omitted_patterns)] match x {
    InlineAsmOperandRef::Label { .. } => true,
    _ => false,
}matches!(x, InlineAsmOperandRef::Label { .. })) {
363            if !unwind_target.is_none() {
    ::core::panicking::panic("assertion failed: unwind_target.is_none()")
};assert!(unwind_target.is_none());
364            let ret_llbb = if let Some(target) = destination {
365                self.llbb_with_cleanup(fx, target)
366            } else {
367                fx.unreachable_block()
368            };
369
370            bx.codegen_inline_asm(
371                template,
372                operands,
373                options,
374                line_spans,
375                instance,
376                Some(ret_llbb),
377                None,
378            );
379            MergingSucc::False
380        } else if let Some(cleanup) = unwind_target {
381            let ret_llbb = if let Some(target) = destination {
382                self.llbb_with_cleanup(fx, target)
383            } else {
384                fx.unreachable_block()
385            };
386
387            bx.codegen_inline_asm(
388                template,
389                operands,
390                options,
391                line_spans,
392                instance,
393                Some(ret_llbb),
394                Some((cleanup, self.funclet(fx))),
395            );
396            MergingSucc::False
397        } else {
398            bx.codegen_inline_asm(template, operands, options, line_spans, instance, None, None);
399
400            if let Some(target) = destination {
401                self.funclet_br(fx, bx, target, mergeable_succ, &[])
402            } else {
403                bx.unreachable();
404                MergingSucc::False
405            }
406        }
407    }
408}
409
410/// Codegen implementations for some terminator variants.
411impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
412    /// Generates code for a `Resume` terminator.
413    fn codegen_resume_terminator(&mut self, helper: TerminatorCodegenHelper<'tcx>, bx: &mut Bx) {
414        if let Some(funclet) = helper.funclet(self) {
415            bx.cleanup_ret(funclet, None);
416        } else {
417            let slot = self.get_personality_slot(bx);
418            let exn0 = slot.project_field(bx, 0);
419            let exn0 = bx.load_operand(exn0).immediate();
420            let exn1 = slot.project_field(bx, 1);
421            let exn1 = bx.load_operand(exn1).immediate();
422            slot.storage_dead(bx);
423
424            bx.resume(exn0, exn1);
425        }
426    }
427
428    fn codegen_switchint_terminator(
429        &mut self,
430        helper: TerminatorCodegenHelper<'tcx>,
431        bx: &mut Bx,
432        discr: &mir::Operand<'tcx>,
433        targets: &SwitchTargets,
434    ) {
435        let discr = self.codegen_operand(bx, discr);
436        let discr_value = discr.immediate();
437        let switch_ty = discr.layout.ty;
438        // If our discriminant is a constant we can branch directly
439        if let Some(const_discr) = bx.const_to_opt_u128(discr_value, false) {
440            let target = targets.target_for_value(const_discr);
441            bx.br(helper.llbb_with_cleanup(self, target));
442            return;
443        };
444
445        let mut target_iter = targets.iter();
446        if target_iter.len() == 1 {
447            // If there are two targets (one conditional, one fallback), emit `br` instead of
448            // `switch`.
449            let (test_value, target) = target_iter.next().unwrap();
450            let otherwise = targets.otherwise();
451            let lltarget = helper.llbb_with_cleanup(self, target);
452            let llotherwise = helper.llbb_with_cleanup(self, otherwise);
453            let target_cold = self.cold_blocks[target];
454            let otherwise_cold = self.cold_blocks[otherwise];
455            // If `target_cold == otherwise_cold`, the branches have the same weight
456            // so there is no expectation. If they differ, the `target` branch is expected
457            // when the `otherwise` branch is cold.
458            let expect = if target_cold == otherwise_cold { None } else { Some(otherwise_cold) };
459            if switch_ty == bx.tcx().types.bool {
460                // Don't generate trivial icmps when switching on bool.
461                match test_value {
462                    0 => {
463                        let expect = expect.map(|e| !e);
464                        bx.cond_br_with_expect(discr_value, llotherwise, lltarget, expect);
465                    }
466                    1 => {
467                        bx.cond_br_with_expect(discr_value, lltarget, llotherwise, expect);
468                    }
469                    _ => ::rustc_span::macros::bug_impl(None, format_args!("impossible case reached"),
    Location::caller())bug!(),
470                }
471            } else {
472                let switch_llty = bx.immediate_backend_type(bx.layout_of(switch_ty));
473                let llval = bx.const_uint_big(switch_llty, test_value);
474                let cmp = bx.icmp(IntPredicate::IntEQ, discr_value, llval);
475                bx.cond_br_with_expect(cmp, lltarget, llotherwise, expect);
476            }
477        } else if target_iter.len() == 2
478            && self.mir[targets.otherwise()].is_empty_unreachable()
479            && targets.all_values().contains(&Pu128(0))
480            && targets.all_values().contains(&Pu128(1))
481        {
482            // This is the really common case for `bool`, `Option`, etc.
483            // By using `trunc nuw` we communicate that other values are
484            // impossible without needing `switch` or `assume`s.
485            let true_bb = targets.target_for_value(1);
486            let false_bb = targets.target_for_value(0);
487            let true_ll = helper.llbb_with_cleanup(self, true_bb);
488            let false_ll = helper.llbb_with_cleanup(self, false_bb);
489
490            let expected_cond_value = if self.cx.sess().opts.optimize == OptLevel::No {
491                None
492            } else {
493                match (self.cold_blocks[true_bb], self.cold_blocks[false_bb]) {
494                    // Same coldness, no expectation
495                    (true, true) | (false, false) => None,
496                    // Different coldness, expect the non-cold one
497                    (true, false) => Some(false),
498                    (false, true) => Some(true),
499                }
500            };
501
502            let bool_ty = bx.tcx().types.bool;
503            let cond = if switch_ty == bool_ty {
504                discr_value
505            } else {
506                let bool_llty = bx.immediate_backend_type(bx.layout_of(bool_ty));
507                bx.unchecked_utrunc(discr_value, bool_llty)
508            };
509            bx.cond_br_with_expect(cond, true_ll, false_ll, expected_cond_value);
510        } else if self.cx.sess().opts.optimize == OptLevel::No
511            && target_iter.len() == 2
512            && self.mir[targets.otherwise()].is_empty_unreachable()
513        {
514            // In unoptimized builds, if there are two normal targets and the `otherwise` target is
515            // an unreachable BB, emit `br` instead of `switch`. This leaves behind the unreachable
516            // BB, which will usually (but not always) be dead code.
517            //
518            // Why only in unoptimized builds?
519            // - In unoptimized builds LLVM uses FastISel which does not support switches, so it
520            //   must fall back to the slower SelectionDAG isel. Therefore, using `br` gives
521            //   significant compile time speedups for unoptimized builds.
522            // - In optimized builds the above doesn't hold, and using `br` sometimes results in
523            //   worse generated code because LLVM can no longer tell that the value being switched
524            //   on can only have two values, e.g. 0 and 1.
525            //
526            let (test_value1, target1) = target_iter.next().unwrap();
527            let (_test_value2, target2) = target_iter.next().unwrap();
528            let ll1 = helper.llbb_with_cleanup(self, target1);
529            let ll2 = helper.llbb_with_cleanup(self, target2);
530            let switch_llty = bx.immediate_backend_type(bx.layout_of(switch_ty));
531            let llval = bx.const_uint_big(switch_llty, test_value1);
532            let cmp = bx.icmp(IntPredicate::IntEQ, discr_value, llval);
533            bx.cond_br(cmp, ll1, ll2);
534        } else {
535            let otherwise = targets.otherwise();
536            let otherwise_cold = self.cold_blocks[otherwise];
537            let otherwise_unreachable = self.mir[otherwise].is_empty_unreachable();
538            let cold_count = targets.iter().filter(|(_, target)| self.cold_blocks[*target]).count();
539            let none_cold = cold_count == 0;
540            let all_cold = cold_count == targets.iter().len();
541            if (none_cold && (!otherwise_cold || otherwise_unreachable))
542                || (all_cold && (otherwise_cold || otherwise_unreachable))
543            {
544                // All targets have the same weight,
545                // or `otherwise` is unreachable and it's the only target with a different weight.
546                bx.switch(
547                    discr_value,
548                    helper.llbb_with_cleanup(self, targets.otherwise()),
549                    target_iter
550                        .map(|(value, target)| (value, helper.llbb_with_cleanup(self, target))),
551                );
552            } else {
553                // Targets have different weights
554                bx.switch_with_weights(
555                    discr_value,
556                    helper.llbb_with_cleanup(self, targets.otherwise()),
557                    otherwise_cold,
558                    target_iter.map(|(value, target)| {
559                        (value, helper.llbb_with_cleanup(self, target), self.cold_blocks[target])
560                    }),
561                );
562            }
563        }
564    }
565
566    fn codegen_return_terminator(&mut self, bx: &mut Bx) {
567        // Explicitly end the lifetime of the VaList if this function is c-variadic. We explicitly
568        // start the lifetime when desugaring `...`. Ending the lifetime meaningfully improves
569        // codegen.
570        if self.fn_abi.c_variadic {
571            // The `VaList` "spoofed" argument is just after all the real arguments.
572            let va_list_arg_idx = self.fn_abi.args.len();
573            match self.locals[mir::Local::arg(va_list_arg_idx)] {
574                LocalRef::Place(va_list) => {
575                    // NOTE: we don't actually call LLVM's va_end here. We know it's a no-op for
576                    // all current targets and hence don't bother
577                    // (as permitted by https://llvm.org/docs/LangRef.html#llvm-va-end-intrinsic).
578
579                    // Explicitly end the lifetime of the `va_list`, improves LLVM codegen.
580                    bx.lifetime_end(va_list.val.llval, va_list.layout.size);
581                }
582                _ => ::rustc_span::macros::bug_impl(None,
    format_args!("C-variadic function must have a `VaList` place"),
    Location::caller())bug!("C-variadic function must have a `VaList` place"),
583            }
584        }
585        if self.fn_abi.ret.layout.is_uninhabited() {
586            // Functions with uninhabited return values are marked `noreturn`,
587            // so we should make sure that we never actually do.
588            // We play it safe by using a well-defined `abort`, but we could go for immediate UB
589            // if that turns out to be helpful.
590            bx.abort();
591            // `abort` does not terminate the block, so we still need to generate
592            // an `unreachable` terminator after it.
593            bx.unreachable();
594            return;
595        }
596        let llval = match &self.fn_abi.ret.mode {
597            PassMode::Ignore | PassMode::Indirect { .. } => {
598                bx.ret_void();
599                return;
600            }
601
602            PassMode::Direct(_) | PassMode::Pair(..) => {
603                let op = self.codegen_consume(bx, mir::Place::return_place().as_ref());
604                if let Ref(place_val) = op.val {
605                    bx.load_from_place(bx.backend_type(op.layout), place_val)
606                } else {
607                    op.immediate_or_packed_pair(bx)
608                }
609            }
610
611            PassMode::Cast { cast: cast_ty, pad_i32_count: _ } => {
612                let op = match self.locals[mir::RETURN_PLACE] {
613                    LocalRef::Operand(op) => op,
614                    LocalRef::PendingOperand => ::rustc_span::macros::bug_impl(None, format_args!("use of return before def"),
    Location::caller())bug!("use of return before def"),
615                    LocalRef::Place(cg_place) => OperandRef {
616                        val: Ref(cg_place.val),
617                        layout: cg_place.layout,
618                        move_annotation: None,
619                    },
620                    LocalRef::UnsizedPlace(_) => ::rustc_span::macros::bug_impl(None,
    format_args!("return type must be sized"), Location::caller())bug!("return type must be sized"),
621                };
622                let llslot = match op.val {
623                    Immediate(_) | Pair(..) => {
624                        let scratch = PlaceRef::alloca(bx, self.fn_abi.ret.layout);
625                        op.val.store(bx, scratch);
626                        scratch.val.llval
627                    }
628                    Ref(place_val) => {
629                        {
    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!(
630                            place_val.align, op.layout.align.abi,
631                            "return place is unaligned!"
632                        );
633                        place_val.llval
634                    }
635                    ZeroSized => ::rustc_span::macros::bug_impl(None,
    format_args!("ZST return value shouldn\'t be in PassMode::Cast"),
    Location::caller())bug!("ZST return value shouldn't be in PassMode::Cast"),
636                };
637
638                if self.fn_abi.conv == CanonAbi::Arm(ArmCall::CCmseNonSecureEntry) {
639                    // The return value of an `extern "cmse-nonsecure-entry"` function crosses the
640                    // secure boundary. Clear any padding bytes so information does not leak.
641                    let ret_layout = self.fn_abi.ret.layout;
642                    self.clear_padding_cmse(bx, llslot, ret_layout.size, ret_layout);
643                }
644
645                load_cast(bx, cast_ty, llslot, self.fn_abi.ret.layout.align.abi)
646            }
647        };
648        bx.ret(llval);
649    }
650
651    {}
#[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("/rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_codegen_ssa/src/mir/block.rs"),
                                    ::tracing_core::__macro_support::Option::Some(651u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir::block"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("source_info")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("source_info");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("location")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("location");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("target")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("target");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("unwind")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("unwind");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("mergeable_succ")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("mergeable_succ");
                                                        NAME.as_str()
                                                    }], ::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};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&source_info)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&location)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&target)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&unwind)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&mergeable_succ as
                                                            &dyn ::tracing::field::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_glue(bx.tcx(), ty);
            if let ty::InstanceKind::Shim(ty::ShimKind::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 /rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_codegen_ssa/src/mir/block.rs:700",
                                                "rustc_codegen_ssa::mir::block", ::tracing::Level::DEBUG,
                                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_codegen_ssa/src/mir/block.rs"),
                                                ::tracing_core::__macro_support::Option::Some(700u32),
                                                ::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};
                                        __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("ty = {0:?}",
                                                                            ty) as &dyn ::tracing::field::Value))])
                                    });
                            } else { ; }
                        };
                        {
                            use ::tracing::__macro_support::Callsite as _;
                            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                {
                                    static META: ::tracing::Metadata<'static> =
                                        {
                                            ::tracing_core::metadata::Metadata::new("event /rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_codegen_ssa/src/mir/block.rs:701",
                                                "rustc_codegen_ssa::mir::block", ::tracing::Level::DEBUG,
                                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_codegen_ssa/src/mir/block.rs"),
                                                ::tracing_core::__macro_support::Option::Some(701u32),
                                                ::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};
                                        __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("drop_fn = {0:?}",
                                                                            drop_fn) as &dyn ::tracing::field::Value))])
                                    });
                            } else { ; }
                        };
                        {
                            use ::tracing::__macro_support::Callsite as _;
                            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                {
                                    static META: ::tracing::Metadata<'static> =
                                        {
                                            ::tracing_core::metadata::Metadata::new("event /rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_codegen_ssa/src/mir/block.rs:702",
                                                "rustc_codegen_ssa::mir::block", ::tracing::Level::DEBUG,
                                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_codegen_ssa/src/mir/block.rs"),
                                                ::tracing_core::__macro_support::Option::Some(702u32),
                                                ::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};
                                        __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("args = {0:?}",
                                                                            args) as &dyn ::tracing::field::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.sess().pointer_authentication_functions()),
                            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, ReturnSlot::Direct,
                args, Some((ReturnDest::Nothing, target)), unwind, &[],
                Some(drop_instance), CallKind::Normal,
                !maybe_null && mergeable_succ)
        }
    }
}#[tracing::instrument(level = "trace", skip(self, helper, bx))]
652    fn codegen_drop_terminator(
653        &mut self,
654        helper: TerminatorCodegenHelper<'tcx>,
655        bx: &mut Bx,
656        source_info: &mir::SourceInfo,
657        location: mir::Place<'tcx>,
658        target: mir::BasicBlock,
659        unwind: mir::UnwindAction,
660        mergeable_succ: bool,
661    ) -> MergingSucc {
662        let ty = location.ty(self.mir, bx.tcx()).ty;
663        let ty = self.monomorphize(ty);
664        let drop_fn = Instance::resolve_drop_glue(bx.tcx(), ty);
665
666        if let ty::InstanceKind::Shim(ty::ShimKind::DropGlue(_, None)) = drop_fn.def {
667            // we don't actually need to drop anything.
668            return helper.funclet_br(self, bx, target, mergeable_succ, &[]);
669        }
670
671        let place = self.codegen_place(bx, location.as_ref());
672        let (args1, args2);
673        let mut args = if let Some(llextra) = place.val.llextra {
674            args2 = [place.val.llval, llextra];
675            &args2[..]
676        } else {
677            args1 = [place.val.llval];
678            &args1[..]
679        };
680        let (maybe_null, drop_fn, fn_abi, drop_instance) = match ty.kind() {
681            // FIXME(eddyb) perhaps move some of this logic into
682            // `Instance::resolve_drop_glue`?
683            ty::Dynamic(_, _) => {
684                // IN THIS ARM, WE HAVE:
685                // ty = *mut (dyn Trait)
686                // which is: exists<T> ( *mut T,    Vtable<T: Trait> )
687                //                       args[0]    args[1]
688                //
689                // args = ( Data, Vtable )
690                //                  |
691                //                  v
692                //                /-------\
693                //                | ...   |
694                //                \-------/
695                //
696                let virtual_drop = Instance {
697                    def: ty::InstanceKind::Virtual(drop_fn.def_id(), 0), // idx 0: the drop function
698                    args: drop_fn.args,
699                };
700                debug!("ty = {:?}", ty);
701                debug!("drop_fn = {:?}", drop_fn);
702                debug!("args = {:?}", args);
703                let fn_abi = bx.fn_abi_of_instance(virtual_drop, ty::List::empty());
704                let vtable = args[1];
705                // Truncate vtable off of args list
706                args = &args[..1];
707                (
708                    true,
709                    meth::VirtualIndex::from_index(ty::COMMON_VTABLE_ENTRIES_DROPINPLACE)
710                        .get_optional_fn(bx, vtable, ty, fn_abi),
711                    fn_abi,
712                    virtual_drop,
713                )
714            }
715            _ => (
716                false,
717                bx.get_fn_addr(drop_fn, bx.sess().pointer_authentication_functions()),
718                bx.fn_abi_of_instance(drop_fn, ty::List::empty()),
719                drop_fn,
720            ),
721        };
722
723        // We generate a null check for the drop_fn. This saves a bunch of relocations being
724        // generated for no-op drops.
725        if maybe_null {
726            let is_not_null = bx.append_sibling_block("is_not_null");
727            let llty = bx.fn_ptr_backend_type(fn_abi);
728            let null = bx.const_null(llty);
729            let non_null =
730                bx.icmp(base::bin_op_to_icmp_predicate(mir::BinOp::Ne, false), drop_fn, null);
731            bx.cond_br(non_null, is_not_null, helper.llbb_with_cleanup(self, target));
732            bx.switch_to_block(is_not_null);
733            self.set_debug_loc(bx, *source_info);
734        }
735
736        helper.do_call(
737            self,
738            bx,
739            fn_abi,
740            drop_fn,
741            ReturnSlot::Direct,
742            args,
743            Some((ReturnDest::Nothing, target)),
744            unwind,
745            &[],
746            Some(drop_instance),
747            CallKind::Normal,
748            !maybe_null && mergeable_succ,
749        )
750    }
751
752    fn codegen_assert_terminator(
753        &mut self,
754        helper: TerminatorCodegenHelper<'tcx>,
755        bx: &mut Bx,
756        terminator: &mir::Terminator<'tcx>,
757        cond: &mir::Operand<'tcx>,
758        expected: bool,
759        msg: &mir::AssertMessage<'tcx>,
760        target: mir::BasicBlock,
761        unwind: mir::UnwindAction,
762        mergeable_succ: bool,
763    ) -> MergingSucc {
764        let span = terminator.source_info.span;
765        let cond = self.codegen_operand(bx, cond).immediate();
766        let mut const_cond = bx.const_to_opt_u128(cond, false).map(|c| c == 1);
767
768        // This case can currently arise only from functions marked
769        // with #[rustc_inherit_overflow_checks] and inlined from
770        // another crate (mostly core::num generic/#[inline] fns),
771        // while the current crate doesn't use overflow checks.
772        if !bx.sess().overflow_checks() && msg.is_optional_overflow_check() {
773            const_cond = Some(expected);
774        }
775
776        // Don't codegen the panic block if success if known.
777        if const_cond == Some(expected) {
778            return helper.funclet_br(self, bx, target, mergeable_succ, &[]);
779        }
780
781        // Because we're branching to a panic block (either a `#[cold]` one
782        // or an inlined abort), there's no need to `expect` it.
783
784        // Create the failure block and the conditional branch to it.
785        let lltarget = helper.llbb_with_cleanup(self, target);
786        let panic_block = bx.append_sibling_block("panic");
787        if expected {
788            bx.cond_br(cond, lltarget, panic_block);
789        } else {
790            bx.cond_br(cond, panic_block, lltarget);
791        }
792
793        // After this point, bx is the block for the call to panic.
794        bx.switch_to_block(panic_block);
795        self.set_debug_loc(bx, terminator.source_info);
796
797        // Get the location information.
798        let location = self.get_caller_location(bx, terminator.source_info).immediate();
799
800        // Put together the arguments to the panic entry point.
801        let (lang_item, args) = match msg {
802            AssertKind::BoundsCheck { len, index } => {
803                let len = self.codegen_operand(bx, len).immediate();
804                let index = self.codegen_operand(bx, index).immediate();
805                // It's `fn panic_bounds_check(index: usize, len: usize)`,
806                // and `#[track_caller]` adds an implicit third argument.
807                (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])
808            }
809            AssertKind::MisalignedPointerDereference { required, found } => {
810                let required = self.codegen_operand(bx, required).immediate();
811                let found = self.codegen_operand(bx, found).immediate();
812                // It's `fn panic_misaligned_pointer_dereference(required: usize, found: usize)`,
813                // and `#[track_caller]` adds an implicit third argument.
814                (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])
815            }
816            AssertKind::NullPointerDereference => {
817                // It's `fn panic_null_pointer_dereference()`,
818                // `#[track_caller]` adds an implicit argument.
819                (LangItem::PanicNullPointerDereference, ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [location]))vec![location])
820            }
821            AssertKind::NullReferenceConstructed => {
822                // It's `fn panic_null_reference_constructed()`,
823                // `#[track_caller]` adds an implicit argument.
824                (LangItem::PanicNullReferenceConstructed, ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [location]))vec![location])
825            }
826            AssertKind::InvalidEnumConstruction(source) => {
827                let source = self.codegen_operand(bx, source).immediate();
828                // It's `fn panic_invalid_enum_construction(source: u128)`,
829                // `#[track_caller]` adds an implicit argument.
830                (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])
831            }
832            _ => {
833                // It's `pub fn panic_...()` and `#[track_caller]` adds an implicit argument.
834                (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])
835            }
836        };
837
838        let (fn_abi, llfn, instance) = common::build_langcall(bx, span, lang_item);
839
840        // Codegen the actual panic invoke/call.
841        let merging_succ = helper.do_call(
842            self,
843            bx,
844            fn_abi,
845            llfn,
846            ReturnSlot::Direct,
847            &args,
848            None,
849            unwind,
850            &[],
851            Some(instance),
852            CallKind::Normal,
853            false,
854        );
855        {
    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);
856        MergingSucc::False
857    }
858
859    fn codegen_terminate_terminator(
860        &mut self,
861        helper: TerminatorCodegenHelper<'tcx>,
862        bx: &mut Bx,
863        terminator: &mir::Terminator<'tcx>,
864        reason: UnwindTerminateReason,
865    ) {
866        let span = terminator.source_info.span;
867        self.set_debug_loc(bx, terminator.source_info);
868
869        // Obtain the panic entry point.
870        let (fn_abi, llfn, instance) = common::build_langcall(bx, span, reason.lang_item());
871
872        // Codegen the actual panic invoke/call.
873        let merging_succ = helper.do_call(
874            self,
875            bx,
876            fn_abi,
877            llfn,
878            ReturnSlot::Direct,
879            &[],
880            None,
881            mir::UnwindAction::Unreachable,
882            &[],
883            Some(instance),
884            CallKind::Normal,
885            false,
886        );
887        {
    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);
888    }
889
890    /// Returns `Some` if this is indeed a panic intrinsic and codegen is done.
891    fn codegen_panic_intrinsic(
892        &mut self,
893        helper: &TerminatorCodegenHelper<'tcx>,
894        bx: &mut Bx,
895        intrinsic: ty::IntrinsicDef,
896        instance: Instance<'tcx>,
897        source_info: mir::SourceInfo,
898        target: Option<mir::BasicBlock>,
899        unwind: mir::UnwindAction,
900        mergeable_succ: bool,
901    ) -> Option<MergingSucc> {
902        // Emit a panic or a no-op for `assert_*` intrinsics.
903        // These are intrinsics that compile to panics so that we can get a message
904        // which mentions the offending type, even from a const context.
905        let Some(requirement) = ValidityRequirement::from_intrinsic(intrinsic.name) else {
906            return None;
907        };
908
909        let ty = instance.args.type_at(0);
910
911        let is_valid = bx
912            .tcx()
913            .check_validity_requirement((requirement, bx.typing_env().as_query_input(ty)))
914            .expect("expect to have layout during codegen");
915
916        if is_valid {
917            // a NOP
918            let target = target.unwrap();
919            return Some(helper.funclet_br(self, bx, target, mergeable_succ, &[]));
920        }
921
922        let layout = bx.layout_of(ty);
923
924        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!({
925            with_no_trimmed_paths!({
926                if layout.is_uninhabited() {
927                    // Use this error even for the other intrinsics as it is more precise.
928                    format!("attempted to instantiate uninhabited type `{ty}`")
929                } else if requirement == ValidityRequirement::Zero {
930                    format!("attempted to zero-initialize type `{ty}`, which is invalid")
931                } else {
932                    format!("attempted to leave type `{ty}` uninitialized, which is invalid")
933                }
934            })
935        });
936        let msg = bx.const_str(&msg_str);
937
938        // Obtain the panic entry point.
939        let (fn_abi, llfn, instance) =
940            common::build_langcall(bx, source_info.span, LangItem::PanicNounwind);
941
942        // Codegen the actual panic invoke/call.
943        Some(helper.do_call(
944            self,
945            bx,
946            fn_abi,
947            llfn,
948            ReturnSlot::Direct,
949            &[msg.0, msg.1],
950            target.as_ref().map(|bb| (ReturnDest::Nothing, *bb)),
951            unwind,
952            &[],
953            Some(instance),
954            CallKind::Normal,
955            mergeable_succ,
956        ))
957    }
958
959    fn codegen_call_terminator(
960        &mut self,
961        helper: TerminatorCodegenHelper<'tcx>,
962        bx: &mut Bx,
963        terminator: &mir::Terminator<'tcx>,
964        func: &mir::Operand<'tcx>,
965        args: &[Spanned<mir::Operand<'tcx>>],
966        destination: mir::Place<'tcx>,
967        target: Option<mir::BasicBlock>,
968        unwind: mir::UnwindAction,
969        fn_span: Span,
970        kind: CallKind,
971        mergeable_succ: bool,
972    ) -> MergingSucc {
973        let source_info = mir::SourceInfo { span: fn_span, ..terminator.source_info };
974
975        // Create the callee. This is a fn ptr or zero-sized and hence a kind of scalar.
976        let callee = self.codegen_operand(bx, func);
977
978        let (instance, mut llfn) = match *callee.layout.ty.kind() {
979            ty::FnDef(def_id, generic_args) => {
980                let instance = ty::Instance::expect_resolve(
981                    bx.tcx(),
982                    bx.typing_env(),
983                    def_id,
984                    generic_args.no_bound_vars().unwrap(),
985                    fn_span,
986                );
987
988                match instance.def {
989                    // We don't need AsyncDropGlueCtorShim here because it is not `noop func`,
990                    // it is `func returning noop future`
991                    ty::InstanceKind::Shim(ty::ShimKind::DropGlue(_, None)) => {
992                        // Empty drop glue; a no-op.
993                        let target = target.unwrap();
994                        return helper.funclet_br(self, bx, target, mergeable_succ, &[]);
995                    }
996                    ty::InstanceKind::Intrinsic(def_id) => {
997                        let intrinsic = bx.tcx().intrinsic(def_id).unwrap();
998                        if let Some(merging_succ) = self.codegen_panic_intrinsic(
999                            &helper,
1000                            bx,
1001                            intrinsic,
1002                            instance,
1003                            source_info,
1004                            target,
1005                            unwind,
1006                            mergeable_succ,
1007                        ) {
1008                            return merging_succ;
1009                        }
1010
1011                        let result_layout =
1012                            self.cx.layout_of(self.monomorphized_place_ty(destination.as_ref()));
1013
1014                        let (result_place, store_in_local) =
1015                            if let Some(local) = destination.as_local() {
1016                                match self.locals[local] {
1017                                    LocalRef::Place(dest) => (Some(dest.val), None),
1018                                    LocalRef::UnsizedPlace(_) => ::rustc_span::macros::bug_impl(None,
    format_args!("return type must be sized"), Location::caller())bug!("return type must be sized"),
1019                                    LocalRef::PendingOperand => (None, Some(local)),
1020                                    LocalRef::Operand(_) => {
1021                                        if result_layout.is_zst() {
1022                                            let place = PlaceRef::new_sized(
1023                                                bx.const_undef(bx.type_ptr()),
1024                                                result_layout,
1025                                            );
1026                                            (Some(place.val), None)
1027                                        } else {
1028                                            ::rustc_span::macros::bug_impl(None,
    format_args!("place local already assigned to"), Location::caller());bug!("place local already assigned to");
1029                                        }
1030                                    }
1031                                }
1032                            } else {
1033                                (Some(self.codegen_place(bx, destination.as_ref()).val), None)
1034                            };
1035
1036                        if let Some(place) = result_place
1037                            && place.align < result_layout.align.abi
1038                        {
1039                            // Currently, MIR code generation does not create calls
1040                            // that store directly to fields of packed structs (in
1041                            // fact, the calls it creates write only to temps).
1042                            //
1043                            // If someone changes that, please update this code path
1044                            // to create a temporary.
1045                            ::rustc_span::macros::bug_impl(Some(self.mir.span),
    format_args!("can\'t directly store to unaligned value"),
    Location::caller());span_bug!(self.mir.span, "can't directly store to unaligned value");
1046                        }
1047
1048                        let args: Vec<_> =
1049                            args.iter().map(|arg| self.codegen_operand(bx, &arg.node)).collect();
1050
1051                        let intrinsic_result = self.codegen_intrinsic_call(
1052                            bx,
1053                            instance,
1054                            &args,
1055                            result_layout,
1056                            result_place,
1057                            source_info,
1058                        );
1059
1060                        if let IntrinsicResult::Operand(op_val) = intrinsic_result {
1061                            match (result_place, store_in_local) {
1062                                (None, Some(local)) => {
1063                                    let op = OperandRef {
1064                                        val: op_val,
1065                                        layout: result_layout,
1066                                        move_annotation: None,
1067                                    };
1068                                    self.overwrite_local(local, LocalRef::Operand(op));
1069                                    self.debug_introduce_local(bx, local);
1070                                }
1071                                (Some(place_val), None) => {
1072                                    let dest = PlaceRef { val: place_val, layout: result_layout };
1073                                    op_val.store(bx, dest);
1074                                }
1075                                _ => ::rustc_span::macros::bug_impl(None, format_args!("impossible case reached"),
    Location::caller())bug!(),
1076                            }
1077                        }
1078
1079                        match intrinsic_result {
1080                            IntrinsicResult::Operand(_) | IntrinsicResult::WroteIntoPlace => {
1081                                return if let Some(target) = target {
1082                                    helper.funclet_br(self, bx, target, mergeable_succ, &[])
1083                                } else {
1084                                    bx.unreachable();
1085                                    MergingSucc::False
1086                                };
1087                            }
1088                            IntrinsicResult::Err(_) => {
1089                                // Even though we're definitely going to error, we need it initialize
1090                                // the local or `maybe_codegen_consume_direct` might ICE later
1091                                // when it goes to use the result from this intrinsic.
1092                                if let Some(local) = store_in_local {
1093                                    let op = OperandRef {
1094                                        val: OperandValue::poison(bx, result_layout),
1095                                        layout: result_layout,
1096                                        move_annotation: None,
1097                                    };
1098                                    self.overwrite_local(local, LocalRef::Operand(op));
1099                                }
1100                                // Also we need to terminate the block to avoid an LLVM assertion,
1101                                // even though we're not going to actually use the IR.
1102                                bx.abort();
1103                                return MergingSucc::False;
1104                            }
1105                            IntrinsicResult::Fallback(instance) => {
1106                                if intrinsic.must_be_overridden {
1107                                    ::rustc_span::macros::bug_impl(Some(fn_span),
    format_args!("intrinsic {0} must be overridden by codegen backend, but isn\'t",
        intrinsic.name), Location::caller());span_bug!(
1108                                        fn_span,
1109                                        "intrinsic {} must be overridden by codegen backend, but isn't",
1110                                        intrinsic.name,
1111                                    );
1112                                }
1113                                (Some(instance), None)
1114                            }
1115                        }
1116                    }
1117
1118                    _ if kind == CallKind::Tail
1119                        && instance.def.requires_caller_location(bx.tcx()) =>
1120                    {
1121                        if let Some(hir_id) =
1122                            terminator.source_info.scope.lint_root(&self.mir.source_scopes)
1123                        {
1124                            bx.tcx().emit_node_lint(TAIL_CALL_TRACK_CALLER, hir_id, rustc_errors::DiagDecorator(|d| {
1125                                _ = d.primary_message("tail calling a function marked with `#[track_caller]` has no special effect").span(fn_span)
1126                            }));
1127                        }
1128
1129                        let instance = ty::Instance::resolve_for_fn_ptr(
1130                            bx.tcx(),
1131                            bx.typing_env(),
1132                            def_id,
1133                            generic_args.no_bound_vars().unwrap(),
1134                        )
1135                        .unwrap();
1136
1137                        (
1138                            None,
1139                            Some(bx.get_fn_addr(
1140                                instance,
1141                                bx.sess().pointer_authentication_functions(),
1142                            )),
1143                        )
1144                    }
1145                    _ => (Some(instance), None),
1146                }
1147            }
1148            ty::FnPtr(..) => (None, Some(callee.immediate())),
1149            _ => ::rustc_span::macros::bug_impl(None,
    format_args!("{0} is not callable", callee.layout.ty), Location::caller())bug!("{} is not callable", callee.layout.ty),
1150        };
1151
1152        if let Some(instance) = instance
1153            && let ty::InstanceKind::LlvmIntrinsic(_) = instance.def
1154            && let Some(name) = bx.tcx().codegen_fn_attrs(instance.def_id()).symbol_name
1155            // This is the only LLVM intrinsic we use that unwinds
1156            // FIXME either add unwind support to codegen_llvm_intrinsic_call or replace usage of
1157            // this intrinsic with something else
1158            && name.as_str() != "llvm.wasm.throw"
1159        {
1160            if !!instance.args.has_infer() {
    ::core::panicking::panic("assertion failed: !instance.args.has_infer()")
};assert!(!instance.args.has_infer());
1161            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());
1162
1163            let result_layout =
1164                self.cx.layout_of(self.monomorphized_place_ty(destination.as_ref()));
1165
1166            let return_dest = if result_layout.is_zst() {
1167                ReturnDest::Nothing
1168            } else if let Some(index) = destination.as_local() {
1169                match self.locals[index] {
1170                    LocalRef::Place(dest) => ReturnDest::Store(dest),
1171                    LocalRef::UnsizedPlace(_) => ::rustc_span::macros::bug_impl(None,
    format_args!("return type must be sized"), Location::caller())bug!("return type must be sized"),
1172                    LocalRef::PendingOperand => {
1173                        // Handle temporary places, specifically `Operand` ones, as
1174                        // they don't have `alloca`s.
1175                        ReturnDest::DirectOperand(index)
1176                    }
1177                    LocalRef::Operand(_) => ::rustc_span::macros::bug_impl(None,
    format_args!("place local already assigned to"), Location::caller())bug!("place local already assigned to"),
1178                }
1179            } else {
1180                ReturnDest::Store(self.codegen_place(bx, destination.as_ref()))
1181            };
1182
1183            let args =
1184                args.into_iter().map(|arg| self.codegen_operand(bx, &arg.node)).collect::<Vec<_>>();
1185
1186            self.set_debug_loc(bx, source_info);
1187
1188            let llret =
1189                bx.codegen_llvm_intrinsic_call(instance, &args, self.mir[helper.bb].is_cleanup);
1190
1191            if let Some(target) = target {
1192                self.store_return(
1193                    bx,
1194                    return_dest,
1195                    &ArgAbi { layout: result_layout, mode: PassMode::Direct(ArgAttributes::new()) },
1196                    llret,
1197                );
1198                return helper.funclet_br(self, bx, target, mergeable_succ, &[]);
1199            } else {
1200                bx.unreachable();
1201                return MergingSucc::False;
1202            }
1203        }
1204
1205        // FIXME(eddyb) avoid computing this if possible, when `instance` is
1206        // available - right now `sig` is only needed for getting the `abi`
1207        // and figuring out how many extra args were passed to a C-variadic `fn`.
1208        let sig = callee.layout.ty.fn_sig(bx.tcx());
1209
1210        let extra_args = &args[sig.inputs().skip_binder().len()..];
1211        let extra_args = bx.tcx().mk_type_list_from_iter(extra_args.iter().map(|op_arg| {
1212            let op_ty = op_arg.node.ty(self.mir, bx.tcx());
1213            self.monomorphize(op_ty)
1214        }));
1215
1216        let fn_abi = match instance {
1217            Some(instance) => bx.fn_abi_of_instance(instance, extra_args),
1218            None => bx.fn_abi_of_fn_ptr(sig, extra_args),
1219        };
1220
1221        // The arguments we'll be passing. Plus one to account for outptr, if used.
1222        let arg_count = fn_abi.args.len() + fn_abi.ret.is_indirect() as usize;
1223
1224        let mut llargs = Vec::with_capacity(arg_count);
1225
1226        // We still need to call `make_return_dest` even if there's no `target`, since
1227        // `fn_abi.ret` could be `PassMode::Indirect`, even if it is uninhabited,
1228        // and `make_return_dest` adds the return-place indirect pointer to `llargs`.
1229        let (destination, return_slot) = match kind {
1230            CallKind::Normal => {
1231                let (return_dest, return_slot) =
1232                    self.make_return_dest(bx, destination, &fn_abi.ret);
1233                (target.map(|target| (return_dest, target)), return_slot)
1234            }
1235            CallKind::Tail => {
1236                let return_slot = if fn_abi.ret.is_indirect() {
1237                    match self.make_return_dest(bx, destination, &fn_abi.ret) {
1238                        (ReturnDest::Nothing, return_slot) => return_slot,
1239                        _ => ::rustc_span::macros::bug_impl(None,
    format_args!("tail calls to functions with indirect returns cannot store into a destination"),
    Location::caller())bug!(
1240                            "tail calls to functions with indirect returns cannot store into a destination"
1241                        ),
1242                    }
1243                } else {
1244                    ReturnSlot::Direct
1245                };
1246                (None, return_slot)
1247            }
1248        };
1249
1250        // Split the rust-call tupled arguments off.
1251        // FIXME(splat): un-tuple splatted arguments in codegen, for performance
1252        let (first_args, untuple) = if sig.abi() == ExternAbi::RustCall
1253            && let Some((tup, args)) = args.split_last()
1254        {
1255            (args, Some(tup))
1256        } else {
1257            (args, None)
1258        };
1259
1260        // Special logic for tail calls with `PassMode::Indirect { mode: IndirectMode::Pointer, .. }` arguments.
1261        //
1262        // Normally an indirect argument that is allocated in the caller's stack frame
1263        // would be passed as a pointer into the callee's stack frame.
1264        // For tail calls, that would be unsound, because the caller's
1265        // stack frame is overwritten by the callee's stack frame.
1266        //
1267        // Therefore we store the argument for the callee in the corresponding caller's slot.
1268        // Because guaranteed tail calls demand that the caller's signature matches the callee's,
1269        // the corresponding slot has the correct type.
1270        //
1271        // To handle cases like the one below, the tail call arguments must first be copied to a
1272        // temporary, and only then copied to the caller's argument slots.
1273        //
1274        // ```
1275        // // A struct big enough that it is not passed via registers.
1276        // pub struct Big([u64; 4]);
1277        //
1278        // fn swapper(a: Big, b: Big) -> (Big, Big) {
1279        //     become swapper_helper(b, a);
1280        // }
1281        // ```
1282        let mut tail_call_temporaries = ::alloc::vec::Vec::new()vec![];
1283        if kind == CallKind::Tail {
1284            tail_call_temporaries = ::alloc::vec::from_elem(None, first_args.len())vec![None; first_args.len()];
1285            // Copy the arguments that use `PassMode::Indirect { mode: IndirectMode::Pointer , ..}`
1286            // to temporary stack allocations. See the comment above.
1287            for (i, arg) in first_args.iter().enumerate() {
1288                if !#[allow(non_exhaustive_omitted_patterns)] match fn_abi.args[i].mode {
    PassMode::Indirect { mode: IndirectMode::Pointer, .. } => true,
    _ => false,
}matches!(
1289                    fn_abi.args[i].mode,
1290                    PassMode::Indirect { mode: IndirectMode::Pointer, .. }
1291                ) {
1292                    continue;
1293                }
1294
1295                let op = self.codegen_operand(bx, &arg.node);
1296                let tmp = PlaceRef::alloca(bx, op.layout);
1297                bx.lifetime_start(tmp.val.llval, tmp.layout.size);
1298                op.store_with_annotation(bx, tmp);
1299
1300                tail_call_temporaries[i] = Some(tmp);
1301            }
1302        }
1303
1304        // When generating arguments we sometimes introduce temporary allocations with lifetime
1305        // that extend for the duration of a call. Keep track of those allocations and their sizes
1306        // to generate `lifetime_end` when the call returns.
1307        let mut lifetime_ends_after_call: Vec<(Bx::Value, Size)> = Vec::new();
1308        'make_args: for (i, arg) in first_args.iter().enumerate() {
1309            let mut op = self.codegen_operand(bx, &arg.node);
1310
1311            if let (0, Some(ty::InstanceKind::Virtual(_, idx))) = (i, instance.map(|i| i.def)) {
1312                match op.val {
1313                    Pair(data_ptr, meta) => {
1314                        // In the case of Rc<Self>, we need to explicitly pass a
1315                        // *mut RcInner<Self> with a Scalar (not ScalarPair) ABI. This is a hack
1316                        // that is understood elsewhere in the compiler as a method on
1317                        // `dyn Trait`.
1318                        // To get a `*mut RcInner<Self>`, we just keep unwrapping newtypes until
1319                        // we get a value of a built-in pointer type.
1320                        //
1321                        // This is also relevant for `Pin<&mut Self>`, where we need to peel the
1322                        // `Pin`.
1323                        while !op.layout.ty.is_raw_ptr() && !op.layout.ty.is_ref() {
1324                            let (idx, _) = op.layout.non_1zst_field(bx).expect(
1325                                "not exactly one non-1-ZST field in a `DispatchFromDyn` type",
1326                            );
1327                            op = op.extract_field(self, bx, idx.as_usize());
1328                        }
1329
1330                        // Now that we have `*dyn Trait` or `&dyn Trait`, split it up into its
1331                        // data pointer and vtable. Look up the method in the vtable, and pass
1332                        // the data pointer as the first argument.
1333                        llfn = Some(meth::VirtualIndex::from_index(idx).get_fn(
1334                            bx,
1335                            meta,
1336                            op.layout.ty,
1337                            fn_abi,
1338                        ));
1339                        llargs.push(data_ptr);
1340                        continue 'make_args;
1341                    }
1342                    Ref(PlaceValue { llval: data_ptr, llextra: Some(meta), .. }) => {
1343                        // by-value dynamic dispatch
1344                        llfn = Some(meth::VirtualIndex::from_index(idx).get_fn(
1345                            bx,
1346                            meta,
1347                            op.layout.ty,
1348                            fn_abi,
1349                        ));
1350                        llargs.push(data_ptr);
1351                        continue;
1352                    }
1353                    _ => {
1354                        ::rustc_span::macros::bug_impl(Some(fn_span),
    format_args!("can\'t codegen a virtual call on {0:#?}", op),
    Location::caller());span_bug!(fn_span, "can't codegen a virtual call on {:#?}", op);
1355                    }
1356                }
1357            }
1358
1359            let by_move = if let PassMode::Indirect { mode: IndirectMode::Pointer, .. } =
1360                fn_abi.args[i].mode
1361                && kind == CallKind::Tail
1362            {
1363                // Special logic for tail calls with `PassMode::Indirect { mode: IndirectMode::Pointer, .. }` arguments.
1364                //
1365                // Normally an indirect argument that is allocated in the caller's stack frame
1366                // would be passed as a pointer into the callee's stack frame.
1367                // For tail calls, that would be unsound, because the caller's
1368                // stack frame is overwritten by the callee's stack frame.
1369                //
1370                // To handle the case, we introduce `tail_call_temporaries` to copy arguments into
1371                // temporaries, then copy back to the caller's argument slots.
1372                // Finally, we pass the caller's argument slots as arguments.
1373                //
1374                // To do that, the argument must be MUST-by-move value.
1375                let Some(tmp) = tail_call_temporaries[i].take() else {
1376                    ::rustc_span::macros::bug_impl(Some(fn_span),
    format_args!("missing temporary for indirect tail call argument #{0}", i),
    Location::caller())span_bug!(fn_span, "missing temporary for indirect tail call argument #{i}")
1377                };
1378
1379                let local = self.mir.args_iter().nth(i).unwrap();
1380
1381                match &self.locals[local] {
1382                    LocalRef::Place(arg) => {
1383                        bx.typed_place_copy(arg.val, tmp.val, fn_abi.args[i].layout);
1384                        op.val = Ref(arg.val);
1385                    }
1386                    LocalRef::Operand(arg) => {
1387                        let Ref(place_value) = arg.val else {
1388                            ::rustc_span::macros::bug_impl(None,
    format_args!("only `Ref` should use `PassMode::Indirect`, but got {0:?}",
        arg.val), Location::caller());bug!(
1389                                "only `Ref` should use `PassMode::Indirect`, but got {:?}",
1390                                arg.val
1391                            );
1392                        };
1393                        bx.typed_place_copy(place_value, tmp.val, fn_abi.args[i].layout);
1394                        op.val = arg.val;
1395                    }
1396                    LocalRef::UnsizedPlace(_) => {
1397                        ::rustc_span::macros::bug_impl(Some(fn_span),
    format_args!("unsized types are not supported"), Location::caller())span_bug!(fn_span, "unsized types are not supported")
1398                    }
1399                    LocalRef::PendingOperand => {
1400                        ::rustc_span::macros::bug_impl(Some(fn_span),
    format_args!("argument local should not be pending"), Location::caller())span_bug!(fn_span, "argument local should not be pending")
1401                    }
1402                };
1403
1404                bx.lifetime_end(tmp.val.llval, tmp.layout.size);
1405                true
1406            } else {
1407                #[allow(non_exhaustive_omitted_patterns)] match arg.node {
    mir::Operand::Move(_) => true,
    _ => false,
}matches!(arg.node, mir::Operand::Move(_))
1408            };
1409
1410            self.codegen_argument(
1411                bx,
1412                fn_abi.conv,
1413                op,
1414                by_move,
1415                &mut llargs,
1416                &fn_abi.args[i],
1417                &mut lifetime_ends_after_call,
1418            );
1419        }
1420        let num_untupled = untuple.map(|tup| {
1421            self.codegen_arguments_untupled(
1422                bx,
1423                fn_abi.conv,
1424                &tup.node,
1425                &mut llargs,
1426                &fn_abi.args[first_args.len()..],
1427                &mut lifetime_ends_after_call,
1428            )
1429        });
1430
1431        let needs_location =
1432            instance.is_some_and(|i| i.def.requires_caller_location(self.cx.tcx()));
1433        if needs_location {
1434            let mir_args = if let Some(num_untupled) = num_untupled {
1435                first_args.len() + num_untupled
1436            } else {
1437                args.len()
1438            };
1439            {
    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!(
1440                fn_abi.args.len(),
1441                mir_args + 1,
1442                "#[track_caller] fn's must have 1 more argument in their ABI than in their MIR: {instance:?} {fn_span:?} {fn_abi:?}",
1443            );
1444            let location = self.get_caller_location(bx, source_info);
1445            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_codegen_ssa/src/mir/block.rs:1445",
                        "rustc_codegen_ssa::mir::block", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_codegen_ssa/src/mir/block.rs"),
                        ::tracing_core::__macro_support::Option::Some(1445u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("codegen_call_terminator({0:?}): location={1:?} (fn_span {2:?})",
                                                    terminator, location, fn_span) as
                                            &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(
1446                "codegen_call_terminator({:?}): location={:?} (fn_span {:?})",
1447                terminator, location, fn_span
1448            );
1449
1450            let last_arg = fn_abi.args.last().unwrap();
1451            self.codegen_argument(
1452                bx,
1453                fn_abi.conv,
1454                location,
1455                /* by_move */ false,
1456                &mut llargs,
1457                last_arg,
1458                &mut lifetime_ends_after_call,
1459            );
1460        }
1461
1462        let fn_ptr = match (instance, llfn) {
1463            (Some(instance), None) => {
1464                bx.get_fn_addr(instance, bx.sess().pointer_authentication_functions())
1465            }
1466            (_, Some(llfn)) => llfn,
1467            _ => ::rustc_span::macros::bug_impl(Some(fn_span),
    format_args!("no instance or llfn for call"), Location::caller())span_bug!(fn_span, "no instance or llfn for call"),
1468        };
1469        self.set_debug_loc(bx, source_info);
1470        helper.do_call(
1471            self,
1472            bx,
1473            fn_abi,
1474            fn_ptr,
1475            return_slot,
1476            &llargs,
1477            destination,
1478            unwind,
1479            &lifetime_ends_after_call,
1480            instance,
1481            kind,
1482            mergeable_succ,
1483        )
1484    }
1485
1486    fn codegen_asm_terminator(
1487        &mut self,
1488        helper: TerminatorCodegenHelper<'tcx>,
1489        bx: &mut Bx,
1490        asm_macro: InlineAsmMacro,
1491        terminator: &mir::Terminator<'tcx>,
1492        template: &[ast::InlineAsmTemplatePiece],
1493        operands: &[mir::InlineAsmOperand<'tcx>],
1494        options: ast::InlineAsmOptions,
1495        line_spans: &[Span],
1496        targets: &[mir::BasicBlock],
1497        unwind: mir::UnwindAction,
1498        instance: Instance<'_>,
1499        mergeable_succ: bool,
1500    ) -> MergingSucc {
1501        let span = terminator.source_info.span;
1502
1503        let operands: Vec<_> = operands
1504            .iter()
1505            .map(|op| match *op {
1506                mir::InlineAsmOperand::In { reg, ref value } => {
1507                    let value = self.codegen_operand(bx, value);
1508                    InlineAsmOperandRef::In { reg, value }
1509                }
1510                mir::InlineAsmOperand::Out { reg, late, ref place } => {
1511                    let place = place.map(|place| self.codegen_place(bx, place.as_ref()));
1512                    InlineAsmOperandRef::Out { reg, late, place }
1513                }
1514                mir::InlineAsmOperand::InOut { reg, late, ref in_value, ref out_place } => {
1515                    let in_value = self.codegen_operand(bx, in_value);
1516                    let out_place =
1517                        out_place.map(|out_place| self.codegen_place(bx, out_place.as_ref()));
1518                    InlineAsmOperandRef::InOut { reg, late, in_value, out_place }
1519                }
1520                mir::InlineAsmOperand::Const { ref value } => {
1521                    let const_value = self.eval_mir_constant(value);
1522                    let mir::ConstValue::Scalar(scalar) = const_value else {
1523                        ::rustc_span::macros::bug_impl(Some(span),
    format_args!("expected Scalar for promoted asm const, but got {0:#?}",
        const_value), Location::caller())span_bug!(
1524                            span,
1525                            "expected Scalar for promoted asm const, but got {:#?}",
1526                            const_value
1527                        )
1528                    };
1529                    InlineAsmOperandRef::Const {
1530                        value: common::asm_const_ptr_clean(bx.tcx(), scalar),
1531                        ty: value.ty(),
1532                    }
1533                }
1534                mir::InlineAsmOperand::SymFn { ref value } => {
1535                    let const_ = self.monomorphize(value.const_);
1536                    if let ty::FnDef(def_id, args) = *const_.ty().kind() {
1537                        let instance = ty::Instance::resolve_for_fn_ptr(
1538                            bx.tcx(),
1539                            bx.typing_env(),
1540                            def_id,
1541                            args.no_bound_vars().unwrap(),
1542                        )
1543                        .unwrap();
1544
1545                        InlineAsmOperandRef::Const {
1546                            value: Scalar::from_pointer(
1547                                bx.tcx().reserve_and_set_fn_alloc(instance, CTFE_ALLOC_SALT).into(),
1548                                bx,
1549                            ),
1550                            ty: Ty::new_fn_ptr(bx.tcx(), const_.ty().fn_sig(bx.tcx())),
1551                        }
1552                    } else {
1553                        ::rustc_span::macros::bug_impl(Some(span),
    format_args!("invalid type for asm sym (fn)"), Location::caller());span_bug!(span, "invalid type for asm sym (fn)");
1554                    }
1555                }
1556                mir::InlineAsmOperand::SymStatic { def_id } => {
1557                    if bx.tcx().is_thread_local_static(def_id) {
1558                        InlineAsmOperandRef::SymThreadLocalStatic { def_id }
1559                    } else {
1560                        InlineAsmOperandRef::Const {
1561                            value: Scalar::from_pointer(
1562                                bx.tcx().reserve_and_set_static_alloc(def_id).into(),
1563                                bx,
1564                            ),
1565                            ty: bx.tcx().static_ptr_ty(def_id, bx.typing_env()),
1566                        }
1567                    }
1568                }
1569                mir::InlineAsmOperand::Label { target_index } => {
1570                    InlineAsmOperandRef::Label { label: self.llbb(targets[target_index]) }
1571                }
1572            })
1573            .collect();
1574
1575        helper.do_inlineasm(
1576            self,
1577            bx,
1578            template,
1579            &operands,
1580            options,
1581            line_spans,
1582            if asm_macro.diverges(options) { None } else { targets.get(0).copied() },
1583            unwind,
1584            instance,
1585            mergeable_succ,
1586        )
1587    }
1588
1589    pub(crate) fn codegen_block(&mut self, mut bb: mir::BasicBlock) {
1590        let llbb = match self.try_llbb(bb) {
1591            Some(llbb) => llbb,
1592            None => return,
1593        };
1594        let bx = &mut Bx::build(self.cx, llbb);
1595        let mir = self.mir;
1596
1597        // MIR basic blocks stop at any function call. This may not be the case
1598        // for the backend's basic blocks, in which case we might be able to
1599        // combine multiple MIR basic blocks into a single backend basic block.
1600        loop {
1601            let data = &mir[bb];
1602
1603            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_codegen_ssa/src/mir/block.rs:1603",
                        "rustc_codegen_ssa::mir::block", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_codegen_ssa/src/mir/block.rs"),
                        ::tracing_core::__macro_support::Option::Some(1603u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("codegen_block({0:?}={1:?})",
                                                    bb, data) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("codegen_block({:?}={:?})", bb, data);
1604
1605            for statement in &data.statements {
1606                self.codegen_statement(bx, statement);
1607            }
1608            self.codegen_stmt_debuginfos(bx, &data.after_last_stmt_debuginfos);
1609
1610            let merging_succ = self.codegen_terminator(bx, bb, data.terminator());
1611            if let MergingSucc::False = merging_succ {
1612                break;
1613            }
1614
1615            // We are merging the successor into the produced backend basic
1616            // block. Record that the successor should be skipped when it is
1617            // reached.
1618            //
1619            // Note: we must not have already generated code for the successor.
1620            // This is implicitly ensured by the reverse postorder traversal,
1621            // and the assertion explicitly guarantees that.
1622            let mut successors = data.terminator().successors();
1623            let succ = successors.next().unwrap();
1624            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));
1625            self.cached_llbbs[succ] = CachedLlbb::Skip;
1626            bb = succ;
1627        }
1628    }
1629
1630    pub(crate) fn codegen_block_as_unreachable(&mut self, bb: mir::BasicBlock) {
1631        let llbb = match self.try_llbb(bb) {
1632            Some(llbb) => llbb,
1633            None => return,
1634        };
1635        let bx = &mut Bx::build(self.cx, llbb);
1636        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_codegen_ssa/src/mir/block.rs:1636",
                        "rustc_codegen_ssa::mir::block", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_codegen_ssa/src/mir/block.rs"),
                        ::tracing_core::__macro_support::Option::Some(1636u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("codegen_block_as_unreachable({0:?})",
                                                    bb) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("codegen_block_as_unreachable({:?})", bb);
1637        bx.unreachable();
1638    }
1639
1640    fn codegen_terminator(
1641        &mut self,
1642        bx: &mut Bx,
1643        bb: mir::BasicBlock,
1644        terminator: &'tcx mir::Terminator<'tcx>,
1645    ) -> MergingSucc {
1646        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_codegen_ssa/src/mir/block.rs:1646",
                        "rustc_codegen_ssa::mir::block", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_codegen_ssa/src/mir/block.rs"),
                        ::tracing_core::__macro_support::Option::Some(1646u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("codegen_terminator: {0:?}",
                                                    terminator) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("codegen_terminator: {:?}", terminator);
1647
1648        let helper = TerminatorCodegenHelper { bb, terminator };
1649
1650        let mergeable_succ = || {
1651            // Note: any call to `switch_to_block` will invalidate a `true` value
1652            // of `mergeable_succ`.
1653            let mut successors = terminator.successors();
1654            if let Some(succ) = successors.next()
1655                && successors.next().is_none()
1656                && let &[succ_pred] = self.mir.basic_blocks.predecessors()[succ].as_slice()
1657            {
1658                // bb has a single successor, and bb is its only predecessor. This
1659                // makes it a candidate for merging.
1660                {
    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);
1661                true
1662            } else {
1663                false
1664            }
1665        };
1666
1667        self.set_debug_loc(bx, terminator.source_info);
1668        match terminator.kind {
1669            mir::TerminatorKind::UnwindResume => {
1670                self.codegen_resume_terminator(helper, bx);
1671                MergingSucc::False
1672            }
1673
1674            mir::TerminatorKind::UnwindTerminate(reason) => {
1675                self.codegen_terminate_terminator(helper, bx, terminator, reason);
1676                MergingSucc::False
1677            }
1678
1679            mir::TerminatorKind::Goto { target } => {
1680                helper.funclet_br(self, bx, target, mergeable_succ(), &terminator.attributes)
1681            }
1682
1683            mir::TerminatorKind::SwitchInt { ref discr, ref targets } => {
1684                self.codegen_switchint_terminator(helper, bx, discr, targets);
1685                MergingSucc::False
1686            }
1687
1688            mir::TerminatorKind::Return => {
1689                self.codegen_return_terminator(bx);
1690                MergingSucc::False
1691            }
1692
1693            mir::TerminatorKind::Unreachable => {
1694                bx.unreachable();
1695                MergingSucc::False
1696            }
1697
1698            mir::TerminatorKind::Drop { place, target, unwind, replace: _, drop } => {
1699                if !drop.is_none() {
    {
        ::core::panicking::panic_fmt(format_args!("Async Drop must be expanded or reset to sync before codegen"));
    }
};assert!(
1700                    drop.is_none(),
1701                    "Async Drop must be expanded or reset to sync before codegen"
1702                );
1703                self.codegen_drop_terminator(
1704                    helper,
1705                    bx,
1706                    &terminator.source_info,
1707                    place,
1708                    target,
1709                    unwind,
1710                    mergeable_succ(),
1711                )
1712            }
1713
1714            mir::TerminatorKind::Assert { ref cond, expected, ref msg, target, unwind } => self
1715                .codegen_assert_terminator(
1716                    helper,
1717                    bx,
1718                    terminator,
1719                    cond,
1720                    expected,
1721                    msg,
1722                    target,
1723                    unwind,
1724                    mergeable_succ(),
1725                ),
1726
1727            mir::TerminatorKind::Call {
1728                ref func,
1729                ref args,
1730                destination,
1731                target,
1732                unwind,
1733                call_source: _,
1734                fn_span,
1735            } => self.codegen_call_terminator(
1736                helper,
1737                bx,
1738                terminator,
1739                func,
1740                args,
1741                destination,
1742                target,
1743                unwind,
1744                fn_span,
1745                CallKind::Normal,
1746                mergeable_succ(),
1747            ),
1748            mir::TerminatorKind::TailCall { ref func, ref args, fn_span } => self
1749                .codegen_call_terminator(
1750                    helper,
1751                    bx,
1752                    terminator,
1753                    func,
1754                    args,
1755                    mir::Place::from(mir::RETURN_PLACE),
1756                    None,
1757                    mir::UnwindAction::Unreachable,
1758                    fn_span,
1759                    CallKind::Tail,
1760                    mergeable_succ(),
1761                ),
1762            mir::TerminatorKind::CoroutineDrop | mir::TerminatorKind::Yield { .. } => {
1763                ::rustc_span::macros::bug_impl(None, format_args!("coroutine ops in codegen"),
    Location::caller())bug!("coroutine ops in codegen")
1764            }
1765            mir::TerminatorKind::FalseEdge { .. } | mir::TerminatorKind::FalseUnwind { .. } => {
1766                ::rustc_span::macros::bug_impl(None,
    format_args!("borrowck false edges in codegen"), Location::caller())bug!("borrowck false edges in codegen")
1767            }
1768
1769            mir::TerminatorKind::InlineAsm {
1770                asm_macro,
1771                template,
1772                ref operands,
1773                options,
1774                line_spans,
1775                ref targets,
1776                unwind,
1777            } => self.codegen_asm_terminator(
1778                helper,
1779                bx,
1780                asm_macro,
1781                terminator,
1782                template,
1783                operands,
1784                options,
1785                line_spans,
1786                targets,
1787                unwind,
1788                self.instance,
1789                mergeable_succ(),
1790            ),
1791        }
1792    }
1793
1794    /// When using CMSE, values that cross the secure boundary from secure to non-secure mode can
1795    /// contain stale secure data in their padding bytes. This function clears that data. This is
1796    /// required when a value is:
1797    ///
1798    /// - passed to an `extern "cmse-nonsecure-call"` function
1799    /// - returned from an `extern "cmse-nonsecure-entry"` function
1800    ///
1801    /// This function clears both:
1802    ///
1803    /// - variant-independent padding, bytes that are padding for all valid values of the type
1804    /// - variant-dependent padding, bytes that are padding for some but not all values of the type
1805    ///
1806    /// Clearing variant-dependent padding requires looking at the data at runtime to determine what
1807    /// bytes to clear.
1808    fn clear_padding_cmse(
1809        &mut self,
1810        bx: &mut Bx,
1811        base_ptr: Bx::Value,
1812        limit: Size,
1813        layout: TyAndLayout<'tcx>,
1814    ) {
1815        // First clear variant-independent padding, a series of memsets.
1816        let variant_independent = layout.variant_independent_padding_ranges(self.cx);
1817        self.zero_byte_ranges(bx, base_ptr, Size::ZERO, limit, &variant_independent);
1818
1819        // Then clear the extra padding of the active variant of any (nested) enum.
1820        self.clear_variant_dependent_padding(bx, base_ptr, Size::ZERO, limit, layout);
1821    }
1822
1823    fn clear_variant_dependent_padding(
1824        &mut self,
1825        bx: &mut Bx,
1826        base_ptr: Bx::Value,
1827        base_offset: Size,
1828        limit: Size,
1829        layout: TyAndLayout<'tcx>,
1830    ) {
1831        let cx = self.cx;
1832
1833        if !layout.has_variant_dependent_padding(cx) {
1834            return;
1835        }
1836
1837        // Recurse into aggregate fields/elements to reach any nested enums.
1838        match layout.fields {
1839            FieldsShape::Array { stride, count } => {
1840                let elem = layout.field(cx, 0);
1841                if elem.has_variant_dependent_padding(cx) {
1842                    for idx in 0..count {
1843                        let off = base_offset + idx * stride;
1844                        self.clear_variant_dependent_padding(bx, base_ptr, off, limit, elem);
1845                    }
1846                }
1847            }
1848            FieldsShape::Arbitrary { .. } => {
1849                for i in 0..layout.fields.count() {
1850                    let field = layout.field(cx, i);
1851                    if field.has_variant_dependent_padding(cx) {
1852                        let off = base_offset + layout.fields.offset(i);
1853                        self.clear_variant_dependent_padding(bx, base_ptr, off, limit, field);
1854                    }
1855                }
1856            }
1857            FieldsShape::Primitive | FieldsShape::Union(_) => { /* nothing to visit */ }
1858        }
1859
1860        // If this is not a multi-variant enum, we're done.
1861        let Variants::Multiple { ref variants, .. } = layout.variants else {
1862            return;
1863        };
1864
1865        // Collect variants that will need padding cleared.
1866        let mut work = Vec::with_capacity(variants.len());
1867        for i in 0..variants.len() {
1868            let idx = VariantIdx::from_usize(i);
1869            let variant = layout.for_variant(cx, idx);
1870
1871            // Don't consider uninhabited variants.
1872            if variant.is_uninhabited() {
1873                continue;
1874            }
1875
1876            let variant_dependent = layout.variant_dependent_padding_ranges(cx, idx);
1877            let has_nested_variant_dependent = (0..variant.fields.count())
1878                .any(|i| variant.field(cx, i).has_variant_dependent_padding(cx));
1879
1880            if !variant_dependent.is_empty() || has_nested_variant_dependent {
1881                work.push((idx, variant, variant_dependent));
1882            }
1883        }
1884
1885        if work.is_empty() {
1886            return;
1887        }
1888
1889        // Build the switch and clear the appropriate padding for each variant.
1890        let root_block = bx.llbb();
1891        let join_block = bx.append_sibling_block("cmse_pad_join");
1892        let mut cases = Vec::with_capacity(work.len());
1893
1894        for (idx, variant, variant_dependent) in work.into_iter() {
1895            let Some(discr) = layout.ty.discriminant_for_variant(bx.tcx(), idx) else {
1896                ::rustc_span::macros::bug_impl(None,
    format_args!("multi-variant layout on a type without discriminants"),
    Location::caller());bug!("multi-variant layout on a type without discriminants");
1897            };
1898
1899            let variant_block = bx.append_sibling_block("cmse_pad_variant");
1900            bx.switch_to_block(variant_block);
1901
1902            // Clear the padding of this variant.
1903            self.zero_byte_ranges(bx, base_ptr, base_offset, limit, &variant_dependent);
1904
1905            // Recurse into the fields.
1906            for i in 0..variant.fields.count() {
1907                let field = variant.field(cx, i);
1908                let off = base_offset + variant.fields.offset(i);
1909                self.clear_variant_dependent_padding(bx, base_ptr, off, limit, field);
1910            }
1911
1912            bx.br(join_block);
1913            cases.push((discr.val, variant_block));
1914        }
1915
1916        // Construct the dispatch.
1917        bx.switch_to_block(root_block);
1918
1919        let discr_ty = layout.ty.discriminant_ty(bx.tcx());
1920        let enum_ptr = bx.inbounds_ptradd(base_ptr, bx.const_usize(base_offset.bytes()));
1921        let operand = OperandRef {
1922            val: OperandValue::Ref(PlaceValue::new_sized(enum_ptr, layout.align.abi)),
1923            layout,
1924            move_annotation: None,
1925        };
1926        let discr = operand.codegen_get_discr(self, bx, discr_ty);
1927
1928        // Default to the join block (for variants without variant-dependent padding).
1929        bx.switch(discr, join_block, cases.into_iter());
1930
1931        bx.switch_to_block(join_block);
1932    }
1933
1934    fn zero_byte_ranges(
1935        &mut self,
1936        bx: &mut Bx,
1937        ptr: Bx::Value,
1938        offset: Size,
1939        limit: Size,
1940        ranges: &[Range<Size>],
1941    ) {
1942        let zero = bx.const_u8(0);
1943
1944        for range in ranges {
1945            let start = range.start + offset;
1946            let end = range.end + offset;
1947
1948            let end = cmp::min(end, limit);
1949            if range.start >= end {
1950                continue;
1951            }
1952            let offset = bx.const_usize(start.bytes());
1953            let len = bx.const_usize((end - start).bytes());
1954            let ptr = bx.inbounds_ptradd(ptr, offset);
1955            bx.memset(ptr, zero, len, Align::ONE, MemFlags::empty());
1956        }
1957    }
1958
1959    fn codegen_argument(
1960        &mut self,
1961        bx: &mut Bx,
1962        conv: CanonAbi,
1963        op: OperandRef<'tcx, Bx::Value>,
1964        by_move: bool,
1965        llargs: &mut Vec<Bx::Value>,
1966        arg: &ArgAbi<'tcx, Ty<'tcx>>,
1967        lifetime_ends_after_call: &mut Vec<(Bx::Value, Size)>,
1968    ) {
1969        match arg.mode {
1970            PassMode::Ignore => return,
1971            PassMode::Cast { pad_i32_count, .. } => {
1972                // Fill padding with undef value, where applicable.
1973                let undef = bx.const_undef(bx.reg_backend_type(&Reg::i32()));
1974                llargs.extend(std::iter::repeat_n(undef, usize::from(pad_i32_count)));
1975            }
1976            PassMode::Pair(..) => match op.val {
1977                Pair(a, b) => {
1978                    llargs.push(a);
1979                    llargs.push(b);
1980                    return;
1981                }
1982                _ => ::rustc_span::macros::bug_impl(None,
    format_args!("codegen_argument: {0:?} invalid for pair argument", op),
    Location::caller())bug!("codegen_argument: {:?} invalid for pair argument", op),
1983            },
1984            PassMode::Indirect { attrs: _, meta_attrs: Some(_), address_space: _, mode: _ } => {
1985                match op.val {
1986                    Ref(PlaceValue { llval: a, llextra: Some(b), .. }) => {
1987                        llargs.push(a);
1988                        llargs.push(b);
1989                        return;
1990                    }
1991                    _ => ::rustc_span::macros::bug_impl(None,
    format_args!("codegen_argument: {0:?} invalid for unsized indirect argument",
        op), Location::caller())bug!("codegen_argument: {:?} invalid for unsized indirect argument", op),
1992                }
1993            }
1994            _ => {}
1995        }
1996
1997        // Force by-ref if we have to load through a cast pointer.
1998        let (mut llval, align, by_ref) = match op.val {
1999            Immediate(_) | Pair(..) => match arg.mode {
2000                PassMode::Indirect { attrs, .. } => {
2001                    // Indirect argument may have higher alignment requirements than the type's
2002                    // alignment. This can happen, e.g. when passing types with <4 byte alignment
2003                    // on the stack on x86.
2004                    let required_align = match attrs.pointee_align {
2005                        Some(pointee_align) => cmp::max(pointee_align, arg.layout.align.abi),
2006                        None => arg.layout.align.abi,
2007                    };
2008                    let scratch = PlaceValue::alloca(bx, arg.layout.size, required_align);
2009                    bx.lifetime_start(scratch.llval, arg.layout.size);
2010                    op.store_with_annotation(bx, scratch.with_type(arg.layout));
2011                    lifetime_ends_after_call.push((scratch.llval, arg.layout.size));
2012                    (scratch.llval, scratch.align, true)
2013                }
2014                PassMode::Cast { .. } => {
2015                    let scratch = PlaceRef::alloca(bx, arg.layout);
2016                    op.store_with_annotation(bx, scratch);
2017                    (scratch.val.llval, scratch.val.align, true)
2018                }
2019                PassMode::Direct(_) => (op.immediate(), arg.layout.align.abi, false),
2020                PassMode::Ignore | PassMode::Pair(..) => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("handled above")));
}unreachable!("handled above"),
2021            },
2022            Ref(op_place_val) => match arg.mode {
2023                PassMode::Indirect { attrs, mode, .. } => {
2024                    if mode == IndirectMode::AmdgpuKernelArg {
2025                        ::rustc_span::macros::bug_impl(None,
    format_args!("{0:?} passed as amdgpu kernel argument with abi {1:?}", op,
        arg), Location::caller());bug!("{op:?} passed as amdgpu kernel argument with abi {arg:?}");
2026                    }
2027                    // For `foo(packed.large_field)`, and types with <4 byte alignment on x86,
2028                    // alignment requirements may be higher than the type's alignment, so copy
2029                    // to a higher-aligned alloca.
2030                    let required_align = match attrs.pointee_align {
2031                        Some(pointee_align) => cmp::max(pointee_align, arg.layout.align.abi),
2032                        None => arg.layout.align.abi,
2033                    };
2034                    // Copy to an alloca when the argument is neither by-val nor by-move.
2035                    if op_place_val.align < required_align
2036                        || (mode == IndirectMode::Pointer && !by_move)
2037                    {
2038                        let scratch = PlaceValue::alloca(bx, arg.layout.size, required_align);
2039                        bx.lifetime_start(scratch.llval, arg.layout.size);
2040                        op.store_with_annotation(bx, scratch.with_type(arg.layout));
2041                        lifetime_ends_after_call.push((scratch.llval, arg.layout.size));
2042                        (scratch.llval, scratch.align, true)
2043                    } else {
2044                        (op_place_val.llval, op_place_val.align, true)
2045                    }
2046                }
2047                _ => (op_place_val.llval, op_place_val.align, true),
2048            },
2049            ZeroSized => match arg.mode {
2050                PassMode::Indirect { mode, .. } => {
2051                    if mode == IndirectMode::AmdgpuKernelArg {
2052                        ::rustc_span::macros::bug_impl(None,
    format_args!("{0:?} passed as amdgpu kernel argument with abi {1:?}", op,
        arg), Location::caller());bug!("{op:?} passed as amdgpu kernel argument with abi {arg:?}");
2053                    }
2054                    if mode == IndirectMode::OnStack {
2055                        // It doesn't seem like any target can have `byval` ZSTs, so this assert
2056                        // is here to replace a would-be untested codepath.
2057                        ::rustc_span::macros::bug_impl(None,
    format_args!("ZST {0:?} passed on stack with abi {1:?}", op, arg),
    Location::caller());bug!("ZST {op:?} passed on stack with abi {arg:?}");
2058                    }
2059                    // Though `extern "Rust"` doesn't pass ZSTs, some ABIs pass
2060                    // a pointer for `repr(C)` structs even when empty, so get
2061                    // one from an `alloca` (which can be left uninitialized).
2062                    let scratch = PlaceRef::alloca(bx, arg.layout);
2063                    (scratch.val.llval, scratch.val.align, true)
2064                }
2065                _ => ::rustc_span::macros::bug_impl(None,
    format_args!("ZST {0:?} wasn\'t ignored, but was passed with abi {1:?}",
        op, arg), Location::caller())bug!("ZST {op:?} wasn't ignored, but was passed with abi {arg:?}"),
2066            },
2067        };
2068
2069        if by_ref && !arg.is_indirect() {
2070            // Have to load the argument, maybe while casting it.
2071            if let PassMode::Cast { cast, pad_i32_count: _ } = &arg.mode {
2072                // The ABI mandates that the value is passed as a different struct representation.
2073                // Spill and reload it from the stack to convert from the Rust representation to
2074                // the ABI representation.
2075                let scratch_size = cast.size(bx);
2076                let scratch_align = cast.align(bx);
2077                // Note that the ABI type may be either larger or smaller than the Rust type,
2078                // due to the presence or absence of trailing padding. For example:
2079                // - On some ABIs, the Rust layout { f64, f32, <f32 padding> } may omit padding
2080                //   when passed by value, making it smaller.
2081                // - On some ABIs, the Rust layout { u16, u16, u16 } may be padded up to 8 bytes
2082                //   when passed by value, making it larger.
2083                let copy_bytes = cmp::min(cast.unaligned_size(bx).bytes(), arg.layout.size.bytes());
2084                // Allocate some scratch space...
2085                let llscratch = bx.alloca(scratch_size, scratch_align);
2086                bx.lifetime_start(llscratch, scratch_size);
2087                // ...memcpy the value...
2088                bx.memcpy(
2089                    llscratch,
2090                    scratch_align,
2091                    llval,
2092                    align,
2093                    bx.const_usize(copy_bytes),
2094                    MemFlags::empty(),
2095                    None,
2096                );
2097
2098                // The arguments of an `extern "cmse-nonsecure-call"` function cross the secure
2099                // boundary. Clear any padding bytes so information does not leak.
2100                if conv == CanonAbi::Arm(ArmCall::CCmseNonSecureCall) {
2101                    self.clear_padding_cmse(
2102                        bx,
2103                        llscratch,
2104                        Size::from_bytes(copy_bytes),
2105                        arg.layout,
2106                    );
2107                }
2108
2109                // ...and then load it with the ABI type.
2110                llval = load_cast(bx, cast, llscratch, scratch_align);
2111                bx.lifetime_end(llscratch, scratch_size);
2112            } else {
2113                // We can't use `PlaceRef::load` here because the argument
2114                // may have a type we don't treat as immediate, but the ABI
2115                // used for this call is passing it by-value. In that case,
2116                // the load would just produce `OperandValue::Ref` instead
2117                // of the `OperandValue::Immediate` we need for the call.
2118                llval = bx.load(bx.backend_type(arg.layout), llval, align);
2119                if let BackendRepr::Scalar(scalar) = arg.layout.backend_repr {
2120                    if scalar.is_bool() {
2121                        bx.range_metadata(llval, WrappingRange { start: 0, end: 1 });
2122                    }
2123                    // We store bools as `i8` so we need to truncate to `i1`.
2124                    llval = bx.to_immediate_scalar(llval, scalar);
2125                }
2126            }
2127        }
2128
2129        llargs.push(llval);
2130    }
2131
2132    fn codegen_arguments_untupled(
2133        &mut self,
2134        bx: &mut Bx,
2135        conv: CanonAbi,
2136        operand: &mir::Operand<'tcx>,
2137        llargs: &mut Vec<Bx::Value>,
2138        args: &[ArgAbi<'tcx, Ty<'tcx>>],
2139        lifetime_ends_after_call: &mut Vec<(Bx::Value, Size)>,
2140    ) -> usize {
2141        let tuple = self.codegen_operand(bx, operand);
2142        let by_move = #[allow(non_exhaustive_omitted_patterns)] match operand {
    mir::Operand::Move(_) => true,
    _ => false,
}matches!(operand, mir::Operand::Move(_));
2143
2144        // Handle both by-ref and immediate tuples.
2145        if let Ref(place_val) = tuple.val {
2146            if place_val.llextra.is_some() {
2147                ::rustc_span::macros::bug_impl(None,
    format_args!("closure arguments must be sized"), Location::caller());bug!("closure arguments must be sized");
2148            }
2149            let tuple_ptr = place_val.with_type(tuple.layout);
2150            for i in 0..tuple.layout.fields.count() {
2151                let field_ptr = tuple_ptr.project_field(bx, i);
2152                let field = bx.load_operand(field_ptr);
2153                self.codegen_argument(
2154                    bx,
2155                    conv,
2156                    field,
2157                    by_move,
2158                    llargs,
2159                    &args[i],
2160                    lifetime_ends_after_call,
2161                );
2162            }
2163        } else {
2164            // If the tuple is immediate, the elements are as well.
2165            for i in 0..tuple.layout.fields.count() {
2166                let op = tuple.extract_field(self, bx, i);
2167                self.codegen_argument(
2168                    bx,
2169                    conv,
2170                    op,
2171                    by_move,
2172                    llargs,
2173                    &args[i],
2174                    lifetime_ends_after_call,
2175                );
2176            }
2177        }
2178        tuple.layout.fields.count()
2179    }
2180
2181    pub(super) fn get_caller_location(
2182        &mut self,
2183        bx: &mut Bx,
2184        source_info: mir::SourceInfo,
2185    ) -> OperandRef<'tcx, Bx::Value> {
2186        self.mir.caller_location_span(source_info, self.caller_location, bx.tcx(), |span: Span| {
2187            let const_loc = bx.tcx().span_as_caller_location(span);
2188            OperandRef::from_const(bx, const_loc, bx.tcx().caller_location_ty())
2189        })
2190    }
2191
2192    fn get_personality_slot(&mut self, bx: &mut Bx) -> PlaceRef<'tcx, Bx::Value> {
2193        let cx = bx.cx();
2194        if let Some(slot) = self.personality_slot {
2195            slot
2196        } else {
2197            let layout = cx.layout_of(Ty::new_tup(
2198                cx.tcx(),
2199                &[Ty::new_mut_ptr(cx.tcx(), cx.tcx().types.u8), cx.tcx().types.i32],
2200            ));
2201            let slot = PlaceRef::alloca(bx, layout);
2202            self.personality_slot = Some(slot);
2203            slot
2204        }
2205    }
2206
2207    /// Returns the landing/cleanup pad wrapper around the given basic block.
2208    // FIXME(eddyb) rename this to `eh_pad_for`.
2209    fn landing_pad_for(&mut self, bb: mir::BasicBlock) -> Bx::BasicBlock {
2210        if let Some(landing_pad) = self.landing_pads[bb] {
2211            return landing_pad;
2212        }
2213
2214        let landing_pad = self.landing_pad_for_uncached(bb);
2215        self.landing_pads[bb] = Some(landing_pad);
2216        landing_pad
2217    }
2218
2219    // FIXME(eddyb) rename this to `eh_pad_for_uncached`.
2220    fn landing_pad_for_uncached(&mut self, bb: mir::BasicBlock) -> Bx::BasicBlock {
2221        let llbb = self.llbb(bb);
2222        if base::wants_new_eh_instructions(&self.cx.sess().target) {
2223            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:?}"));
2224            let mut cleanup_bx = Bx::build(self.cx, cleanup_bb);
2225            let funclet = cleanup_bx.cleanup_pad(None, &[]);
2226            cleanup_bx.br(llbb);
2227            self.funclets[bb] = Some(funclet);
2228            cleanup_bb
2229        } else {
2230            let cleanup_llbb = Bx::append_block(self.cx, self.llfn, "cleanup");
2231            let mut cleanup_bx = Bx::build(self.cx, cleanup_llbb);
2232
2233            let llpersonality = self.cx.eh_personality();
2234            let (exn0, exn1) = cleanup_bx.cleanup_landing_pad(llpersonality);
2235
2236            let slot = self.get_personality_slot(&mut cleanup_bx);
2237            slot.storage_live(&mut cleanup_bx);
2238            Pair(exn0, exn1).store(&mut cleanup_bx, slot);
2239
2240            cleanup_bx.br(llbb);
2241            cleanup_llbb
2242        }
2243    }
2244
2245    fn unreachable_block(&mut self) -> Bx::BasicBlock {
2246        self.unreachable_block.unwrap_or_else(|| {
2247            let llbb = Bx::append_block(self.cx, self.llfn, "unreachable");
2248            let mut bx = Bx::build(self.cx, llbb);
2249            bx.unreachable();
2250            self.unreachable_block = Some(llbb);
2251            llbb
2252        })
2253    }
2254
2255    fn terminate_block(
2256        &mut self,
2257        reason: UnwindTerminateReason,
2258        outer_catchpad_bb: Option<mir::BasicBlock>,
2259    ) -> Bx::BasicBlock {
2260        // mb_funclet_bb should be present if and only if the target is wasm and
2261        // we're terminating because of an unwind in a cleanup block. In that
2262        // case we have nested funclets and the inner catch_switch needs to know
2263        // what outer catch_pad it is contained in.
2264        if true {
    if !(outer_catchpad_bb.is_some() ==
                (base::wants_wasm_eh(&self.cx.tcx().sess.target) &&
                        reason == UnwindTerminateReason::InCleanup)) {
        ::core::panicking::panic("assertion failed: outer_catchpad_bb.is_some() ==\n    (base::wants_wasm_eh(&self.cx.tcx().sess.target) &&\n            reason == UnwindTerminateReason::InCleanup)")
    };
};debug_assert!(
2265            outer_catchpad_bb.is_some()
2266                == (base::wants_wasm_eh(&self.cx.tcx().sess.target)
2267                    && reason == UnwindTerminateReason::InCleanup)
2268        );
2269
2270        // When we aren't in a wasm InCleanup block, there's only one terminate
2271        // block needed so we cache at START_BLOCK index.
2272        let mut cache_bb = mir::START_BLOCK;
2273        // In wasm eh InCleanup, use the outer funclet's cleanup BB as the cache
2274        // key.
2275        if let Some(outer_bb) = outer_catchpad_bb {
2276            let cleanup_kinds =
2277                self.cleanup_kinds.as_ref().expect("cleanup_kinds required for funclets");
2278            cache_bb = cleanup_kinds[outer_bb]
2279                .funclet_bb(outer_bb)
2280                .expect("funclet_bb should be in a funclet");
2281
2282            // Ensure the outer funclet is created first
2283            if self.funclets[cache_bb].is_none() {
2284                self.landing_pad_for(cache_bb);
2285            }
2286        }
2287        if let Some((cached_bb, cached_reason)) = self.terminate_blocks[cache_bb]
2288            && reason == cached_reason
2289        {
2290            return cached_bb;
2291        }
2292
2293        let funclet;
2294        let llbb;
2295        let mut bx;
2296        if base::wants_new_eh_instructions(&self.cx.sess().target) {
2297            // This is a basic block that we're aborting the program for,
2298            // notably in an `extern` function. These basic blocks are inserted
2299            // so that we assert that `extern` functions do indeed not panic,
2300            // and if they do we abort the process.
2301            //
2302            // On MSVC these are tricky though (where we're doing funclets). If
2303            // we were to do a cleanuppad (like below) the normal functions like
2304            // `longjmp` would trigger the abort logic, terminating the
2305            // program. Instead we insert the equivalent of `catch(...)` for C++
2306            // which magically doesn't trigger when `longjmp` files over this
2307            // frame.
2308            //
2309            // Lots more discussion can be found on #48251 but this codegen is
2310            // modeled after clang's for:
2311            //
2312            //      try {
2313            //          foo();
2314            //      } catch (...) {
2315            //          bar();
2316            //      }
2317            //
2318            // which creates an IR snippet like
2319            //
2320            //      cs_terminate:
2321            //         %cs = catchswitch within none [%cp_terminate] unwind to caller
2322            //      cp_terminate:
2323            //         %cp = catchpad within %cs [null, i32 64, null]
2324            //         ...
2325            //
2326            // By contrast, on WebAssembly targets, we specifically _do_ want to
2327            // catch foreign exceptions. The situation with MSVC is a
2328            // regrettable hack which we don't want to extend to other targets
2329            // unless necessary. For WebAssembly, to generate catch(...) and
2330            // catch only C++ exception instead of generating a catch_all, we
2331            // need to call the intrinsics @llvm.wasm.get.exception and
2332            // @llvm.wasm.get.ehselector in the catch pad. Since we don't do
2333            // this, we generate a catch_all. We originally got this behavior
2334            // by accident but it luckily matches our intention.
2335
2336            llbb = Bx::append_block(self.cx, self.llfn, "cs_terminate");
2337
2338            let mut cs_bx = Bx::build(self.cx, llbb);
2339
2340            // For wasm InCleanup blocks, our catch_switch is nested within the
2341            // outer catchpad, so we need to provide it as the parent value to
2342            // catch_switch.
2343            let mut outer_cleanuppad = None;
2344            if outer_catchpad_bb.is_some() {
2345                // Get the outer funclet's catchpad
2346                let outer_funclet = self.funclets[cache_bb]
2347                    .as_ref()
2348                    .expect("landing_pad_for didn't create funclet");
2349                outer_cleanuppad = Some(cs_bx.get_funclet_cleanuppad(outer_funclet));
2350            }
2351            let cp_llbb = Bx::append_block(self.cx, self.llfn, "cp_terminate");
2352            let cs = cs_bx.catch_switch(outer_cleanuppad, None, &[cp_llbb]);
2353            drop(cs_bx);
2354
2355            bx = Bx::build(self.cx, cp_llbb);
2356            let null =
2357                bx.const_null(bx.type_ptr_ext(bx.cx().data_layout().instruction_address_space));
2358
2359            // The `null` in first argument here is actually a RTTI type
2360            // descriptor for the C++ personality function, but `catch (...)`
2361            // has no type so it's null.
2362            let args = if base::wants_msvc_seh(&self.cx.sess().target) {
2363                // This bitmask is a single `HT_IsStdDotDot` flag, which
2364                // represents that this is a C++-style `catch (...)` block that
2365                // only captures programmatic exceptions, not all SEH
2366                // exceptions. The second `null` points to a non-existent
2367                // `alloca` instruction, which an LLVM pass would inline into
2368                // the initial SEH frame allocation.
2369                let adjectives = bx.const_i32(0x40);
2370                &[null, adjectives, null] as &[_]
2371            } else {
2372                // Specifying more arguments than necessary usually doesn't
2373                // hurt, but the `WasmEHPrepare` LLVM pass does not recognize
2374                // anything other than a single `null` as a `catch_all` block,
2375                // leading to problems down the line during instruction
2376                // selection.
2377                &[null] as &[_]
2378            };
2379
2380            funclet = Some(bx.catch_pad(cs, args));
2381            // On wasm, if we wanted to generate a catch(...) and only catch C++
2382            // exceptions, we'd call @llvm.wasm.get.exception and
2383            // @llvm.wasm.get.ehselector selectors here. We want a catch_all so
2384            // we leave them out. This is intentionally diverging from the MSVC
2385            // behavior.
2386        } else {
2387            llbb = Bx::append_block(self.cx, self.llfn, "terminate");
2388            bx = Bx::build(self.cx, llbb);
2389
2390            let llpersonality = self.cx.eh_personality();
2391            bx.filter_landing_pad(llpersonality);
2392
2393            funclet = None;
2394        }
2395
2396        self.set_debug_loc(&mut bx, mir::SourceInfo::outermost(self.mir.span));
2397
2398        let (fn_abi, fn_ptr, instance) =
2399            common::build_langcall(&bx, self.mir.span, reason.lang_item());
2400        if is_call_from_compiler_builtins_to_upstream_monomorphization(bx.tcx(), instance) {
2401            bx.abort();
2402        } else {
2403            let fn_ty = bx.fn_decl_backend_type(fn_abi);
2404
2405            let llret = bx.call(
2406                fn_ty,
2407                None,
2408                Some(fn_abi),
2409                fn_ptr,
2410                ReturnSlot::Direct,
2411                &[],
2412                funclet.as_ref(),
2413                None,
2414            );
2415            bx.apply_attrs_to_cleanup_callsite(llret);
2416        }
2417
2418        bx.unreachable();
2419
2420        self.terminate_blocks[cache_bb] = Some((llbb, reason));
2421        llbb
2422    }
2423
2424    /// Get the backend `BasicBlock` for a MIR `BasicBlock`, either already
2425    /// cached in `self.cached_llbbs`, or created on demand (and cached).
2426    // FIXME(eddyb) rename `llbb` and other `ll`-prefixed things to use a
2427    // more backend-agnostic prefix such as `cg` (i.e. this would be `cgbb`).
2428    pub fn llbb(&mut self, bb: mir::BasicBlock) -> Bx::BasicBlock {
2429        self.try_llbb(bb).unwrap()
2430    }
2431
2432    /// Like `llbb`, but may fail if the basic block should be skipped.
2433    pub(crate) fn try_llbb(&mut self, bb: mir::BasicBlock) -> Option<Bx::BasicBlock> {
2434        match self.cached_llbbs[bb] {
2435            CachedLlbb::None => {
2436                let llbb = Bx::append_block(self.cx, self.llfn, &::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0:?}", bb))
    })format!("{bb:?}"));
2437                self.cached_llbbs[bb] = CachedLlbb::Some(llbb);
2438                Some(llbb)
2439            }
2440            CachedLlbb::Some(llbb) => Some(llbb),
2441            CachedLlbb::Skip => None,
2442        }
2443    }
2444
2445    fn make_return_dest(
2446        &mut self,
2447        bx: &mut Bx,
2448        dest: mir::Place<'tcx>,
2449        fn_ret: &ArgAbi<'tcx, Ty<'tcx>>,
2450    ) -> (ReturnDest<'tcx, Bx::Value>, ReturnSlot<Bx::Value>) {
2451        // If the return is ignored, we can just return a do-nothing `ReturnDest`.
2452        if fn_ret.is_ignore() {
2453            return (ReturnDest::Nothing, ReturnSlot::Direct);
2454        }
2455        let dest = if let Some(index) = dest.as_local() {
2456            match self.locals[index] {
2457                LocalRef::Place(dest) => dest,
2458                LocalRef::UnsizedPlace(_) => ::rustc_span::macros::bug_impl(None,
    format_args!("return type must be sized"), Location::caller())bug!("return type must be sized"),
2459                LocalRef::PendingOperand => {
2460                    // Handle temporary places, specifically `Operand` ones, as
2461                    // they don't have `alloca`s.
2462                    return if fn_ret.is_indirect() {
2463                        // Odd, but possible, case, we have an operand temporary,
2464                        // but the calling convention has an indirect return.
2465                        let tmp = PlaceRef::alloca(bx, fn_ret.layout);
2466                        tmp.storage_live(bx);
2467                        (
2468                            ReturnDest::IndirectOperand(tmp, index),
2469                            ReturnSlot::Indirect(tmp.val.llval),
2470                        )
2471                    } else {
2472                        (ReturnDest::DirectOperand(index), ReturnSlot::Direct)
2473                    };
2474                }
2475                LocalRef::Operand(_) => {
2476                    ::rustc_span::macros::bug_impl(None,
    format_args!("place local already assigned to"), Location::caller());bug!("place local already assigned to");
2477                }
2478            }
2479        } else {
2480            self.codegen_place(bx, dest.as_ref())
2481        };
2482        if fn_ret.is_indirect() {
2483            if dest.val.align < dest.layout.align.abi {
2484                // Currently, MIR code generation does not create calls
2485                // that store directly to fields of packed structs (in
2486                // fact, the calls it creates write only to temps).
2487                //
2488                // If someone changes that, please update this code path
2489                // to create a temporary.
2490                ::rustc_span::macros::bug_impl(Some(self.mir.span),
    format_args!("can\'t directly store to unaligned value"),
    Location::caller());span_bug!(self.mir.span, "can't directly store to unaligned value");
2491            }
2492            (ReturnDest::Nothing, ReturnSlot::Indirect(dest.val.llval))
2493        } else {
2494            (ReturnDest::Store(dest), ReturnSlot::Direct)
2495        }
2496    }
2497
2498    // Stores the return value of a function call into it's final location.
2499    fn store_return(
2500        &mut self,
2501        bx: &mut Bx,
2502        dest: ReturnDest<'tcx, Bx::Value>,
2503        ret_abi: &ArgAbi<'tcx, Ty<'tcx>>,
2504        llval: Bx::Value,
2505    ) {
2506        use self::ReturnDest::*;
2507        let retags_enabled = bx.tcx().sess.opts.unstable_opts.codegen_emit_retag.is_some();
2508        match dest {
2509            Nothing => (),
2510            Store(dst) => {
2511                bx.store_arg(ret_abi, llval, dst);
2512                if retags_enabled {
2513                    self.codegen_retag_place(bx, dst, false);
2514                }
2515            }
2516            IndirectOperand(tmp, index) => {
2517                let mut op = bx.load_operand(tmp);
2518                tmp.storage_dead(bx);
2519                if retags_enabled {
2520                    op = self.codegen_retag_operand(bx, op, false);
2521                }
2522                self.overwrite_local(index, LocalRef::Operand(op));
2523                self.debug_introduce_local(bx, index);
2524            }
2525            DirectOperand(index) => {
2526                // If there is a cast, we have to store and reload.
2527                let mut op = if let PassMode::Cast { .. } = ret_abi.mode {
2528                    let tmp = PlaceRef::alloca(bx, ret_abi.layout);
2529                    tmp.storage_live(bx);
2530                    bx.store_arg(ret_abi, llval, tmp);
2531                    let op = bx.load_operand(tmp);
2532                    tmp.storage_dead(bx);
2533                    op
2534                } else {
2535                    OperandRef::from_immediate_or_packed_pair(bx, llval, ret_abi.layout)
2536                };
2537                if retags_enabled {
2538                    op = self.codegen_retag_operand(bx, op, false);
2539                }
2540                self.overwrite_local(index, LocalRef::Operand(op));
2541                self.debug_introduce_local(bx, index);
2542            }
2543        }
2544    }
2545}
2546
2547enum ReturnDest<'tcx, V> {
2548    /// Do nothing; the return value is indirect or ignored.
2549    Nothing,
2550    /// Store the return value to the pointer.
2551    Store(PlaceRef<'tcx, V>),
2552    /// Store an indirect return value to an operand local place.
2553    IndirectOperand(PlaceRef<'tcx, V>, mir::Local),
2554    /// Store a direct return value to an operand local place.
2555    DirectOperand(mir::Local),
2556}
2557
2558fn load_cast<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
2559    bx: &mut Bx,
2560    cast: &CastTarget,
2561    ptr: Bx::Value,
2562    align: Align,
2563) -> Bx::Value {
2564    let cast_ty = bx.cast_backend_type(cast);
2565    if let Some(offset_from_start) = cast.rest_offset {
2566        {
    match (&cast.prefix.len(), &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::None);
            }
        }
    }
};assert_eq!(cast.prefix.len(), 1);
2567        {
    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);
2568        let first_ty = bx.reg_backend_type(&cast.prefix[0]);
2569        let second_ty = bx.reg_backend_type(&cast.rest.unit);
2570        let first = bx.load(first_ty, ptr, align);
2571        let second_ptr = bx.inbounds_ptradd(ptr, bx.const_usize(offset_from_start.bytes()));
2572        let second = bx.load(second_ty, second_ptr, align.restrict_for_offset(offset_from_start));
2573        let res = bx.cx().const_poison(cast_ty);
2574        let res = bx.insert_value(res, first, 0);
2575        bx.insert_value(res, second, 1)
2576    } else {
2577        bx.load(cast_ty, ptr, align)
2578    }
2579}
2580
2581pub fn store_cast<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
2582    bx: &mut Bx,
2583    cast: &CastTarget,
2584    value: Bx::Value,
2585    ptr: Bx::Value,
2586    align: Align,
2587) {
2588    if let Some(offset_from_start) = cast.rest_offset {
2589        {
    match (&cast.prefix.len(), &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::None);
            }
        }
    }
};assert_eq!(cast.prefix.len(), 1);
2590        {
    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);
2591        let first = bx.extract_value(value, 0);
2592        let second = bx.extract_value(value, 1);
2593        bx.store(first, ptr, align);
2594        let second_ptr = bx.inbounds_ptradd(ptr, bx.const_usize(offset_from_start.bytes()));
2595        bx.store(second, second_ptr, align.restrict_for_offset(offset_from_start));
2596    } else {
2597        bx.store(value, ptr, align);
2598    };
2599}