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