Skip to main content

rustc_codegen_ssa/mir/
block.rs

1use std::cmp;
2use std::ops::Range;
3
4use rustc_abi::{
5    Align, ArmCall, BackendRepr, CanonAbi, ExternAbi, FieldsShape, HasDataLayout, Reg, Size,
6    VariantIdx, Variants, WrappingRange,
7};
8use rustc_ast as ast;
9use rustc_ast::{InlineAsmOptions, InlineAsmTemplatePiece};
10use rustc_data_structures::packed::Pu128;
11use rustc_hir::attrs::AttributeKind;
12use rustc_hir::attrs::lang_items::LangItem;
13use rustc_lint_defs::builtin::TAIL_CALL_TRACK_CALLER;
14use rustc_middle::mir::interpret::{CTFE_ALLOC_SALT, Scalar};
15use rustc_middle::mir::{self, AssertKind, InlineAsmMacro, SwitchTargets, UnwindTerminateReason};
16use rustc_middle::ty::layout::{HasTyCtxt, LayoutOf, TyAndLayout, ValidityRequirement};
17use rustc_middle::ty::print::{with_no_trimmed_paths, with_no_visible_paths};
18use rustc_middle::ty::{self, Instance, Ty, TypeVisitableExt};
19use rustc_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, 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                if let Ref(place_val) = op.val {
585                    bx.load_from_place(bx.backend_type(op.layout), place_val)
586                } else {
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                };
617
618                if self.fn_abi.conv == CanonAbi::Arm(ArmCall::CCmseNonSecureEntry) {
619                    // The return value of an `extern "cmse-nonsecure-entry"` function crosses the
620                    // secure boundary. Clear any padding bytes so information does not leak.
621                    let ret_layout = self.fn_abi.ret.layout;
622                    self.clear_padding_cmse(bx, llslot, ret_layout.size, ret_layout);
623                }
624
625                load_cast(bx, cast_ty, llslot, self.fn_abi.ret.layout.align.abi)
626            }
627        };
628        bx.ret(llval);
629    }
630
631    #[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(631u32),
                                    ::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:680",
                                                "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(680u32),
                                                ::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:681",
                                                "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(681u32),
                                                ::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:682",
                                                "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(682u32),
                                                ::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))]
632    fn codegen_drop_terminator(
633        &mut self,
634        helper: TerminatorCodegenHelper<'tcx>,
635        bx: &mut Bx,
636        source_info: &mir::SourceInfo,
637        location: mir::Place<'tcx>,
638        target: mir::BasicBlock,
639        unwind: mir::UnwindAction,
640        mergeable_succ: bool,
641    ) -> MergingSucc {
642        let ty = location.ty(self.mir, bx.tcx()).ty;
643        let ty = self.monomorphize(ty);
644        let drop_fn = Instance::resolve_drop_glue(bx.tcx(), ty);
645
646        if let ty::InstanceKind::Shim(ty::ShimKind::DropGlue(_, None)) = drop_fn.def {
647            // we don't actually need to drop anything.
648            return helper.funclet_br(self, bx, target, mergeable_succ, &[]);
649        }
650
651        let place = self.codegen_place(bx, location.as_ref());
652        let (args1, args2);
653        let mut args = if let Some(llextra) = place.val.llextra {
654            args2 = [place.val.llval, llextra];
655            &args2[..]
656        } else {
657            args1 = [place.val.llval];
658            &args1[..]
659        };
660        let (maybe_null, drop_fn, fn_abi, drop_instance) = match ty.kind() {
661            // FIXME(eddyb) perhaps move some of this logic into
662            // `Instance::resolve_drop_glue`?
663            ty::Dynamic(_, _) => {
664                // IN THIS ARM, WE HAVE:
665                // ty = *mut (dyn Trait)
666                // which is: exists<T> ( *mut T,    Vtable<T: Trait> )
667                //                       args[0]    args[1]
668                //
669                // args = ( Data, Vtable )
670                //                  |
671                //                  v
672                //                /-------\
673                //                | ...   |
674                //                \-------/
675                //
676                let virtual_drop = Instance {
677                    def: ty::InstanceKind::Virtual(drop_fn.def_id(), 0), // idx 0: the drop function
678                    args: drop_fn.args,
679                };
680                debug!("ty = {:?}", ty);
681                debug!("drop_fn = {:?}", drop_fn);
682                debug!("args = {:?}", args);
683                let fn_abi = bx.fn_abi_of_instance(virtual_drop, ty::List::empty());
684                let vtable = args[1];
685                // Truncate vtable off of args list
686                args = &args[..1];
687                (
688                    true,
689                    meth::VirtualIndex::from_index(ty::COMMON_VTABLE_ENTRIES_DROPINPLACE)
690                        .get_optional_fn(bx, vtable, ty, fn_abi),
691                    fn_abi,
692                    virtual_drop,
693                )
694            }
695            _ => (
696                false,
697                bx.get_fn_addr(drop_fn, bx.sess().pointer_authentication_functions()),
698                bx.fn_abi_of_instance(drop_fn, ty::List::empty()),
699                drop_fn,
700            ),
701        };
702
703        // We generate a null check for the drop_fn. This saves a bunch of relocations being
704        // generated for no-op drops.
705        if maybe_null {
706            let is_not_null = bx.append_sibling_block("is_not_null");
707            let llty = bx.fn_ptr_backend_type(fn_abi);
708            let null = bx.const_null(llty);
709            let non_null =
710                bx.icmp(base::bin_op_to_icmp_predicate(mir::BinOp::Ne, false), drop_fn, null);
711            bx.cond_br(non_null, is_not_null, helper.llbb_with_cleanup(self, target));
712            bx.switch_to_block(is_not_null);
713            self.set_debug_loc(bx, *source_info);
714        }
715
716        helper.do_call(
717            self,
718            bx,
719            fn_abi,
720            drop_fn,
721            args,
722            Some((ReturnDest::Nothing, target)),
723            unwind,
724            &[],
725            Some(drop_instance),
726            CallKind::Normal,
727            !maybe_null && mergeable_succ,
728        )
729    }
730
731    fn codegen_assert_terminator(
732        &mut self,
733        helper: TerminatorCodegenHelper<'tcx>,
734        bx: &mut Bx,
735        terminator: &mir::Terminator<'tcx>,
736        cond: &mir::Operand<'tcx>,
737        expected: bool,
738        msg: &mir::AssertMessage<'tcx>,
739        target: mir::BasicBlock,
740        unwind: mir::UnwindAction,
741        mergeable_succ: bool,
742    ) -> MergingSucc {
743        let span = terminator.source_info.span;
744        let cond = self.codegen_operand(bx, cond).immediate();
745        let mut const_cond = bx.const_to_opt_u128(cond, false).map(|c| c == 1);
746
747        // This case can currently arise only from functions marked
748        // with #[rustc_inherit_overflow_checks] and inlined from
749        // another crate (mostly core::num generic/#[inline] fns),
750        // while the current crate doesn't use overflow checks.
751        if !bx.sess().overflow_checks() && msg.is_optional_overflow_check() {
752            const_cond = Some(expected);
753        }
754
755        // Don't codegen the panic block if success if known.
756        if const_cond == Some(expected) {
757            return helper.funclet_br(self, bx, target, mergeable_succ, &[]);
758        }
759
760        // Because we're branching to a panic block (either a `#[cold]` one
761        // or an inlined abort), there's no need to `expect` it.
762
763        // Create the failure block and the conditional branch to it.
764        let lltarget = helper.llbb_with_cleanup(self, target);
765        let panic_block = bx.append_sibling_block("panic");
766        if expected {
767            bx.cond_br(cond, lltarget, panic_block);
768        } else {
769            bx.cond_br(cond, panic_block, lltarget);
770        }
771
772        // After this point, bx is the block for the call to panic.
773        bx.switch_to_block(panic_block);
774        self.set_debug_loc(bx, terminator.source_info);
775
776        // Get the location information.
777        let location = self.get_caller_location(bx, terminator.source_info).immediate();
778
779        // Put together the arguments to the panic entry point.
780        let (lang_item, args) = match msg {
781            AssertKind::BoundsCheck { len, index } => {
782                let len = self.codegen_operand(bx, len).immediate();
783                let index = self.codegen_operand(bx, index).immediate();
784                // It's `fn panic_bounds_check(index: usize, len: usize)`,
785                // and `#[track_caller]` adds an implicit third argument.
786                (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])
787            }
788            AssertKind::MisalignedPointerDereference { required, found } => {
789                let required = self.codegen_operand(bx, required).immediate();
790                let found = self.codegen_operand(bx, found).immediate();
791                // It's `fn panic_misaligned_pointer_dereference(required: usize, found: usize)`,
792                // and `#[track_caller]` adds an implicit third argument.
793                (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])
794            }
795            AssertKind::NullPointerDereference => {
796                // It's `fn panic_null_pointer_dereference()`,
797                // `#[track_caller]` adds an implicit argument.
798                (LangItem::PanicNullPointerDereference, ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [location]))vec![location])
799            }
800            AssertKind::NullReferenceConstructed => {
801                // It's `fn panic_null_reference_constructed()`,
802                // `#[track_caller]` adds an implicit argument.
803                (LangItem::PanicNullReferenceConstructed, ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [location]))vec![location])
804            }
805            AssertKind::InvalidEnumConstruction(source) => {
806                let source = self.codegen_operand(bx, source).immediate();
807                // It's `fn panic_invalid_enum_construction(source: u128)`,
808                // `#[track_caller]` adds an implicit argument.
809                (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])
810            }
811            _ => {
812                // It's `pub fn panic_...()` and `#[track_caller]` adds an implicit argument.
813                (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])
814            }
815        };
816
817        let (fn_abi, llfn, instance) = common::build_langcall(bx, span, lang_item);
818
819        // Codegen the actual panic invoke/call.
820        let merging_succ = helper.do_call(
821            self,
822            bx,
823            fn_abi,
824            llfn,
825            &args,
826            None,
827            unwind,
828            &[],
829            Some(instance),
830            CallKind::Normal,
831            false,
832        );
833        {
    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);
