Skip to main content

rustc_codegen_ssa/mir/
block.rs

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