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