834        MergingSucc::False
835    }
836
837    fn codegen_terminate_terminator(
838        &mut self,
839        helper: TerminatorCodegenHelper<'tcx>,
840        bx: &mut Bx,
841        terminator: &mir::Terminator<'tcx>,
842        reason: UnwindTerminateReason,
843    ) {
844        let span = terminator.source_info.span;
845        self.set_debug_loc(bx, terminator.source_info);
846
847        // Obtain the panic entry point.
848        let (fn_abi, llfn, instance) = common::build_langcall(bx, span, reason.lang_item());
849
850        // Codegen the actual panic invoke/call.
851        let merging_succ = helper.do_call(
852            self,
853            bx,
854            fn_abi,
855            llfn,
856            &[],
857            None,
858            mir::UnwindAction::Unreachable,
859            &[],
860            Some(instance),
861            CallKind::Normal,
862            false,
863        );
864        {
    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);
865    }
866
867    /// Returns `Some` if this is indeed a panic intrinsic and codegen is done.
868    fn codegen_panic_intrinsic(
869        &mut self,
870        helper: &TerminatorCodegenHelper<'tcx>,
871        bx: &mut Bx,
872        intrinsic: ty::IntrinsicDef,
873        instance: Instance<'tcx>,
874        source_info: mir::SourceInfo,
875        target: Option<mir::BasicBlock>,
876        unwind: mir::UnwindAction,
877        mergeable_succ: bool,
878    ) -> Option<MergingSucc> {
879        // Emit a panic or a no-op for `assert_*` intrinsics.
880        // These are intrinsics that compile to panics so that we can get a message
881        // which mentions the offending type, even from a const context.
882        let Some(requirement) = ValidityRequirement::from_intrinsic(intrinsic.name) else {
883            return None;
884        };
885
886        let ty = instance.args.type_at(0);
887
888        let is_valid = bx
889            .tcx()
890            .check_validity_requirement((requirement, bx.typing_env().as_query_input(ty)))
891            .expect("expect to have layout during codegen");
892
893        if is_valid {
894            // a NOP
895            let target = target.unwrap();
896            return Some(helper.funclet_br(self, bx, target, mergeable_succ, &[]));
897        }
898
899        let layout = bx.layout_of(ty);
900
901        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!({
902            with_no_trimmed_paths!({
903                if layout.is_uninhabited() {
904                    // Use this error even for the other intrinsics as it is more precise.
905                    format!("attempted to instantiate uninhabited type `{ty}`")
906                } else if requirement == ValidityRequirement::Zero {
907                    format!("attempted to zero-initialize type `{ty}`, which is invalid")
908                } else {
909                    format!("attempted to leave type `{ty}` uninitialized, which is invalid")
910                }
911            })
912        });
913        let msg = bx.const_str(&msg_str);
914
915        // Obtain the panic entry point.
916        let (fn_abi, llfn, instance) =
917            common::build_langcall(bx, source_info.span, LangItem::PanicNounwind);
918
919        // Codegen the actual panic invoke/call.
920        Some(helper.do_call(
921            self,
922            bx,
923            fn_abi,
924            llfn,
925            &[msg.0, msg.1],
926            target.as_ref().map(|bb| (ReturnDest::Nothing, *bb)),
927            unwind,
928            &[],
929            Some(instance),
930            CallKind::Normal,
931            mergeable_succ,
932        ))
933    }
934
935    fn codegen_call_terminator(
936        &mut self,
937        helper: TerminatorCodegenHelper<'tcx>,
938        bx: &mut Bx,
939        terminator: &mir::Terminator<'tcx>,
940        func: &mir::Operand<'tcx>,
941        args: &[Spanned<mir::Operand<'tcx>>],
942        destination: mir::Place<'tcx>,
943        target: Option<mir::BasicBlock>,
944        unwind: mir::UnwindAction,
945        fn_span: Span,
946        kind: CallKind,
947        mergeable_succ: bool,
948    ) -> MergingSucc {
949        let source_info = mir::SourceInfo { span: fn_span, ..terminator.source_info };
950
951        // Create the callee. This is a fn ptr or zero-sized and hence a kind of scalar.
952        let callee = self.codegen_operand(bx, func);
953
954        let (instance, mut llfn) = match *callee.layout.ty.kind() {
955            ty::FnDef(def_id, generic_args) => {
956                let instance = ty::Instance::expect_resolve(
957                    bx.tcx(),
958                    bx.typing_env(),
959                    def_id,
960                    generic_args.no_bound_vars().unwrap(),
961                    fn_span,
962                );
963
964                match instance.def {
965                    // We don't need AsyncDropGlueCtorShim here because it is not `noop func`,
966                    // it is `func returning noop future`
967                    ty::InstanceKind::Shim(ty::ShimKind::DropGlue(_, None)) => {
968                        // Empty drop glue; a no-op.
969                        let target = target.unwrap();
970                        return helper.funclet_br(self, bx, target, mergeable_succ, &[]);
971                    }
972                    ty::InstanceKind::Intrinsic(def_id) => {
973                        let intrinsic = bx.tcx().intrinsic(def_id).unwrap();
974                        if let Some(merging_succ) = self.codegen_panic_intrinsic(
975                            &helper,
976                            bx,
977                            intrinsic,
978                            instance,
979                            source_info,
980                            target,
981                            unwind,
982                            mergeable_succ,
983                        ) {
984                            return merging_succ;
985                        }
986
987                        let result_layout =
988                            self.cx.layout_of(self.monomorphized_place_ty(destination.as_ref()));
989
990                        let (result_place, store_in_local) =
991                            if let Some(local) = destination.as_local() {
992                                match self.locals[local] {
993                                    LocalRef::Place(dest) => (Some(dest.val), None),
994                                    LocalRef::UnsizedPlace(_) => ::rustc_middle::util::bug::bug_fmt(format_args!("return type must be sized"))bug!("return type must be sized"),
995                                    LocalRef::PendingOperand => (None, Some(local)),
996                                    LocalRef::Operand(_) => {
997                                        if result_layout.is_zst() {
998                                            let place = PlaceRef::new_sized(
999                                                bx.const_undef(bx.type_ptr()),
1000                                                result_layout,
1001                                            );
1002                                            (Some(place.val), None)
1003                                        } else {
1004                                            ::rustc_middle::util::bug::bug_fmt(format_args!("place local already assigned to"));bug!("place local already assigned to");
1005                                        }
1006                                    }
1007                                }
1008                            } else {
1009                                (Some(self.codegen_place(bx, destination.as_ref()).val), None)
1010                            };
1011
1012                        if let Some(place) = result_place
1013                            && place.align < result_layout.align.abi
1014                        {
1015                            // Currently, MIR code generation does not create calls
1016                            // that store directly to fields of packed structs (in
1017                            // fact, the calls it creates write only to temps).
1018                            //
1019                            // If someone changes that, please update this code path
1020                            // to create a temporary.
1021                            ::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");
1022                        }
1023
1024                        let args: Vec<_> =
1025                            args.iter().map(|arg| self.codegen_operand(bx, &arg.node)).collect();
1026
1027                        let intrinsic_result = self.codegen_intrinsic_call(
1028                            bx,
1029                            instance,
1030                            &args,
1031                            result_layout,
1032                            result_place,
1033                            source_info,
1034                        );
1035
1036                        if let IntrinsicResult::Operand(op_val) = intrinsic_result {
1037                            match (result_place, store_in_local) {
1038                                (None, Some(local)) => {
1039                                    let op = OperandRef {
1040                                        val: op_val,
1041                                        layout: result_layout,
1042                                        move_annotation: None,
1043                                    };
1044                                    self.overwrite_local(local, LocalRef::Operand(op));
1045                                    self.debug_introduce_local(bx, local);
1046                                }
1047                                (Some(place_val), None) => {
1048                                    let dest = PlaceRef { val: place_val, layout: result_layout };
1049                                    op_val.store(bx, dest);
1050                                }
1051                                _ => ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!(),
1052                            }
1053                        }
1054
1055                        match intrinsic_result {
1056                            IntrinsicResult::Operand(_) | IntrinsicResult::WroteIntoPlace => {
1057                                return if let Some(target) = target {
1058                                    helper.funclet_br(self, bx, target, mergeable_succ, &[])
1059                                } else {
1060                                    bx.unreachable();
1061                                    MergingSucc::False
1062                                };
1063                            }
1064                            IntrinsicResult::Err(_) => {
1065                                // Even though we're definitely going to error, we need it initialize
1066                                // the local or `maybe_codegen_consume_direct` might ICE later
1067                                // when it goes to use the result from this intrinsic.
1068                                if let Some(local) = store_in_local {
1069                                    let op = OperandRef {
1070                                        val: OperandValue::poison(bx, result_layout),
1071                                        layout: result_layout,
1072                                        move_annotation: None,
1073                                    };
1074                                    self.overwrite_local(local, LocalRef::Operand(op));
1075                                }
1076                                // Also we need to terminate the block to avoid an LLVM assertion,
1077                                // even though we're not going to actually use the IR.
1078                                bx.abort();
1079                                return MergingSucc::False;
1080                            }
1081                            IntrinsicResult::Fallback(instance) => {
1082                                if intrinsic.must_be_overridden {
1083                                    ::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!(
1084                                        fn_span,
1085                                        "intrinsic {} must be overridden by codegen backend, but isn't",
1086                                        intrinsic.name,
1087                                    );
1088                                }
1089                                (Some(instance), None)
1090                            }
1091                        }
1092                    }
1093
1094                    _ if kind == CallKind::Tail
1095                        && instance.def.requires_caller_location(bx.tcx()) =>
1096                    {
1097                        if let Some(hir_id) =
1098                            terminator.source_info.scope.lint_root(&self.mir.source_scopes)
1099                        {
1100                            bx.tcx().emit_node_lint(TAIL_CALL_TRACK_CALLER, hir_id, rustc_errors::DiagDecorator(|d| {
1101                                _ = d.primary_message("tail calling a function marked with `#[track_caller]` has no special effect").span(fn_span)
1102                            }));
1103                        }
1104
1105                        let instance = ty::Instance::resolve_for_fn_ptr(
1106                            bx.tcx(),
1107                            bx.typing_env(),
1108                            def_id,
1109                            generic_args.no_bound_vars().unwrap(),
1110                        )
1111                        .unwrap();
1112
1113                        (
1114                            None,
1115                            Some(bx.get_fn_addr(
1116                                instance,
1117                                bx.sess().pointer_authentication_functions(),
1118                            )),
1119                        )
1120                    }
1121                    _ => (Some(instance), None),
1122                }
1123            }
1124            ty::FnPtr(..) => (None, Some(callee.immediate())),
1125            _ => ::rustc_middle::util::bug::bug_fmt(format_args!("{0} is not callable",
        callee.layout.ty))bug!("{} is not callable", callee.layout.ty),
1126        };
1127
1128        if let Some(instance) = instance
1129            && let ty::InstanceKind::LlvmIntrinsic(_) = instance.def
1130            && let Some(name) = bx.tcx().codegen_fn_attrs(instance.def_id()).symbol_name
1131            // This is the only LLVM intrinsic we use that unwinds
1132            // FIXME either add unwind support to codegen_llvm_intrinsic_call or replace usage of
1133            // this intrinsic with something else
1134            && name.as_str() != "llvm.wasm.throw"
1135        {
1136            if !!instance.args.has_infer() {
    ::core::panicking::panic("assertion failed: !instance.args.has_infer()")
};assert!(!instance.args.has_infer());
1137            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());
1138
1139            let result_layout =
1140                self.cx.layout_of(self.monomorphized_place_ty(destination.as_ref()));
1141
1142            let return_dest = if result_layout.is_zst() {
1143                ReturnDest::Nothing
1144            } else if let Some(index) = destination.as_local() {
1145                match self.locals[index] {
1146                    LocalRef::Place(dest) => ReturnDest::Store(dest),
1147                    LocalRef::UnsizedPlace(_) => ::rustc_middle::util::bug::bug_fmt(format_args!("return type must be sized"))bug!("return type must be sized"),
1148                    LocalRef::PendingOperand => {
1149                        // Handle temporary places, specifically `Operand` ones, as
1150                        // they don't have `alloca`s.
1151                        ReturnDest::DirectOperand(index)
1152                    }
1153                    LocalRef::Operand(_) => ::rustc_middle::util::bug::bug_fmt(format_args!("place local already assigned to"))bug!("place local already assigned to"),
1154                }
1155            } else {
1156                ReturnDest::Store(self.codegen_place(bx, destination.as_ref()))
1157            };
1158
1159            let args =
1160                args.into_iter().map(|arg| self.codegen_operand(bx, &arg.node)).collect::<Vec<_>>();
1161
1162            self.set_debug_loc(bx, source_info);
1163
1164            let llret =
1165                bx.codegen_llvm_intrinsic_call(instance, &args, self.mir[helper.bb].is_cleanup);
1166
1167            if let Some(target) = target {
1168                self.store_return(
1169                    bx,
1170                    return_dest,
1171                    &ArgAbi { layout: result_layout, mode: PassMode::Direct(ArgAttributes::new()) },
1172                    llret,
1173                );
1174                return helper.funclet_br(self, bx, target, mergeable_succ, &[]);
1175            } else {
1176                bx.unreachable();
1177                return MergingSucc::False;
1178            }
1179        }
1180
1181        // FIXME(eddyb) avoid computing this if possible, when `instance` is
1182        // available - right now `sig` is only needed for getting the `abi`
1183        // and figuring out how many extra args were passed to a C-variadic `fn`.
1184        let sig = callee.layout.ty.fn_sig(bx.tcx());
1185
1186        let extra_args = &args[sig.inputs().skip_binder().len()..];
1187        let extra_args = bx.tcx().mk_type_list_from_iter(extra_args.iter().map(|op_arg| {
1188            let op_ty = op_arg.node.ty(self.mir, bx.tcx());
1189            self.monomorphize(op_ty)
1190        }));
1191
1192        let fn_abi = match instance {
1193            Some(instance) => bx.fn_abi_of_instance(instance, extra_args),
1194            None => bx.fn_abi_of_fn_ptr(sig, extra_args),
1195        };
1196
1197        // The arguments we'll be passing. Plus one to account for outptr, if used.
1198        let arg_count = fn_abi.args.len() + fn_abi.ret.is_indirect() as usize;
1199
1200        let mut llargs = Vec::with_capacity(arg_count);
1201
1202        // We still need to call `make_return_dest` even if there's no `target`, since
1203        // `fn_abi.ret` could be `PassMode::Indirect`, even if it is uninhabited,
1204        // and `make_return_dest` adds the return-place indirect pointer to `llargs`.
1205        let destination = match kind {
1206            CallKind::Normal => {
1207                let return_dest = self.make_return_dest(bx, destination, &fn_abi.ret, &mut llargs);
1208                target.map(|target| (return_dest, target))
1209            }
1210            CallKind::Tail => {
1211                if fn_abi.ret.is_indirect() {
1212                    match self.make_return_dest(bx, destination, &fn_abi.ret, &mut llargs) {
1213                        ReturnDest::Nothing => {}
1214                        _ => ::rustc_middle::util::bug::bug_fmt(format_args!("tail calls to functions with indirect returns cannot store into a destination"))bug!(
1215                            "tail calls to functions with indirect returns cannot store into a destination"
1216                        ),
1217                    }
1218                }
1219                None
1220            }
1221        };
1222
1223        // Split the rust-call tupled arguments off.
1224        // FIXME(splat): un-tuple splatted arguments in codegen, for performance
1225        let (first_args, untuple) = if sig.abi() == ExternAbi::RustCall
1226            && let Some((tup, args)) = args.split_last()
1227        {
1228            (args, Some(tup))
1229        } else {
1230            (args, None)
1231        };
1232
1233        // Special logic for tail calls with `PassMode::Indirect { on_stack: false, .. }` arguments.
1234        //
1235        // Normally an indirect argument that is allocated in the caller's stack frame
1236        // would be passed as a pointer into the callee's stack frame.
1237        // For tail calls, that would be unsound, because the caller's
1238        // stack frame is overwritten by the callee's stack frame.
1239        //
1240        // Therefore we store the argument for the callee in the corresponding caller's slot.
1241        // Because guaranteed tail calls demand that the caller's signature matches the callee's,
1242        // the corresponding slot has the correct type.
1243        //
1244        // To handle cases like the one below, the tail call arguments must first be copied to a
1245        // temporary, and only then copied to the caller's argument slots.
1246        //
1247        // ```
1248        // // A struct big enough that it is not passed via registers.
1249        // pub struct Big([u64; 4]);
1250        //
1251        // fn swapper(a: Big, b: Big) -> (Big, Big) {
1252        //     become swapper_helper(b, a);
1253        // }
1254        // ```
1255        let mut tail_call_temporaries = ::alloc::vec::Vec::new()vec![];
1256        if kind == CallKind::Tail {
1257            tail_call_temporaries = ::alloc::vec::from_elem(None, first_args.len())vec![None; first_args.len()];
1258            // Copy the arguments that use `PassMode::Indirect { on_stack: false , ..}`
1259            // to temporary stack allocations. See the comment above.
1260            for (i, arg) in first_args.iter().enumerate() {
1261                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, .. }) {
1262                    continue;
1263                }
1264
1265                let op = self.codegen_operand(bx, &arg.node);
1266                let tmp = PlaceRef::alloca(bx, op.layout);
1267                bx.lifetime_start(tmp.val.llval, tmp.layout.size);
1268                op.store_with_annotation(bx, tmp);
1269
1270                tail_call_temporaries[i] = Some(tmp);
1271            }
1272        }
1273
1274        // When generating arguments we sometimes introduce temporary allocations with lifetime
1275        // that extend for the duration of a call. Keep track of those allocations and their sizes
1276        // to generate `lifetime_end` when the call returns.
1277        let mut lifetime_ends_after_call: Vec<(Bx::Value, Size)> = Vec::new();
1278        'make_args: for (i, arg) in first_args.iter().enumerate() {
1279            let mut op = self.codegen_operand(bx, &arg.node);
1280
1281            if let (0, Some(ty::InstanceKind::Virtual(_, idx))) = (i, instance.map(|i| i.def)) {
1282                match op.val {
1283                    Pair(data_ptr, meta) => {
1284                        // In the case of Rc<Self>, we need to explicitly pass a
1285                        // *mut RcInner<Self> with a Scalar (not ScalarPair) ABI. This is a hack
1286                        // that is understood elsewhere in the compiler as a method on
1287                        // `dyn Trait`.
1288                        // To get a `*mut RcInner<Self>`, we just keep unwrapping newtypes until
1289                        // we get a value of a built-in pointer type.
1290                        //
1291                        // This is also relevant for `Pin<&mut Self>`, where we need to peel the
1292                        // `Pin`.
1293                        while !op.layout.ty.is_raw_ptr() && !op.layout.ty.is_ref() {
1294                            let (idx, _) = op.layout.non_1zst_field(bx).expect(
1295                                "not exactly one non-1-ZST field in a `DispatchFromDyn` type",
1296                            );
1297                            op = op.extract_field(self, bx, idx.as_usize());
1298                        }
1299
1300                        // Now that we have `*dyn Trait` or `&dyn Trait`, split it up into its
1301                        // data pointer and vtable. Look up the method in the vtable, and pass
1302                        // the data pointer as the first argument.
1303                        llfn = Some(meth::VirtualIndex::from_index(idx).get_fn(
1304                            bx,
1305                            meta,
1306                            op.layout.ty,
1307                            fn_abi,
1308                        ));
1309                        llargs.push(data_ptr);
1310                        continue 'make_args;
1311                    }
1312                    Ref(PlaceValue { llval: data_ptr, llextra: Some(meta), .. }) => {
1313                        // by-value dynamic dispatch
1314                        llfn = Some(meth::VirtualIndex::from_index(idx).get_fn(
1315                            bx,
1316                            meta,
1317                            op.layout.ty,
1318                            fn_abi,
1319                        ));
1320                        llargs.push(data_ptr);
1321                        continue;
1322                    }
1323                    _ => {
1324                        ::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);
1325                    }
1326                }
1327            }
1328
1329            let by_move = if let PassMode::Indirect { on_stack: false, .. } = fn_abi.args[i].mode
1330                && kind == CallKind::Tail
1331            {
1332                // Special logic for tail calls with `PassMode::Indirect { on_stack: false, .. }` arguments.
1333                //
1334                // Normally an indirect argument that is allocated in the caller's stack frame
1335                // would be passed as a pointer into the callee's stack frame.
1336                // For tail calls, that would be unsound, because the caller's
1337                // stack frame is overwritten by the callee's stack frame.
1338                //
1339                // To handle the case, we introduce `tail_call_temporaries` to copy arguments into
1340                // temporaries, then copy back to the caller's argument slots.
1341                // Finally, we pass the caller's argument slots as arguments.
1342                //
1343                // To do that, the argument must be MUST-by-move value.
1344                let Some(tmp) = tail_call_temporaries[i].take() else {
1345                    ::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}")
1346                };
1347
1348                let local = self.mir.args_iter().nth(i).unwrap();
1349
1350                match &self.locals[local] {
1351                    LocalRef::Place(arg) => {
1352                        bx.typed_place_copy(arg.val, tmp.val, fn_abi.args[i].layout);
1353                        op.val = Ref(arg.val);
1354                    }
1355                    LocalRef::Operand(arg) => {
1356                        let Ref(place_value) = arg.val else {
1357                            ::rustc_middle::util::bug::bug_fmt(format_args!("only `Ref` should use `PassMode::Indirect`, but got {0:?}",
        arg.val));bug!(
1358                                "only `Ref` should use `PassMode::Indirect`, but got {:?}",
1359                                arg.val
1360                            );
1361                        };
1362                        bx.typed_place_copy(place_value, tmp.val, fn_abi.args[i].layout);
1363                        op.val = arg.val;
1364                    }
1365                    LocalRef::UnsizedPlace(_) => {
1366                        ::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")
1367                    }
1368                    LocalRef::PendingOperand => {
1369                        ::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")
1370                    }
1371                };
1372
1373                bx.lifetime_end(tmp.val.llval, tmp.layout.size);
1374                true
1375            } else {
1376                #[allow(non_exhaustive_omitted_patterns)] match arg.node {
    mir::Operand::Move(_) => true,
    _ => false,
}matches!(arg.node, mir::Operand::Move(_))
1377            };
1378
1379            self.codegen_argument(
1380                bx,
1381                fn_abi.conv,
1382                op,
1383                by_move,
1384                &mut llargs,
1385                &fn_abi.args[i],
1386                &mut lifetime_ends_after_call,
1387            );
1388        }
1389        let num_untupled = untuple.map(|tup| {
1390            self.codegen_arguments_untupled(
1391                bx,
1392                fn_abi.conv,
1393                &tup.node,
1394                &mut llargs,
1395                &fn_abi.args[first_args.len()..],
1396                &mut lifetime_ends_after_call,
1397            )
1398        });
1399
1400        let needs_location =
1401            instance.is_some_and(|i| i.def.requires_caller_location(self.cx.tcx()));
1402        if needs_location {
1403            let mir_args = if let Some(num_untupled) = num_untupled {
1404                first_args.len() + num_untupled
1405            } else {
1406                args.len()
1407            };
1408            {
    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!(
1409                fn_abi.args.len(),
1410                mir_args + 1,
1411                "#[track_caller] fn's must have 1 more argument in their ABI than in their MIR: {instance:?} {fn_span:?} {fn_abi:?}",
1412            );
1413            let location = self.get_caller_location(bx, source_info);
1414            {
    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:1414",
                        "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(1414u32),
                        ::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!(
1415                "codegen_call_terminator({:?}): location={:?} (fn_span {:?})",
1416                terminator, location, fn_span
1417            );
1418
1419            let last_arg = fn_abi.args.last().unwrap();
1420            self.codegen_argument(
1421                bx,
1422                fn_abi.conv,
1423                location,
1424                /* by_move */ false,
1425                &mut llargs,
1426                last_arg,
1427                &mut lifetime_ends_after_call,
1428            );
1429        }
1430
1431        let fn_ptr = match (instance, llfn) {
1432            (Some(instance), None) => {
1433                bx.get_fn_addr(instance, bx.sess().pointer_authentication_functions())
1434            }
1435            (_, Some(llfn)) => llfn,
1436            _ => ::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"),
1437        };
1438        self.set_debug_loc(bx, source_info);
1439        helper.do_call(
1440            self,
1441            bx,
1442            fn_abi,
1443            fn_ptr,
1444            &llargs,
1445            destination,
1446            unwind,
1447            &lifetime_ends_after_call,
1448            instance,
1449            kind,
1450            mergeable_succ,
1451        )
1452    }
1453
1454    fn codegen_asm_terminator(
1455        &mut self,
1456        helper: TerminatorCodegenHelper<'tcx>,
1457        bx: &mut Bx,
1458        asm_macro: InlineAsmMacro,
1459        terminator: &mir::Terminator<'tcx>,
1460        template: &[ast::InlineAsmTemplatePiece],
1461        operands: &[mir::InlineAsmOperand<'tcx>],
1462        options: ast::InlineAsmOptions,
1463        line_spans: &[Span],
1464        targets: &[mir::BasicBlock],
1465        unwind: mir::UnwindAction,
1466        instance: Instance<'_>,
1467        mergeable_succ: bool,
1468    ) -> MergingSucc {
1469        let span = terminator.source_info.span;
1470
1471        let operands: Vec<_> = operands
1472            .iter()
1473            .map(|op| match *op {
1474                mir::InlineAsmOperand::In { reg, ref value } => {
1475                    let value = self.codegen_operand(bx, value);
1476                    InlineAsmOperandRef::In { reg, value }
1477                }
1478                mir::InlineAsmOperand::Out { reg, late, ref place } => {
1479                    let place = place.map(|place| self.codegen_place(bx, place.as_ref()));
1480                    InlineAsmOperandRef::Out { reg, late, place }
1481                }
1482                mir::InlineAsmOperand::InOut { reg, late, ref in_value, ref out_place } => {
1483                    let in_value = self.codegen_operand(bx, in_value);
1484                    let out_place =
1485                        out_place.map(|out_place| self.codegen_place(bx, out_place.as_ref()));
1486                    InlineAsmOperandRef::InOut { reg, late, in_value, out_place }
1487                }
1488                mir::InlineAsmOperand::Const { ref value } => {
1489                    let const_value = self.eval_mir_constant(value);
1490                    let mir::ConstValue::Scalar(scalar) = const_value else {
1491                        ::rustc_middle::util::bug::span_bug_fmt(span,
    format_args!("expected Scalar for promoted asm const, but got {0:#?}",
        const_value))span_bug!(
1492                            span,
1493                            "expected Scalar for promoted asm const, but got {:#?}",
1494                            const_value
1495                        )
1496                    };
1497                    InlineAsmOperandRef::Const {
1498                        value: common::asm_const_ptr_clean(bx.tcx(), scalar),
1499                        ty: value.ty(),
1500                    }
1501                }
1502                mir::InlineAsmOperand::SymFn { ref value } => {
1503                    let const_ = self.monomorphize(value.const_);
1504                    if let ty::FnDef(def_id, args) = *const_.ty().kind() {
1505                        let instance = ty::Instance::resolve_for_fn_ptr(
1506                            bx.tcx(),
1507                            bx.typing_env(),
1508                            def_id,
1509                            args.no_bound_vars().unwrap(),
1510                        )
1511                        .unwrap();
1512
1513                        InlineAsmOperandRef::Const {
1514                            value: Scalar::from_pointer(
1515                                bx.tcx().reserve_and_set_fn_alloc(instance, CTFE_ALLOC_SALT).into(),
1516                                bx,
1517                            ),
1518                            ty: Ty::new_fn_ptr(bx.tcx(), const_.ty().fn_sig(bx.tcx())),
1519                        }
1520                    } else {
1521                        ::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)");
1522                    }
1523                }
1524                mir::InlineAsmOperand::SymStatic { def_id } => {
1525                    if bx.tcx().is_thread_local_static(def_id) {
1526                        InlineAsmOperandRef::SymThreadLocalStatic { def_id }
1527                    } else {
1528                        InlineAsmOperandRef::Const {
1529                            value: Scalar::from_pointer(
1530                                bx.tcx().reserve_and_set_static_alloc(def_id).into(),
1531                                bx,
1532                            ),
1533                            ty: bx.tcx().static_ptr_ty(def_id, bx.typing_env()),
1534                        }
1535                    }
1536                }
1537                mir::InlineAsmOperand::Label { target_index } => {
1538                    InlineAsmOperandRef::Label { label: self.llbb(targets[target_index]) }
1539                }
1540            })
1541            .collect();
1542
1543        helper.do_inlineasm(
1544            self,
1545            bx,
1546            template,
1547            &operands,
1548            options,
1549            line_spans,
1550            if asm_macro.diverges(options) { None } else { targets.get(0).copied() },
1551            unwind,
1552            instance,
1553            mergeable_succ,
1554        )
1555    }
1556
1557    pub(crate) fn codegen_block(&mut self, mut bb: mir::BasicBlock) {
1558        let llbb = match self.try_llbb(bb) {
1559            Some(llbb) => llbb,
1560            None => return,
1561        };
1562        let bx = &mut Bx::build(self.cx, llbb);
1563        let mir = self.mir;
1564
1565        // MIR basic blocks stop at any function call. This may not be the case
1566        // for the backend's basic blocks, in which case we might be able to
1567        // combine multiple MIR basic blocks into a single backend basic block.
1568        loop {
1569            let data = &mir[bb];
1570
1571            {
    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:1571",
                        "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(1571u32),
                        ::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);
1572
1573            for statement in &data.statements {
1574                self.codegen_statement(bx, statement);
1575            }
1576            self.codegen_stmt_debuginfos(bx, &data.after_last_stmt_debuginfos);
1577
1578            let merging_succ = self.codegen_terminator(bx, bb, data.terminator());
1579            if let MergingSucc::False = merging_succ {
1580                break;
1581            }
1582
1583            // We are merging the successor into the produced backend basic
1584            // block. Record that the successor should be skipped when it is
1585            // reached.
1586            //
1587            // Note: we must not have already generated code for the successor.
1588            // This is implicitly ensured by the reverse postorder traversal,
1589            // and the assertion explicitly guarantees that.
1590            let mut successors = data.terminator().successors();
1591            let succ = successors.next().unwrap();
1592            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));
1593            self.cached_llbbs[succ] = CachedLlbb::Skip;
1594            bb = succ;
1595        }
1596    }
1597
1598    pub(crate) fn codegen_block_as_unreachable(&mut self, bb: mir::BasicBlock) {
1599        let llbb = match self.try_llbb(bb) {
1600            Some(llbb) => llbb,
1601            None => return,
1602        };
1603        let bx = &mut Bx::build(self.cx, llbb);
1604        {
    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:1604",
                        "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(1604u32),
                        ::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);
1605        bx.unreachable();
1606    }
1607
1608    fn codegen_terminator(
1609        &mut self,
1610        bx: &mut Bx,
1611        bb: mir::BasicBlock,
1612        terminator: &'tcx mir::Terminator<'tcx>,
1613    ) -> MergingSucc {
1614        {
    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:1614",
                        "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(1614u32),
                        ::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);
1615
1616        let helper = TerminatorCodegenHelper { bb, terminator };
1617
1618        let mergeable_succ = || {
1619            // Note: any call to `switch_to_block` will invalidate a `true` value
1620            // of `mergeable_succ`.
1621            let mut successors = terminator.successors();
1622            if let Some(succ) = successors.next()
1623                && successors.next().is_none()
1624                && let &[succ_pred] = self.mir.basic_blocks.predecessors()[succ].as_slice()
1625            {
1626                // bb has a single successor, and bb is its only predecessor. This
1627                // makes it a candidate for merging.
1628                {
    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);
1629                true
1630            } else {
1631                false
1632            }
1633        };
1634
1635        self.set_debug_loc(bx, terminator.source_info);
1636        match terminator.kind {
1637            mir::TerminatorKind::UnwindResume => {
1638                self.codegen_resume_terminator(helper, bx);
1639                MergingSucc::False
1640            }
1641
1642            mir::TerminatorKind::UnwindTerminate(reason) => {
1643                self.codegen_terminate_terminator(helper, bx, terminator, reason);
1644                MergingSucc::False
1645            }
1646
1647            mir::TerminatorKind::Goto { target } => {
1648                helper.funclet_br(self, bx, target, mergeable_succ(), &terminator.attributes)
1649            }
1650
1651            mir::TerminatorKind::SwitchInt { ref discr, ref targets } => {
1652                self.codegen_switchint_terminator(helper, bx, discr, targets);
1653                MergingSucc::False
1654            }
1655
1656            mir::TerminatorKind::Return => {
1657                self.codegen_return_terminator(bx);
1658                MergingSucc::False
1659            }
1660
1661            mir::TerminatorKind::Unreachable => {
1662                bx.unreachable();
1663                MergingSucc::False
1664            }
1665
1666            mir::TerminatorKind::Drop { place, target, unwind, replace: _, drop } => {
1667                if !drop.is_none() {
    {
        ::core::panicking::panic_fmt(format_args!("Async Drop must be expanded or reset to sync before codegen"));
    }
};assert!(
1668                    drop.is_none(),
1669                    "Async Drop must be expanded or reset to sync before codegen"
1670                );
1671                self.codegen_drop_terminator(
1672                    helper,
1673                    bx,
1674                    &terminator.source_info,
1675                    place,
1676                    target,
1677                    unwind,
1678                    mergeable_succ(),
1679                )
1680            }
1681
1682            mir::TerminatorKind::Assert { ref cond, expected, ref msg, target, unwind } => self
1683                .codegen_assert_terminator(
1684                    helper,
1685                    bx,
1686                    terminator,
1687                    cond,
1688                    expected,
1689                    msg,
1690                    target,
1691                    unwind,
1692                    mergeable_succ(),
1693                ),
1694
1695            mir::TerminatorKind::Call {
1696                ref func,
1697                ref args,
1698                destination,
1699                target,
1700                unwind,
1701                call_source: _,
1702                fn_span,
1703            } => self.codegen_call_terminator(
1704                helper,
1705                bx,
1706                terminator,
1707                func,
1708                args,
1709                destination,
1710                target,
1711                unwind,
1712                fn_span,
1713                CallKind::Normal,
1714                mergeable_succ(),
1715            ),
1716            mir::TerminatorKind::TailCall { ref func, ref args, fn_span } => self
1717                .codegen_call_terminator(
1718                    helper,
1719                    bx,
1720                    terminator,
1721                    func,
1722                    args,
1723                    mir::Place::from(mir::RETURN_PLACE),
1724                    None,
1725                    mir::UnwindAction::Unreachable,
1726                    fn_span,
1727                    CallKind::Tail,
1728                    mergeable_succ(),
1729                ),
1730            mir::TerminatorKind::CoroutineDrop | mir::TerminatorKind::Yield { .. } => {
1731                ::rustc_middle::util::bug::bug_fmt(format_args!("coroutine ops in codegen"))bug!("coroutine ops in codegen")
1732            }
1733            mir::TerminatorKind::FalseEdge { .. } | mir::TerminatorKind::FalseUnwind { .. } => {
1734                ::rustc_middle::util::bug::bug_fmt(format_args!("borrowck false edges in codegen"))bug!("borrowck false edges in codegen")
1735            }
1736
1737            mir::TerminatorKind::InlineAsm {
1738                asm_macro,
1739                template,
1740                ref operands,
1741                options,
1742                line_spans,
1743                ref targets,
1744                unwind,
1745            } => self.codegen_asm_terminator(
1746                helper,
1747                bx,
1748                asm_macro,
1749                terminator,
1750                template,
1751                operands,
1752                options,
1753                line_spans,
1754                targets,
1755                unwind,
1756                self.instance,
1757                mergeable_succ(),
1758            ),
1759        }
1760    }
1761
1762    /// When using CMSE, values that cross the secure boundary from secure to non-secure mode can
1763    /// contain stale secure data in their padding bytes. This function clears that data. This is
1764    /// required when a value is:
1765    ///
1766    /// - passed to an `extern "cmse-nonsecure-call"` function
1767    /// - returned from an `extern "cmse-nonsecure-entry"` function
1768    ///
1769    /// This function clears both:
1770    ///
1771    /// - variant-independent padding, bytes that are padding for all valid values of the type
1772    /// - variant-dependent padding, bytes that are padding for some but not all values of the type
1773    ///
1774    /// Clearing variant-dependent padding requires looking at the data at runtime to determine what
1775    /// bytes to clear.
1776    fn clear_padding_cmse(
1777        &mut self,
1778        bx: &mut Bx,
1779        base_ptr: Bx::Value,
1780        limit: Size,
1781        layout: TyAndLayout<'tcx>,
1782    ) {
1783        // First clear variant-independent padding, a series of memsets.
1784        let variant_independent = layout.variant_independent_padding_ranges(self.cx);
1785        self.zero_byte_ranges(bx, base_ptr, Size::ZERO, limit, &variant_independent);
1786
1787        // Then clear the extra padding of the active variant of any (nested) enum.
1788        self.clear_variant_dependent_padding(bx, base_ptr, Size::ZERO, limit, layout);
1789    }
1790
1791    fn clear_variant_dependent_padding(
1792        &mut self,
1793        bx: &mut Bx,
1794        base_ptr: Bx::Value,
1795        base_offset: Size,
1796        limit: Size,
1797        layout: TyAndLayout<'tcx>,
1798    ) {
1799        let cx = self.cx;
1800
1801        if !layout.has_variant_dependent_padding(cx) {
1802            return;
1803        }
1804
1805        // Recurse into aggregate fields/elements to reach any nested enums.
1806        match layout.fields {
1807            FieldsShape::Array { stride, count } => {
1808                let elem = layout.field(cx, 0);
1809                if elem.has_variant_dependent_padding(cx) {
1810                    for idx in 0..count {
1811                        let off = base_offset + idx * stride;
1812                        self.clear_variant_dependent_padding(bx, base_ptr, off, limit, elem);
1813                    }
1814                }
1815            }
1816            FieldsShape::Arbitrary { .. } => {
1817                for i in 0..layout.fields.count() {
1818                    let field = layout.field(cx, i);
1819                    if field.has_variant_dependent_padding(cx) {
1820                        let off = base_offset + layout.fields.offset(i);
1821                        self.clear_variant_dependent_padding(bx, base_ptr, off, limit, field);
1822                    }
1823                }
1824            }
1825            FieldsShape::Primitive | FieldsShape::Union(_) => { /* nothing to visit */ }
1826        }
1827
1828        // If this is not a multi-variant enum, we're done.
1829        let Variants::Multiple { ref variants, .. } = layout.variants else {
1830            return;
1831        };
1832
1833        // Collect variants that will need padding cleared.
1834        let mut work = Vec::with_capacity(variants.len());
1835        for i in 0..variants.len() {
1836            let idx = VariantIdx::from_usize(i);
1837            let variant = layout.for_variant(cx, idx);
1838
1839            // Don't consider uninhabited variants.
1840            if variant.is_uninhabited() {
1841                continue;
1842            }
1843
1844            let variant_dependent = layout.variant_dependent_padding_ranges(cx, idx);
1845            let has_nested_variant_dependent = (0..variant.fields.count())
1846                .any(|i| variant.field(cx, i).has_variant_dependent_padding(cx));
1847
1848            if !variant_dependent.is_empty() || has_nested_variant_dependent {
1849                work.push((idx, variant, variant_dependent));
1850            }
1851        }
1852
1853        if work.is_empty() {
1854            return;
1855        }
1856
1857        // Build the switch and clear the appropriate padding for each variant.
1858        let root_block = bx.llbb();
1859        let join_block = bx.append_sibling_block("cmse_pad_join");
1860        let mut cases = Vec::with_capacity(work.len());
1861
1862        for (idx, variant, variant_dependent) in work.into_iter() {
1863            let Some(discr) = layout.ty.discriminant_for_variant(bx.tcx(), idx) else {
1864                ::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");
1865            };
1866
1867            let variant_block = bx.append_sibling_block("cmse_pad_variant");
1868            bx.switch_to_block(variant_block);
1869
1870            // Clear the padding of this variant.
1871            self.zero_byte_ranges(bx, base_ptr, base_offset, limit, &variant_dependent);
1872
1873            // Recurse into the fields.
1874            for i in 0..variant.fields.count() {
1875                let field = variant.field(cx, i);
1876                let off = base_offset + variant.fields.offset(i);
1877                self.clear_variant_dependent_padding(bx, base_ptr, off, limit, field);
1878            }
1879
1880            bx.br(join_block);
1881            cases.push((discr.val, variant_block));
1882        }
1883
1884        // Construct the dispatch.
1885        bx.switch_to_block(root_block);
1886
1887        let discr_ty = layout.ty.discriminant_ty(bx.tcx());
1888        let enum_ptr = bx.inbounds_ptradd(base_ptr, bx.const_usize(base_offset.bytes()));
1889        let operand = OperandRef {
1890            val: OperandValue::Ref(PlaceValue::new_sized(enum_ptr, layout.align.abi)),
1891            layout,
1892            move_annotation: None,
1893        };
1894        let discr = operand.codegen_get_discr(self, bx, discr_ty);
1895
1896        // Default to the join block (for variants without variant-dependent padding).
1897        bx.switch(discr, join_block, cases.into_iter());
1898
1899        bx.switch_to_block(join_block);
1900    }
1901
1902    fn zero_byte_ranges(
1903        &mut self,
1904        bx: &mut Bx,
1905        ptr: Bx::Value,
1906        offset: Size,
1907        limit: Size,
1908        ranges: &[Range<Size>],
1909    ) {
1910        let zero = bx.const_u8(0);
1911
1912        for range in ranges {
1913            let start = range.start + offset;
1914            let end = range.end + offset;
1915
1916            let end = cmp::min(end, limit);
1917            if range.start >= end {
1918                continue;
1919            }
1920            let offset = bx.const_usize(start.bytes());
1921            let len = bx.const_usize((end - start).bytes());
1922            let ptr = bx.inbounds_ptradd(ptr, offset);
1923            bx.memset(ptr, zero, len, Align::ONE, MemFlags::empty());
1924        }
1925    }
1926
1927    fn codegen_argument(
1928        &mut self,
1929        bx: &mut Bx,
1930        conv: CanonAbi,
1931        op: OperandRef<'tcx, Bx::Value>,
1932        by_move: bool,
1933        llargs: &mut Vec<Bx::Value>,
1934        arg: &ArgAbi<'tcx, Ty<'tcx>>,
1935        lifetime_ends_after_call: &mut Vec<(Bx::Value, Size)>,
1936    ) {
1937        match arg.mode {
1938            PassMode::Ignore => return,
1939            PassMode::Cast { pad_i32: true, .. } => {
1940                // Fill padding with undef value, where applicable.
1941                llargs.push(bx.const_undef(bx.reg_backend_type(&Reg::i32())));
1942            }
1943            PassMode::Pair(..) => match op.val {
1944                Pair(a, b) => {
1945                    llargs.push(a);
1946                    llargs.push(b);
1947                    return;
1948                }
1949                _ => ::rustc_middle::util::bug::bug_fmt(format_args!("codegen_argument: {0:?} invalid for pair argument",
        op))bug!("codegen_argument: {:?} invalid for pair argument", op),
1950            },
1951            PassMode::Indirect { attrs: _, meta_attrs: Some(_), on_stack: _ } => match op.val {
1952                Ref(PlaceValue { llval: a, llextra: Some(b), .. }) => {
1953                    llargs.push(a);
1954                    llargs.push(b);
1955                    return;
1956                }
1957                _ => ::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),
1958            },
1959            _ => {}
1960        }
1961
1962        // Force by-ref if we have to load through a cast pointer.
1963        let (mut llval, align, by_ref) = match op.val {
1964            Immediate(_) | Pair(..) => match arg.mode {
1965                PassMode::Indirect { attrs, .. } => {
1966                    // Indirect argument may have higher alignment requirements than the type's
1967                    // alignment. This can happen, e.g. when passing types with <4 byte alignment
1968                    // on the stack on x86.
1969                    let required_align = match attrs.pointee_align {
1970                        Some(pointee_align) => cmp::max(pointee_align, arg.layout.align.abi),
1971                        None => arg.layout.align.abi,
1972                    };
1973                    let scratch = PlaceValue::alloca(bx, arg.layout.size, required_align);
1974                    bx.lifetime_start(scratch.llval, arg.layout.size);
1975                    op.store_with_annotation(bx, scratch.with_type(arg.layout));
1976                    lifetime_ends_after_call.push((scratch.llval, arg.layout.size));
1977                    (scratch.llval, scratch.align, true)
1978                }
1979                PassMode::Cast { .. } => {
1980                    let scratch = PlaceRef::alloca(bx, arg.layout);
1981                    op.store_with_annotation(bx, scratch);
1982                    (scratch.val.llval, scratch.val.align, true)
1983                }
1984                PassMode::Direct(_) => (op.immediate(), arg.layout.align.abi, false),
1985                PassMode::Ignore | PassMode::Pair(..) => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("handled above")));
}unreachable!("handled above"),
1986            },
1987            Ref(op_place_val) => match arg.mode {
1988                PassMode::Indirect { attrs, on_stack, .. } => {
1989                    // For `foo(packed.large_field)`, and types with <4 byte alignment on x86,
1990                    // alignment requirements may be higher than the type's alignment, so copy
1991                    // to a higher-aligned alloca.
1992                    let required_align = match attrs.pointee_align {
1993                        Some(pointee_align) => cmp::max(pointee_align, arg.layout.align.abi),
1994                        None => arg.layout.align.abi,
1995                    };
1996                    // Copy to an alloca when the argument is neither by-val nor by-move.
1997                    if op_place_val.align < required_align || (!on_stack && !by_move) {
1998                        let scratch = PlaceValue::alloca(bx, arg.layout.size, required_align);
1999                        bx.lifetime_start(scratch.llval, arg.layout.size);
2000                        op.store_with_annotation(bx, scratch.with_type(arg.layout));
2001                        lifetime_ends_after_call.push((scratch.llval, arg.layout.size));
2002                        (scratch.llval, scratch.align, true)
2003                    } else {
2004                        (op_place_val.llval, op_place_val.align, true)
2005                    }
2006                }
2007                _ => (op_place_val.llval, op_place_val.align, true),
2008            },
2009            ZeroSized => match arg.mode {
2010                PassMode::Indirect { on_stack, .. } => {
2011                    if on_stack {
2012                        // It doesn't seem like any target can have `byval` ZSTs, so this assert
2013                        // is here to replace a would-be untested codepath.
2014                        ::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:?}");
2015                    }
2016                    // Though `extern "Rust"` doesn't pass ZSTs, some ABIs pass
2017                    // a pointer for `repr(C)` structs even when empty, so get
2018                    // one from an `alloca` (which can be left uninitialized).
2019                    let scratch = PlaceRef::alloca(bx, arg.layout);
2020                    (scratch.val.llval, scratch.val.align, true)
2021                }
2022                _ => ::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:?}"),
2023            },
2024        };
2025
2026        if by_ref && !arg.is_indirect() {
2027            // Have to load the argument, maybe while casting it.
2028            if let PassMode::Cast { cast, pad_i32: _ } = &arg.mode {
2029                // The ABI mandates that the value is passed as a different struct representation.
2030                // Spill and reload it from the stack to convert from the Rust representation to
2031                // the ABI representation.
2032                let scratch_size = cast.size(bx);
2033                let scratch_align = cast.align(bx);
2034                // Note that the ABI type may be either larger or smaller than the Rust type,
2035                // due to the presence or absence of trailing padding. For example:
2036                // - On some ABIs, the Rust layout { f64, f32, <f32 padding> } may omit padding
2037                //   when passed by value, making it smaller.
2038                // - On some ABIs, the Rust layout { u16, u16, u16 } may be padded up to 8 bytes
2039                //   when passed by value, making it larger.
2040                let copy_bytes = cmp::min(cast.unaligned_size(bx).bytes(), arg.layout.size.bytes());
2041                // Allocate some scratch space...
2042                let llscratch = bx.alloca(scratch_size, scratch_align);
2043                bx.lifetime_start(llscratch, scratch_size);
2044                // ...memcpy the value...
2045                bx.memcpy(
2046                    llscratch,
2047                    scratch_align,
2048                    llval,
2049                    align,
2050                    bx.const_usize(copy_bytes),
2051                    MemFlags::empty(),
2052                    None,
2053                );
2054
2055                // The arguments of an `extern "cmse-nonsecure-call"` function cross the secure
2056                // boundary. Clear any padding bytes so information does not leak.
2057                if conv == CanonAbi::Arm(ArmCall::CCmseNonSecureCall) {
2058                    self.clear_padding_cmse(
2059                        bx,
2060                        llscratch,
2061                        Size::from_bytes(copy_bytes),
2062                        arg.layout,
2063                    );
2064                }
2065
2066                // ...and then load it with the ABI type.
2067                llval = load_cast(bx, cast, llscratch, scratch_align);
2068                bx.lifetime_end(llscratch, scratch_size);
2069            } else {
2070                // We can't use `PlaceRef::load` here because the argument
2071                // may have a type we don't treat as immediate, but the ABI
2072                // used for this call is passing it by-value. In that case,
2073                // the load would just produce `OperandValue::Ref` instead
2074                // of the `OperandValue::Immediate` we need for the call.
2075                llval = bx.load(bx.backend_type(arg.layout), llval, align);
2076                if let BackendRepr::Scalar(scalar) = arg.layout.backend_repr {
2077                    if scalar.is_bool() {
2078                        bx.range_metadata(llval, WrappingRange { start: 0, end: 1 });
2079                    }
2080                    // We store bools as `i8` so we need to truncate to `i1`.
2081                    llval = bx.to_immediate_scalar(llval, scalar);
2082                }
2083            }
2084        }
2085
2086        llargs.push(llval);
2087    }
2088
2089    fn codegen_arguments_untupled(
2090        &mut self,
2091        bx: &mut Bx,
2092        conv: CanonAbi,
2093        operand: &mir::Operand<'tcx>,
2094        llargs: &mut Vec<Bx::Value>,
2095        args: &[ArgAbi<'tcx, Ty<'tcx>>],
2096        lifetime_ends_after_call: &mut Vec<(Bx::Value, Size)>,
2097    ) -> usize {
2098        let tuple = self.codegen_operand(bx, operand);
2099        let by_move = #[allow(non_exhaustive_omitted_patterns)] match operand {
    mir::Operand::Move(_) => true,
    _ => false,
}matches!(operand, mir::Operand::Move(_));
2100
2101        // Handle both by-ref and immediate tuples.
2102        if let Ref(place_val) = tuple.val {
2103            if place_val.llextra.is_some() {
2104                ::rustc_middle::util::bug::bug_fmt(format_args!("closure arguments must be sized"));bug!("closure arguments must be sized");
2105            }
2106            let tuple_ptr = place_val.with_type(tuple.layout);
2107            for i in 0..tuple.layout.fields.count() {
2108                let field_ptr = tuple_ptr.project_field(bx, i);
2109                let field = bx.load_operand(field_ptr);
2110                self.codegen_argument(
2111                    bx,
2112                    conv,
2113                    field,
2114                    by_move,
2115                    llargs,
2116                    &args[i],
2117                    lifetime_ends_after_call,
2118                );
2119            }
2120        } else {
2121            // If the tuple is immediate, the elements are as well.
2122            for i in 0..tuple.layout.fields.count() {
2123                let op = tuple.extract_field(self, bx, i);
2124                self.codegen_argument(
2125                    bx,
2126                    conv,
2127                    op,
2128                    by_move,
2129                    llargs,
2130                    &args[i],
2131                    lifetime_ends_after_call,
2132                );
2133            }
2134        }
2135        tuple.layout.fields.count()
2136    }
2137
2138    pub(super) fn get_caller_location(
2139        &mut self,
2140        bx: &mut Bx,
2141        source_info: mir::SourceInfo,
2142    ) -> OperandRef<'tcx, Bx::Value> {
2143        self.mir.caller_location_span(source_info, self.caller_location, bx.tcx(), |span: Span| {
2144            let const_loc = bx.tcx().span_as_caller_location(span);
2145            OperandRef::from_const(bx, const_loc, bx.tcx().caller_location_ty())
2146        })
2147    }
2148
2149    fn get_personality_slot(&mut self, bx: &mut Bx) -> PlaceRef<'tcx, Bx::Value> {
2150        let cx = bx.cx();
2151        if let Some(slot) = self.personality_slot {
2152            slot
2153        } else {
2154            let layout = cx.layout_of(Ty::new_tup(
2155                cx.tcx(),
2156                &[Ty::new_mut_ptr(cx.tcx(), cx.tcx().types.u8), cx.tcx().types.i32],
2157            ));
2158            let slot = PlaceRef::alloca(bx, layout);
2159            self.personality_slot = Some(slot);
2160            slot
2161        }
2162    }
2163
2164    /// Returns the landing/cleanup pad wrapper around the given basic block.
2165    // FIXME(eddyb) rename this to `eh_pad_for`.
2166    fn landing_pad_for(&mut self, bb: mir::BasicBlock) -> Bx::BasicBlock {
2167        if let Some(landing_pad) = self.landing_pads[bb] {
2168            return landing_pad;
2169        }
2170
2171        let landing_pad = self.landing_pad_for_uncached(bb);
2172        self.landing_pads[bb] = Some(landing_pad);
2173        landing_pad
2174    }
2175
2176    // FIXME(eddyb) rename this to `eh_pad_for_uncached`.
2177    fn landing_pad_for_uncached(&mut self, bb: mir::BasicBlock) -> Bx::BasicBlock {
2178        let llbb = self.llbb(bb);
2179        if base::wants_new_eh_instructions(self.cx.sess()) {
2180            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:?}"));
2181            let mut cleanup_bx = Bx::build(self.cx, cleanup_bb);
2182            let funclet = cleanup_bx.cleanup_pad(None, &[]);
2183            cleanup_bx.br(llbb);
2184            self.funclets[bb] = Some(funclet);
2185            cleanup_bb
2186        } else {
2187            let cleanup_llbb = Bx::append_block(self.cx, self.llfn, "cleanup");
2188            let mut cleanup_bx = Bx::build(self.cx, cleanup_llbb);
2189
2190            let llpersonality = self.cx.eh_personality();
2191            let (exn0, exn1) = cleanup_bx.cleanup_landing_pad(llpersonality);
2192
2193            let slot = self.get_personality_slot(&mut cleanup_bx);
2194            slot.storage_live(&mut cleanup_bx);
2195            Pair(exn0, exn1).store(&mut cleanup_bx, slot);
2196
2197            cleanup_bx.br(llbb);
2198            cleanup_llbb
2199        }
2200    }
2201
2202    fn unreachable_block(&mut self) -> Bx::BasicBlock {
2203        self.unreachable_block.unwrap_or_else(|| {
2204            let llbb = Bx::append_block(self.cx, self.llfn, "unreachable");
2205            let mut bx = Bx::build(self.cx, llbb);
2206            bx.unreachable();
2207            self.unreachable_block = Some(llbb);
2208            llbb
2209        })
2210    }
2211
2212    fn terminate_block(
2213        &mut self,
2214        reason: UnwindTerminateReason,
2215        outer_catchpad_bb: Option<mir::BasicBlock>,
2216    ) -> Bx::BasicBlock {
2217        // mb_funclet_bb should be present if and only if the target is wasm and
2218        // we're terminating because of an unwind in a cleanup block. In that
2219        // case we have nested funclets and the inner catch_switch needs to know
2220        // what outer catch_pad it is contained in.
2221        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!(
2222            outer_catchpad_bb.is_some()
2223                == (base::wants_wasm_eh(self.cx.tcx().sess)
2224                    && reason == UnwindTerminateReason::InCleanup)
2225        );
2226
2227        // When we aren't in a wasm InCleanup block, there's only one terminate
2228        // block needed so we cache at START_BLOCK index.
2229        let mut cache_bb = mir::START_BLOCK;
2230        // In wasm eh InCleanup, use the outer funclet's cleanup BB as the cache
2231        // key.
2232        if let Some(outer_bb) = outer_catchpad_bb {
2233            let cleanup_kinds =
2234                self.cleanup_kinds.as_ref().expect("cleanup_kinds required for funclets");
2235            cache_bb = cleanup_kinds[outer_bb]
2236                .funclet_bb(outer_bb)
2237                .expect("funclet_bb should be in a funclet");
2238
2239            // Ensure the outer funclet is created first
2240            if self.funclets[cache_bb].is_none() {
2241                self.landing_pad_for(cache_bb);
2242            }
2243        }
2244        if let Some((cached_bb, cached_reason)) = self.terminate_blocks[cache_bb]
2245            && reason == cached_reason
2246        {
2247            return cached_bb;
2248        }
2249
2250        let funclet;
2251        let llbb;
2252        let mut bx;
2253        if base::wants_new_eh_instructions(self.cx.sess()) {
2254            // This is a basic block that we're aborting the program for,
2255            // notably in an `extern` function. These basic blocks are inserted
2256            // so that we assert that `extern` functions do indeed not panic,
2257            // and if they do we abort the process.
2258            //
2259            // On MSVC these are tricky though (where we're doing funclets). If
2260            // we were to do a cleanuppad (like below) the normal functions like
2261            // `longjmp` would trigger the abort logic, terminating the
2262            // program. Instead we insert the equivalent of `catch(...)` for C++
2263            // which magically doesn't trigger when `longjmp` files over this
2264            // frame.
2265            //
2266            // Lots more discussion can be found on #48251 but this codegen is
2267            // modeled after clang's for:
2268            //
2269            //      try {
2270            //          foo();
2271            //      } catch (...) {
2272            //          bar();
2273            //      }
2274            //
2275            // which creates an IR snippet like
2276            //
2277            //      cs_terminate:
2278            //         %cs = catchswitch within none [%cp_terminate] unwind to caller
2279            //      cp_terminate:
2280            //         %cp = catchpad within %cs [null, i32 64, null]
2281            //         ...
2282            //
2283            // By contrast, on WebAssembly targets, we specifically _do_ want to
2284            // catch foreign exceptions. The situation with MSVC is a
2285            // regrettable hack which we don't want to extend to other targets
2286            // unless necessary. For WebAssembly, to generate catch(...) and
2287            // catch only C++ exception instead of generating a catch_all, we
2288            // need to call the intrinsics @llvm.wasm.get.exception and
2289            // @llvm.wasm.get.ehselector in the catch pad. Since we don't do
2290            // this, we generate a catch_all. We originally got this behavior
2291            // by accident but it luckily matches our intention.
2292
2293            llbb = Bx::append_block(self.cx, self.llfn, "cs_terminate");
2294
2295            let mut cs_bx = Bx::build(self.cx, llbb);
2296
2297            // For wasm InCleanup blocks, our catch_switch is nested within the
2298            // outer catchpad, so we need to provide it as the parent value to
2299            // catch_switch.
2300            let mut outer_cleanuppad = None;
2301            if outer_catchpad_bb.is_some() {
2302                // Get the outer funclet's catchpad
2303                let outer_funclet = self.funclets[cache_bb]
2304                    .as_ref()
2305                    .expect("landing_pad_for didn't create funclet");
2306                outer_cleanuppad = Some(cs_bx.get_funclet_cleanuppad(outer_funclet));
2307            }
2308            let cp_llbb = Bx::append_block(self.cx, self.llfn, "cp_terminate");
2309            let cs = cs_bx.catch_switch(outer_cleanuppad, None, &[cp_llbb]);
2310            drop(cs_bx);
2311
2312            bx = Bx::build(self.cx, cp_llbb);
2313            let null =
2314                bx.const_null(bx.type_ptr_ext(bx.cx().data_layout().instruction_address_space));
2315
2316            // The `null` in first argument here is actually a RTTI type
2317            // descriptor for the C++ personality function, but `catch (...)`
2318            // has no type so it's null.
2319            let args = if base::wants_msvc_seh(self.cx.sess()) {
2320                // This bitmask is a single `HT_IsStdDotDot` flag, which
2321                // represents that this is a C++-style `catch (...)` block that
2322                // only captures programmatic exceptions, not all SEH
2323                // exceptions. The second `null` points to a non-existent
2324                // `alloca` instruction, which an LLVM pass would inline into
2325                // the initial SEH frame allocation.
2326                let adjectives = bx.const_i32(0x40);
2327                &[null, adjectives, null] as &[_]
2328            } else {
2329                // Specifying more arguments than necessary usually doesn't
2330                // hurt, but the `WasmEHPrepare` LLVM pass does not recognize
2331                // anything other than a single `null` as a `catch_all` block,
2332                // leading to problems down the line during instruction
2333                // selection.
2334                &[null] as &[_]
2335            };
2336
2337            funclet = Some(bx.catch_pad(cs, args));
2338            // On wasm, if we wanted to generate a catch(...) and only catch C++
2339            // exceptions, we'd call @llvm.wasm.get.exception and
2340            // @llvm.wasm.get.ehselector selectors here. We want a catch_all so
2341            // we leave them out. This is intentionally diverging from the MSVC
2342            // behavior.
2343        } else {
2344            llbb = Bx::append_block(self.cx, self.llfn, "terminate");
2345            bx = Bx::build(self.cx, llbb);
2346
2347            let llpersonality = self.cx.eh_personality();
2348            bx.filter_landing_pad(llpersonality);
2349
2350            funclet = None;
2351        }
2352
2353        self.set_debug_loc(&mut bx, mir::SourceInfo::outermost(self.mir.span));
2354
2355        let (fn_abi, fn_ptr, instance) =
2356            common::build_langcall(&bx, self.mir.span, reason.lang_item());
2357        if is_call_from_compiler_builtins_to_upstream_monomorphization(bx.tcx(), instance) {
2358            bx.abort();
2359        } else {
2360            let fn_ty = bx.fn_decl_backend_type(fn_abi);
2361
2362            let llret = bx.call(fn_ty, None, Some(fn_abi), fn_ptr, &[], funclet.as_ref(), None);
2363            bx.apply_attrs_to_cleanup_callsite(llret);
2364        }
2365
2366        bx.unreachable();
2367
2368        self.terminate_blocks[cache_bb] = Some((llbb, reason));
2369        llbb
2370    }
2371
2372    /// Get the backend `BasicBlock` for a MIR `BasicBlock`, either already
2373    /// cached in `self.cached_llbbs`, or created on demand (and cached).
2374    // FIXME(eddyb) rename `llbb` and other `ll`-prefixed things to use a
2375    // more backend-agnostic prefix such as `cg` (i.e. this would be `cgbb`).
2376    pub fn llbb(&mut self, bb: mir::BasicBlock) -> Bx::BasicBlock {
2377        self.try_llbb(bb).unwrap()
2378    }
2379
2380    /// Like `llbb`, but may fail if the basic block should be skipped.
2381    pub(crate) fn try_llbb(&mut self, bb: mir::BasicBlock) -> Option<Bx::BasicBlock> {
2382        match self.cached_llbbs[bb] {
2383            CachedLlbb::None => {
2384                let llbb = Bx::append_block(self.cx, self.llfn, &::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0:?}", bb))
    })format!("{bb:?}"));
