Skip to main content

rustc_codegen_ssa/mir/
block.rs

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