Skip to main content

rustc_codegen_ssa/mir/
block.rs

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