2385                self.cached_llbbs[bb] = CachedLlbb::Some(llbb);
2386                Some(llbb)
2387            }
2388            CachedLlbb::Some(llbb) => Some(llbb),
2389            CachedLlbb::Skip => None,
2390        }
2391    }
2392
2393    fn make_return_dest(
2394        &mut self,
2395        bx: &mut Bx,
2396        dest: mir::Place<'tcx>,
2397        fn_ret: &ArgAbi<'tcx, Ty<'tcx>>,
2398        llargs: &mut Vec<Bx::Value>,
2399    ) -> ReturnDest<'tcx, Bx::Value> {
2400        // If the return is ignored, we can just return a do-nothing `ReturnDest`.
2401        if fn_ret.is_ignore() {
2402            return ReturnDest::Nothing;
2403        }
2404        let dest = if let Some(index) = dest.as_local() {
2405            match self.locals[index] {
2406                LocalRef::Place(dest) => dest,
2407                LocalRef::UnsizedPlace(_) => ::rustc_middle::util::bug::bug_fmt(format_args!("return type must be sized"))bug!("return type must be sized"),
2408                LocalRef::PendingOperand => {
2409                    // Handle temporary places, specifically `Operand` ones, as
2410                    // they don't have `alloca`s.
2411                    return if fn_ret.is_indirect() {
2412                        // Odd, but possible, case, we have an operand temporary,
2413                        // but the calling convention has an indirect return.
2414                        let tmp = PlaceRef::alloca(bx, fn_ret.layout);
2415                        tmp.storage_live(bx);
2416                        llargs.push(tmp.val.llval);
2417                        ReturnDest::IndirectOperand(tmp, index)
2418                    } else {
2419                        ReturnDest::DirectOperand(index)
2420                    };
2421                }
2422                LocalRef::Operand(_) => {
2423                    ::rustc_middle::util::bug::bug_fmt(format_args!("place local already assigned to"));bug!("place local already assigned to");
2424                }
2425            }
2426        } else {
2427            self.codegen_place(bx, dest.as_ref())
2428        };
2429        if fn_ret.is_indirect() {
2430            if dest.val.align < dest.layout.align.abi {
2431                // Currently, MIR code generation does not create calls
2432                // that store directly to fields of packed structs (in
2433                // fact, the calls it creates write only to temps).
2434                //
2435                // If someone changes that, please update this code path
2436                // to create a temporary.
2437                ::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");
2438            }
2439            llargs.push(dest.val.llval);
2440            ReturnDest::Nothing
2441        } else {
2442            ReturnDest::Store(dest)
2443        }
2444    }
2445
2446    // Stores the return value of a function call into it's final location.
2447    fn store_return(
2448        &mut self,
2449        bx: &mut Bx,
2450        dest: ReturnDest<'tcx, Bx::Value>,
2451        ret_abi: &ArgAbi<'tcx, Ty<'tcx>>,
2452        llval: Bx::Value,
2453    ) {
2454        use self::ReturnDest::*;
2455        let retags_enabled = bx.tcx().sess.opts.unstable_opts.codegen_emit_retag.is_some();
2456        match dest {
2457            Nothing => (),
2458            Store(dst) => {
2459                bx.store_arg(ret_abi, llval, dst);
2460                if retags_enabled {
2461                    self.codegen_retag_place(bx, dst, false);
2462                }
2463            }
2464            IndirectOperand(tmp, index) => {
2465                let mut op = bx.load_operand(tmp);
2466                tmp.storage_dead(bx);
2467                if retags_enabled {
2468                    op = self.codegen_retag_operand(bx, op, false);
2469                }
2470                self.overwrite_local(index, LocalRef::Operand(op));
2471                self.debug_introduce_local(bx, index);
2472            }
2473            DirectOperand(index) => {
2474                // If there is a cast, we have to store and reload.
2475                let mut op = if let PassMode::Cast { .. } = ret_abi.mode {
2476                    let tmp = PlaceRef::alloca(bx, ret_abi.layout);
2477                    tmp.storage_live(bx);
2478                    bx.store_arg(ret_abi, llval, tmp);
2479                    let op = bx.load_operand(tmp);
2480                    tmp.storage_dead(bx);
2481                    op
2482                } else {
2483                    OperandRef::from_immediate_or_packed_pair(bx, llval, ret_abi.layout)
2484                };
2485                if retags_enabled {
2486                    op = self.codegen_retag_operand(bx, op, false);
2487                }
2488                self.overwrite_local(index, LocalRef::Operand(op));
2489                self.debug_introduce_local(bx, index);
2490            }
2491        }
2492    }
2493}
2494
2495enum ReturnDest<'tcx, V> {
2496    /// Do nothing; the return value is indirect or ignored.
2497    Nothing,
2498    /// Store the return value to the pointer.
2499    Store(PlaceRef<'tcx, V>),
2500    /// Store an indirect return value to an operand local place.
2501    IndirectOperand(PlaceRef<'tcx, V>, mir::Local),
2502    /// Store a direct return value to an operand local place.
2503    DirectOperand(mir::Local),
2504}
2505
2506fn load_cast<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
2507    bx: &mut Bx,
2508    cast: &CastTarget,
2509    ptr: Bx::Value,
2510    align: Align,
2511) -> Bx::Value {
2512    let cast_ty = bx.cast_backend_type(cast);
2513    if let Some(offset_from_start) = cast.rest_offset {
2514        {
    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);
2515        {
    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);
2516        let first_ty = bx.reg_backend_type(&cast.prefix[0]);
2517        let second_ty = bx.reg_backend_type(&cast.rest.unit);
2518        let first = bx.load(first_ty, ptr, align);
2519        let second_ptr = bx.inbounds_ptradd(ptr, bx.const_usize(offset_from_start.bytes()));
2520        let second = bx.load(second_ty, second_ptr, align.restrict_for_offset(offset_from_start));
2521        let res = bx.cx().const_poison(cast_ty);
2522        let res = bx.insert_value(res, first, 0);
2523        bx.insert_value(res, second, 1)
2524    } else {
2525        bx.load(cast_ty, ptr, align)
2526    }
2527}
2528
2529pub fn store_cast<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
2530    bx: &mut Bx,
2531    cast: &CastTarget,
2532    value: Bx::Value,
2533    ptr: Bx::Value,
2534    align: Align,
2535) {
2536    if let Some(offset_from_start) = cast.rest_offset {
2537        {
    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);
2538        {
    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);
2539        let first = bx.extract_value(value, 0);
2540        let second = bx.extract_value(value, 1);
2541        bx.store(first, ptr, align);
2542        let second_ptr = bx.inbounds_ptradd(ptr, bx.const_usize(offset_from_start.bytes()));
2543        bx.store(second, second_ptr, align.restrict_for_offset(offset_from_start));
2544    } else {
2545        bx.store(value, ptr, align);
2546    };
2547}