rustc_codegen_ssa/mir/
block.rs

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