]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_codegen_ssa/src/mir/block.rs
e7abae665e357b3712effd43fd94bd7394c9d78a
[rust.git] / compiler / rustc_codegen_ssa / src / mir / block.rs
1 use super::operand::OperandRef;
2 use super::operand::OperandValue::{Immediate, Pair, Ref};
3 use super::place::PlaceRef;
4 use super::{FunctionCx, LocalRef};
5
6 use crate::base;
7 use crate::common::{self, IntPredicate};
8 use crate::meth;
9 use crate::traits::*;
10 use crate::MemFlags;
11
12 use rustc_ast as ast;
13 use rustc_ast::{InlineAsmOptions, InlineAsmTemplatePiece};
14 use rustc_hir::lang_items::LangItem;
15 use rustc_index::vec::Idx;
16 use rustc_middle::mir::{self, AssertKind, SwitchTargets};
17 use rustc_middle::ty::layout::{HasTyCtxt, LayoutOf};
18 use rustc_middle::ty::print::{with_no_trimmed_paths, with_no_visible_paths};
19 use rustc_middle::ty::{self, Instance, Ty, TypeVisitable};
20 use rustc_span::source_map::Span;
21 use rustc_span::{sym, Symbol};
22 use rustc_symbol_mangling::typeid::typeid_for_fnabi;
23 use rustc_target::abi::call::{ArgAbi, FnAbi, PassMode, Reg};
24 use rustc_target::abi::{self, HasDataLayout, WrappingRange};
25 use rustc_target::spec::abi::Abi;
26
27 /// Used by `FunctionCx::codegen_terminator` for emitting common patterns
28 /// e.g., creating a basic block, calling a function, etc.
29 struct TerminatorCodegenHelper<'tcx> {
30     bb: mir::BasicBlock,
31     terminator: &'tcx mir::Terminator<'tcx>,
32     funclet_bb: Option<mir::BasicBlock>,
33 }
34
35 impl<'a, 'tcx> TerminatorCodegenHelper<'tcx> {
36     /// Returns the appropriate `Funclet` for the current funclet, if on MSVC,
37     /// either already previously cached, or newly created, by `landing_pad_for`.
38     fn funclet<'b, Bx: BuilderMethods<'a, 'tcx>>(
39         &self,
40         fx: &'b mut FunctionCx<'a, 'tcx, Bx>,
41     ) -> Option<&'b Bx::Funclet> {
42         let funclet_bb = self.funclet_bb?;
43         if base::wants_msvc_seh(fx.cx.tcx().sess) {
44             // If `landing_pad_for` hasn't been called yet to create the `Funclet`,
45             // it has to be now. This may not seem necessary, as RPO should lead
46             // to all the unwind edges being visited (and so to `landing_pad_for`
47             // getting called for them), before building any of the blocks inside
48             // the funclet itself - however, if MIR contains edges that end up not
49             // being needed in the LLVM IR after monomorphization, the funclet may
50             // be unreachable, and we don't have yet a way to skip building it in
51             // such an eventuality (which may be a better solution than this).
52             if fx.funclets[funclet_bb].is_none() {
53                 fx.landing_pad_for(funclet_bb);
54             }
55
56             Some(
57                 fx.funclets[funclet_bb]
58                     .as_ref()
59                     .expect("landing_pad_for didn't also create funclets entry"),
60             )
61         } else {
62             None
63         }
64     }
65
66     fn lltarget<Bx: BuilderMethods<'a, 'tcx>>(
67         &self,
68         fx: &mut FunctionCx<'a, 'tcx, Bx>,
69         target: mir::BasicBlock,
70     ) -> (Bx::BasicBlock, bool) {
71         let span = self.terminator.source_info.span;
72         let lltarget = fx.llbb(target);
73         let target_funclet = fx.cleanup_kinds[target].funclet_bb(target);
74         match (self.funclet_bb, target_funclet) {
75             (None, None) => (lltarget, false),
76             (Some(f), Some(t_f)) if f == t_f || !base::wants_msvc_seh(fx.cx.tcx().sess) => {
77                 (lltarget, false)
78             }
79             // jump *into* cleanup - need a landing pad if GNU, cleanup pad if MSVC
80             (None, Some(_)) => (fx.landing_pad_for(target), false),
81             (Some(_), None) => span_bug!(span, "{:?} - jump out of cleanup?", self.terminator),
82             (Some(_), Some(_)) => (fx.landing_pad_for(target), true),
83         }
84     }
85
86     /// Create a basic block.
87     fn llblock<Bx: BuilderMethods<'a, 'tcx>>(
88         &self,
89         fx: &mut FunctionCx<'a, 'tcx, Bx>,
90         target: mir::BasicBlock,
91     ) -> Bx::BasicBlock {
92         let (lltarget, is_cleanupret) = self.lltarget(fx, target);
93         if is_cleanupret {
94             // MSVC cross-funclet jump - need a trampoline
95
96             debug!("llblock: creating cleanup trampoline for {:?}", target);
97             let name = &format!("{:?}_cleanup_trampoline_{:?}", self.bb, target);
98             let trampoline_llbb = Bx::append_block(fx.cx, fx.llfn, name);
99             let mut trampoline_bx = Bx::build(fx.cx, trampoline_llbb);
100             trampoline_bx.cleanup_ret(self.funclet(fx).unwrap(), Some(lltarget));
101             trampoline_llbb
102         } else {
103             lltarget
104         }
105     }
106
107     fn funclet_br<Bx: BuilderMethods<'a, 'tcx>>(
108         &self,
109         fx: &mut FunctionCx<'a, 'tcx, Bx>,
110         bx: &mut Bx,
111         target: mir::BasicBlock,
112     ) {
113         let (lltarget, is_cleanupret) = self.lltarget(fx, target);
114         if is_cleanupret {
115             // micro-optimization: generate a `ret` rather than a jump
116             // to a trampoline.
117             bx.cleanup_ret(self.funclet(fx).unwrap(), Some(lltarget));
118         } else {
119             bx.br(lltarget);
120         }
121     }
122
123     /// Call `fn_ptr` of `fn_abi` with the arguments `llargs`, the optional
124     /// return destination `destination` and the cleanup function `cleanup`.
125     fn do_call<Bx: BuilderMethods<'a, 'tcx>>(
126         &self,
127         fx: &mut FunctionCx<'a, 'tcx, Bx>,
128         bx: &mut Bx,
129         fn_abi: &'tcx FnAbi<'tcx, Ty<'tcx>>,
130         fn_ptr: Bx::Value,
131         llargs: &[Bx::Value],
132         destination: Option<(ReturnDest<'tcx, Bx::Value>, mir::BasicBlock)>,
133         cleanup: Option<mir::BasicBlock>,
134         copied_constant_arguments: &[PlaceRef<'tcx, <Bx as BackendTypes>::Value>],
135     ) {
136         // If there is a cleanup block and the function we're calling can unwind, then
137         // do an invoke, otherwise do a call.
138         let fn_ty = bx.fn_decl_backend_type(&fn_abi);
139
140         let unwind_block = if let Some(cleanup) = cleanup.filter(|_| fn_abi.can_unwind) {
141             Some(self.llblock(fx, cleanup))
142         } else if fx.mir[self.bb].is_cleanup
143             && fn_abi.can_unwind
144             && !base::wants_msvc_seh(fx.cx.tcx().sess)
145         {
146             // Exception must not propagate out of the execution of a cleanup (doing so
147             // can cause undefined behaviour). We insert a double unwind guard for
148             // functions that can potentially unwind to protect against this.
149             //
150             // This is not necessary for SEH which does not use successive unwinding
151             // like Itanium EH. EH frames in SEH are different from normal function
152             // frames and SEH will abort automatically if an exception tries to
153             // propagate out from cleanup.
154             Some(fx.double_unwind_guard())
155         } else {
156             None
157         };
158
159         if let Some(unwind_block) = unwind_block {
160             let ret_llbb = if let Some((_, target)) = destination {
161                 fx.llbb(target)
162             } else {
163                 fx.unreachable_block()
164             };
165             let invokeret = bx.invoke(
166                 fn_ty,
167                 Some(&fn_abi),
168                 fn_ptr,
169                 &llargs,
170                 ret_llbb,
171                 unwind_block,
172                 self.funclet(fx),
173             );
174             if fx.mir[self.bb].is_cleanup {
175                 bx.do_not_inline(invokeret);
176             }
177
178             if let Some((ret_dest, target)) = destination {
179                 bx.switch_to_block(fx.llbb(target));
180                 fx.set_debug_loc(bx, self.terminator.source_info);
181                 for tmp in copied_constant_arguments {
182                     bx.lifetime_end(tmp.llval, tmp.layout.size);
183                 }
184                 fx.store_return(bx, ret_dest, &fn_abi.ret, invokeret);
185             }
186         } else {
187             let llret = bx.call(fn_ty, Some(&fn_abi), fn_ptr, &llargs, self.funclet(fx));
188             if fx.mir[self.bb].is_cleanup {
189                 // Cleanup is always the cold path. Don't inline
190                 // drop glue. Also, when there is a deeply-nested
191                 // struct, there are "symmetry" issues that cause
192                 // exponential inlining - see issue #41696.
193                 bx.do_not_inline(llret);
194             }
195
196             if let Some((ret_dest, target)) = destination {
197                 for tmp in copied_constant_arguments {
198                     bx.lifetime_end(tmp.llval, tmp.layout.size);
199                 }
200                 fx.store_return(bx, ret_dest, &fn_abi.ret, llret);
201                 self.funclet_br(fx, bx, target);
202             } else {
203                 bx.unreachable();
204             }
205         }
206     }
207
208     /// Generates inline assembly with optional `destination` and `cleanup`.
209     fn do_inlineasm<Bx: BuilderMethods<'a, 'tcx>>(
210         &self,
211         fx: &mut FunctionCx<'a, 'tcx, Bx>,
212         bx: &mut Bx,
213         template: &[InlineAsmTemplatePiece],
214         operands: &[InlineAsmOperandRef<'tcx, Bx>],
215         options: InlineAsmOptions,
216         line_spans: &[Span],
217         destination: Option<mir::BasicBlock>,
218         cleanup: Option<mir::BasicBlock>,
219         instance: Instance<'_>,
220     ) {
221         if let Some(cleanup) = cleanup {
222             let ret_llbb = if let Some(target) = destination {
223                 fx.llbb(target)
224             } else {
225                 fx.unreachable_block()
226             };
227
228             bx.codegen_inline_asm(
229                 template,
230                 &operands,
231                 options,
232                 line_spans,
233                 instance,
234                 Some((ret_llbb, self.llblock(fx, cleanup), self.funclet(fx))),
235             );
236         } else {
237             bx.codegen_inline_asm(template, &operands, options, line_spans, instance, None);
238
239             if let Some(target) = destination {
240                 self.funclet_br(fx, bx, target);
241             } else {
242                 bx.unreachable();
243             }
244         }
245     }
246 }
247
248 /// Codegen implementations for some terminator variants.
249 impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
250     /// Generates code for a `Resume` terminator.
251     fn codegen_resume_terminator(&mut self, helper: TerminatorCodegenHelper<'tcx>, mut bx: Bx) {
252         if let Some(funclet) = helper.funclet(self) {
253             bx.cleanup_ret(funclet, None);
254         } else {
255             let slot = self.get_personality_slot(&mut bx);
256             let lp0 = slot.project_field(&mut bx, 0);
257             let lp0 = bx.load_operand(lp0).immediate();
258             let lp1 = slot.project_field(&mut bx, 1);
259             let lp1 = bx.load_operand(lp1).immediate();
260             slot.storage_dead(&mut bx);
261
262             let mut lp = bx.const_undef(self.landing_pad_type());
263             lp = bx.insert_value(lp, lp0, 0);
264             lp = bx.insert_value(lp, lp1, 1);
265             bx.resume(lp);
266         }
267     }
268
269     fn codegen_switchint_terminator(
270         &mut self,
271         helper: TerminatorCodegenHelper<'tcx>,
272         mut bx: Bx,
273         discr: &mir::Operand<'tcx>,
274         switch_ty: Ty<'tcx>,
275         targets: &SwitchTargets,
276     ) {
277         let discr = self.codegen_operand(&mut bx, &discr);
278         // `switch_ty` is redundant, sanity-check that.
279         assert_eq!(discr.layout.ty, switch_ty);
280         let mut target_iter = targets.iter();
281         if target_iter.len() == 1 {
282             // If there are two targets (one conditional, one fallback), emit br instead of switch
283             let (test_value, target) = target_iter.next().unwrap();
284             let lltrue = helper.llblock(self, target);
285             let llfalse = helper.llblock(self, targets.otherwise());
286             if switch_ty == bx.tcx().types.bool {
287                 // Don't generate trivial icmps when switching on bool
288                 match test_value {
289                     0 => bx.cond_br(discr.immediate(), llfalse, lltrue),
290                     1 => bx.cond_br(discr.immediate(), lltrue, llfalse),
291                     _ => bug!(),
292                 }
293             } else {
294                 let switch_llty = bx.immediate_backend_type(bx.layout_of(switch_ty));
295                 let llval = bx.const_uint_big(switch_llty, test_value);
296                 let cmp = bx.icmp(IntPredicate::IntEQ, discr.immediate(), llval);
297                 bx.cond_br(cmp, lltrue, llfalse);
298             }
299         } else {
300             bx.switch(
301                 discr.immediate(),
302                 helper.llblock(self, targets.otherwise()),
303                 target_iter.map(|(value, target)| (value, helper.llblock(self, target))),
304             );
305         }
306     }
307
308     fn codegen_return_terminator(&mut self, mut bx: Bx) {
309         // Call `va_end` if this is the definition of a C-variadic function.
310         if self.fn_abi.c_variadic {
311             // The `VaList` "spoofed" argument is just after all the real arguments.
312             let va_list_arg_idx = self.fn_abi.args.len();
313             match self.locals[mir::Local::new(1 + va_list_arg_idx)] {
314                 LocalRef::Place(va_list) => {
315                     bx.va_end(va_list.llval);
316                 }
317                 _ => bug!("C-variadic function must have a `VaList` place"),
318             }
319         }
320         if self.fn_abi.ret.layout.abi.is_uninhabited() {
321             // Functions with uninhabited return values are marked `noreturn`,
322             // so we should make sure that we never actually do.
323             // We play it safe by using a well-defined `abort`, but we could go for immediate UB
324             // if that turns out to be helpful.
325             bx.abort();
326             // `abort` does not terminate the block, so we still need to generate
327             // an `unreachable` terminator after it.
328             bx.unreachable();
329             return;
330         }
331         let llval = match &self.fn_abi.ret.mode {
332             PassMode::Ignore | PassMode::Indirect { .. } => {
333                 bx.ret_void();
334                 return;
335             }
336
337             PassMode::Direct(_) | PassMode::Pair(..) => {
338                 let op = self.codegen_consume(&mut bx, mir::Place::return_place().as_ref());
339                 if let Ref(llval, _, align) = op.val {
340                     bx.load(bx.backend_type(op.layout), llval, align)
341                 } else {
342                     op.immediate_or_packed_pair(&mut bx)
343                 }
344             }
345
346             PassMode::Cast(cast_ty, _) => {
347                 let op = match self.locals[mir::RETURN_PLACE] {
348                     LocalRef::Operand(Some(op)) => op,
349                     LocalRef::Operand(None) => bug!("use of return before def"),
350                     LocalRef::Place(cg_place) => OperandRef {
351                         val: Ref(cg_place.llval, None, cg_place.align),
352                         layout: cg_place.layout,
353                     },
354                     LocalRef::UnsizedPlace(_) => bug!("return type must be sized"),
355                 };
356                 let llslot = match op.val {
357                     Immediate(_) | Pair(..) => {
358                         let scratch = PlaceRef::alloca(&mut bx, self.fn_abi.ret.layout);
359                         op.val.store(&mut bx, scratch);
360                         scratch.llval
361                     }
362                     Ref(llval, _, align) => {
363                         assert_eq!(align, op.layout.align.abi, "return place is unaligned!");
364                         llval
365                     }
366                 };
367                 let ty = bx.cast_backend_type(cast_ty);
368                 let addr = bx.pointercast(llslot, bx.type_ptr_to(ty));
369                 bx.load(ty, addr, self.fn_abi.ret.layout.align.abi)
370             }
371         };
372         bx.ret(llval);
373     }
374
375     #[tracing::instrument(level = "trace", skip(self, helper, bx))]
376     fn codegen_drop_terminator(
377         &mut self,
378         helper: TerminatorCodegenHelper<'tcx>,
379         mut bx: Bx,
380         location: mir::Place<'tcx>,
381         target: mir::BasicBlock,
382         unwind: Option<mir::BasicBlock>,
383     ) {
384         let ty = location.ty(self.mir, bx.tcx()).ty;
385         let ty = self.monomorphize(ty);
386         let drop_fn = Instance::resolve_drop_in_place(bx.tcx(), ty);
387
388         if let ty::InstanceDef::DropGlue(_, None) = drop_fn.def {
389             // we don't actually need to drop anything.
390             helper.funclet_br(self, &mut bx, target);
391             return;
392         }
393
394         let place = self.codegen_place(&mut bx, location.as_ref());
395         let (args1, args2);
396         let mut args = if let Some(llextra) = place.llextra {
397             args2 = [place.llval, llextra];
398             &args2[..]
399         } else {
400             args1 = [place.llval];
401             &args1[..]
402         };
403         let (drop_fn, fn_abi) = match ty.kind() {
404             // FIXME(eddyb) perhaps move some of this logic into
405             // `Instance::resolve_drop_in_place`?
406             ty::Dynamic(_, _, ty::Dyn) => {
407                 // IN THIS ARM, WE HAVE:
408                 // ty = *mut (dyn Trait)
409                 // which is: exists<T> ( *mut T,    Vtable<T: Trait> )
410                 //                       args[0]    args[1]
411                 //
412                 // args = ( Data, Vtable )
413                 //                  |
414                 //                  v
415                 //                /-------\
416                 //                | ...   |
417                 //                \-------/
418                 //
419                 let virtual_drop = Instance {
420                     def: ty::InstanceDef::Virtual(drop_fn.def_id(), 0),
421                     substs: drop_fn.substs,
422                 };
423                 debug!("ty = {:?}", ty);
424                 debug!("drop_fn = {:?}", drop_fn);
425                 debug!("args = {:?}", args);
426                 let fn_abi = bx.fn_abi_of_instance(virtual_drop, ty::List::empty());
427                 let vtable = args[1];
428                 // Truncate vtable off of args list
429                 args = &args[..1];
430                 (
431                     meth::VirtualIndex::from_index(ty::COMMON_VTABLE_ENTRIES_DROPINPLACE)
432                         .get_fn(&mut bx, vtable, ty, &fn_abi),
433                     fn_abi,
434                 )
435             }
436             ty::Dynamic(_, _, ty::DynStar) => {
437                 // IN THIS ARM, WE HAVE:
438                 // ty = *mut (dyn* Trait)
439                 // which is: *mut exists<T: sizeof(T) == sizeof(usize)> (T, Vtable<T: Trait>)
440                 //
441                 // args = [ * ]
442                 //          |
443                 //          v
444                 //      ( Data, Vtable )
445                 //                |
446                 //                v
447                 //              /-------\
448                 //              | ...   |
449                 //              \-------/
450                 //
451                 //
452                 // WE CAN CONVERT THIS INTO THE ABOVE LOGIC BY DOING
453                 //
454                 // data = &(*args[0]).0    // gives a pointer to Data above (really the same pointer)
455                 // vtable = (*args[0]).1   // loads the vtable out
456                 // (data, vtable)          // an equivalent Rust `*mut dyn Trait`
457                 //
458                 // SO THEN WE CAN USE THE ABOVE CODE.
459                 let virtual_drop = Instance {
460                     def: ty::InstanceDef::Virtual(drop_fn.def_id(), 0),
461                     substs: drop_fn.substs,
462                 };
463                 debug!("ty = {:?}", ty);
464                 debug!("drop_fn = {:?}", drop_fn);
465                 debug!("args = {:?}", args);
466                 let fn_abi = bx.fn_abi_of_instance(virtual_drop, ty::List::empty());
467                 let data = args[0];
468                 let data_ty = bx.cx().backend_type(place.layout);
469                 let vtable_ptr =
470                     bx.gep(data_ty, data, &[bx.cx().const_i32(0), bx.cx().const_i32(1)]);
471                 let vtable = bx.load(bx.type_i8p(), vtable_ptr, abi::Align::ONE);
472                 // Truncate vtable off of args list
473                 args = &args[..1];
474                 debug!("args' = {:?}", args);
475                 (
476                     meth::VirtualIndex::from_index(ty::COMMON_VTABLE_ENTRIES_DROPINPLACE)
477                         .get_fn(&mut bx, vtable, ty, &fn_abi),
478                     fn_abi,
479                 )
480             }
481             _ => (bx.get_fn_addr(drop_fn), bx.fn_abi_of_instance(drop_fn, ty::List::empty())),
482         };
483         helper.do_call(
484             self,
485             &mut bx,
486             fn_abi,
487             drop_fn,
488             args,
489             Some((ReturnDest::Nothing, target)),
490             unwind,
491             &[],
492         );
493     }
494
495     fn codegen_assert_terminator(
496         &mut self,
497         helper: TerminatorCodegenHelper<'tcx>,
498         mut bx: Bx,
499         terminator: &mir::Terminator<'tcx>,
500         cond: &mir::Operand<'tcx>,
501         expected: bool,
502         msg: &mir::AssertMessage<'tcx>,
503         target: mir::BasicBlock,
504         cleanup: Option<mir::BasicBlock>,
505     ) {
506         let span = terminator.source_info.span;
507         let cond = self.codegen_operand(&mut bx, cond).immediate();
508         let mut const_cond = bx.const_to_opt_u128(cond, false).map(|c| c == 1);
509
510         // This case can currently arise only from functions marked
511         // with #[rustc_inherit_overflow_checks] and inlined from
512         // another crate (mostly core::num generic/#[inline] fns),
513         // while the current crate doesn't use overflow checks.
514         // NOTE: Unlike binops, negation doesn't have its own
515         // checked operation, just a comparison with the minimum
516         // value, so we have to check for the assert message.
517         if !bx.check_overflow() {
518             if let AssertKind::OverflowNeg(_) = *msg {
519                 const_cond = Some(expected);
520             }
521         }
522
523         // Don't codegen the panic block if success if known.
524         if const_cond == Some(expected) {
525             helper.funclet_br(self, &mut bx, target);
526             return;
527         }
528
529         // Pass the condition through llvm.expect for branch hinting.
530         let cond = bx.expect(cond, expected);
531
532         // Create the failure block and the conditional branch to it.
533         let lltarget = helper.llblock(self, target);
534         let panic_block = bx.append_sibling_block("panic");
535         if expected {
536             bx.cond_br(cond, lltarget, panic_block);
537         } else {
538             bx.cond_br(cond, panic_block, lltarget);
539         }
540
541         // After this point, bx is the block for the call to panic.
542         bx.switch_to_block(panic_block);
543         self.set_debug_loc(&mut bx, terminator.source_info);
544
545         // Get the location information.
546         let location = self.get_caller_location(&mut bx, terminator.source_info).immediate();
547
548         // Put together the arguments to the panic entry point.
549         let (lang_item, args) = match msg {
550             AssertKind::BoundsCheck { ref len, ref index } => {
551                 let len = self.codegen_operand(&mut bx, len).immediate();
552                 let index = self.codegen_operand(&mut bx, index).immediate();
553                 // It's `fn panic_bounds_check(index: usize, len: usize)`,
554                 // and `#[track_caller]` adds an implicit third argument.
555                 (LangItem::PanicBoundsCheck, vec![index, len, location])
556             }
557             _ => {
558                 let msg = bx.const_str(msg.description());
559                 // It's `pub fn panic(expr: &str)`, with the wide reference being passed
560                 // as two arguments, and `#[track_caller]` adds an implicit third argument.
561                 (LangItem::Panic, vec![msg.0, msg.1, location])
562             }
563         };
564
565         let (fn_abi, llfn) = common::build_langcall(&bx, Some(span), lang_item);
566
567         // Codegen the actual panic invoke/call.
568         helper.do_call(self, &mut bx, fn_abi, llfn, &args, None, cleanup, &[]);
569     }
570
571     fn codegen_abort_terminator(
572         &mut self,
573         helper: TerminatorCodegenHelper<'tcx>,
574         mut bx: Bx,
575         terminator: &mir::Terminator<'tcx>,
576     ) {
577         let span = terminator.source_info.span;
578         self.set_debug_loc(&mut bx, terminator.source_info);
579
580         // Obtain the panic entry point.
581         let (fn_abi, llfn) = common::build_langcall(&bx, Some(span), LangItem::PanicNoUnwind);
582
583         // Codegen the actual panic invoke/call.
584         helper.do_call(self, &mut bx, fn_abi, llfn, &[], None, None, &[]);
585     }
586
587     /// Returns `true` if this is indeed a panic intrinsic and codegen is done.
588     fn codegen_panic_intrinsic(
589         &mut self,
590         helper: &TerminatorCodegenHelper<'tcx>,
591         bx: &mut Bx,
592         intrinsic: Option<Symbol>,
593         instance: Option<Instance<'tcx>>,
594         source_info: mir::SourceInfo,
595         target: Option<mir::BasicBlock>,
596         cleanup: Option<mir::BasicBlock>,
597     ) -> bool {
598         // Emit a panic or a no-op for `assert_*` intrinsics.
599         // These are intrinsics that compile to panics so that we can get a message
600         // which mentions the offending type, even from a const context.
601         #[derive(Debug, PartialEq)]
602         enum AssertIntrinsic {
603             Inhabited,
604             ZeroValid,
605             UninitValid,
606         }
607         let panic_intrinsic = intrinsic.and_then(|i| match i {
608             sym::assert_inhabited => Some(AssertIntrinsic::Inhabited),
609             sym::assert_zero_valid => Some(AssertIntrinsic::ZeroValid),
610             sym::assert_uninit_valid => Some(AssertIntrinsic::UninitValid),
611             _ => None,
612         });
613         if let Some(intrinsic) = panic_intrinsic {
614             use AssertIntrinsic::*;
615
616             let ty = instance.unwrap().substs.type_at(0);
617             let layout = bx.layout_of(ty);
618             let do_panic = match intrinsic {
619                 Inhabited => layout.abi.is_uninhabited(),
620                 ZeroValid => !bx.tcx().permits_zero_init(layout),
621                 UninitValid => !bx.tcx().permits_uninit_init(layout),
622             };
623             if do_panic {
624                 let msg_str = with_no_visible_paths!({
625                     with_no_trimmed_paths!({
626                         if layout.abi.is_uninhabited() {
627                             // Use this error even for the other intrinsics as it is more precise.
628                             format!("attempted to instantiate uninhabited type `{}`", ty)
629                         } else if intrinsic == ZeroValid {
630                             format!("attempted to zero-initialize type `{}`, which is invalid", ty)
631                         } else {
632                             format!(
633                                 "attempted to leave type `{}` uninitialized, which is invalid",
634                                 ty
635                             )
636                         }
637                     })
638                 });
639                 let msg = bx.const_str(&msg_str);
640                 let location = self.get_caller_location(bx, source_info).immediate();
641
642                 // Obtain the panic entry point.
643                 let (fn_abi, llfn) =
644                     common::build_langcall(bx, Some(source_info.span), LangItem::Panic);
645
646                 // Codegen the actual panic invoke/call.
647                 helper.do_call(
648                     self,
649                     bx,
650                     fn_abi,
651                     llfn,
652                     &[msg.0, msg.1, location],
653                     target.as_ref().map(|bb| (ReturnDest::Nothing, *bb)),
654                     cleanup,
655                     &[],
656                 );
657             } else {
658                 // a NOP
659                 let target = target.unwrap();
660                 helper.funclet_br(self, bx, target)
661             }
662             true
663         } else {
664             false
665         }
666     }
667
668     fn codegen_call_terminator(
669         &mut self,
670         helper: TerminatorCodegenHelper<'tcx>,
671         mut bx: Bx,
672         terminator: &mir::Terminator<'tcx>,
673         func: &mir::Operand<'tcx>,
674         args: &[mir::Operand<'tcx>],
675         destination: mir::Place<'tcx>,
676         target: Option<mir::BasicBlock>,
677         cleanup: Option<mir::BasicBlock>,
678         fn_span: Span,
679     ) {
680         let source_info = terminator.source_info;
681         let span = source_info.span;
682
683         // Create the callee. This is a fn ptr or zero-sized and hence a kind of scalar.
684         let callee = self.codegen_operand(&mut bx, func);
685
686         let (instance, mut llfn) = match *callee.layout.ty.kind() {
687             ty::FnDef(def_id, substs) => (
688                 Some(
689                     ty::Instance::resolve(bx.tcx(), ty::ParamEnv::reveal_all(), def_id, substs)
690                         .unwrap()
691                         .unwrap()
692                         .polymorphize(bx.tcx()),
693                 ),
694                 None,
695             ),
696             ty::FnPtr(_) => (None, Some(callee.immediate())),
697             _ => bug!("{} is not callable", callee.layout.ty),
698         };
699         let def = instance.map(|i| i.def);
700
701         if let Some(ty::InstanceDef::DropGlue(_, None)) = def {
702             // Empty drop glue; a no-op.
703             let target = target.unwrap();
704             helper.funclet_br(self, &mut bx, target);
705             return;
706         }
707
708         // FIXME(eddyb) avoid computing this if possible, when `instance` is
709         // available - right now `sig` is only needed for getting the `abi`
710         // and figuring out how many extra args were passed to a C-variadic `fn`.
711         let sig = callee.layout.ty.fn_sig(bx.tcx());
712         let abi = sig.abi();
713
714         // Handle intrinsics old codegen wants Expr's for, ourselves.
715         let intrinsic = match def {
716             Some(ty::InstanceDef::Intrinsic(def_id)) => Some(bx.tcx().item_name(def_id)),
717             _ => None,
718         };
719
720         let extra_args = &args[sig.inputs().skip_binder().len()..];
721         let extra_args = bx.tcx().mk_type_list(extra_args.iter().map(|op_arg| {
722             let op_ty = op_arg.ty(self.mir, bx.tcx());
723             self.monomorphize(op_ty)
724         }));
725
726         let fn_abi = match instance {
727             Some(instance) => bx.fn_abi_of_instance(instance, extra_args),
728             None => bx.fn_abi_of_fn_ptr(sig, extra_args),
729         };
730
731         if intrinsic == Some(sym::transmute) {
732             if let Some(target) = target {
733                 self.codegen_transmute(&mut bx, &args[0], destination);
734                 helper.funclet_br(self, &mut bx, target);
735             } else {
736                 // If we are trying to transmute to an uninhabited type,
737                 // it is likely there is no allotted destination. In fact,
738                 // transmuting to an uninhabited type is UB, which means
739                 // we can do what we like. Here, we declare that transmuting
740                 // into an uninhabited type is impossible, so anything following
741                 // it must be unreachable.
742                 assert_eq!(fn_abi.ret.layout.abi, abi::Abi::Uninhabited);
743                 bx.unreachable();
744             }
745             return;
746         }
747
748         if self.codegen_panic_intrinsic(
749             &helper,
750             &mut bx,
751             intrinsic,
752             instance,
753             source_info,
754             target,
755             cleanup,
756         ) {
757             return;
758         }
759
760         // The arguments we'll be passing. Plus one to account for outptr, if used.
761         let arg_count = fn_abi.args.len() + fn_abi.ret.is_indirect() as usize;
762         let mut llargs = Vec::with_capacity(arg_count);
763
764         // Prepare the return value destination
765         let ret_dest = if target.is_some() {
766             let is_intrinsic = intrinsic.is_some();
767             self.make_return_dest(&mut bx, destination, &fn_abi.ret, &mut llargs, is_intrinsic)
768         } else {
769             ReturnDest::Nothing
770         };
771
772         if intrinsic == Some(sym::caller_location) {
773             if let Some(target) = target {
774                 let location = self
775                     .get_caller_location(&mut bx, mir::SourceInfo { span: fn_span, ..source_info });
776
777                 if let ReturnDest::IndirectOperand(tmp, _) = ret_dest {
778                     location.val.store(&mut bx, tmp);
779                 }
780                 self.store_return(&mut bx, ret_dest, &fn_abi.ret, location.immediate());
781                 helper.funclet_br(self, &mut bx, target);
782             }
783             return;
784         }
785
786         match intrinsic {
787             None | Some(sym::drop_in_place) => {}
788             Some(sym::copy_nonoverlapping) => unreachable!(),
789             Some(intrinsic) => {
790                 let dest = match ret_dest {
791                     _ if fn_abi.ret.is_indirect() => llargs[0],
792                     ReturnDest::Nothing => {
793                         bx.const_undef(bx.type_ptr_to(bx.arg_memory_ty(&fn_abi.ret)))
794                     }
795                     ReturnDest::IndirectOperand(dst, _) | ReturnDest::Store(dst) => dst.llval,
796                     ReturnDest::DirectOperand(_) => {
797                         bug!("Cannot use direct operand with an intrinsic call")
798                     }
799                 };
800
801                 let args: Vec<_> = args
802                     .iter()
803                     .enumerate()
804                     .map(|(i, arg)| {
805                         // The indices passed to simd_shuffle* in the
806                         // third argument must be constant. This is
807                         // checked by const-qualification, which also
808                         // promotes any complex rvalues to constants.
809                         if i == 2 && intrinsic.as_str().starts_with("simd_shuffle") {
810                             if let mir::Operand::Constant(constant) = arg {
811                                 let c = self.eval_mir_constant(constant);
812                                 let (llval, ty) = self.simd_shuffle_indices(
813                                     &bx,
814                                     constant.span,
815                                     self.monomorphize(constant.ty()),
816                                     c,
817                                 );
818                                 return OperandRef {
819                                     val: Immediate(llval),
820                                     layout: bx.layout_of(ty),
821                                 };
822                             } else {
823                                 span_bug!(span, "shuffle indices must be constant");
824                             }
825                         }
826
827                         self.codegen_operand(&mut bx, arg)
828                     })
829                     .collect();
830
831                 Self::codegen_intrinsic_call(
832                     &mut bx,
833                     *instance.as_ref().unwrap(),
834                     &fn_abi,
835                     &args,
836                     dest,
837                     span,
838                 );
839
840                 if let ReturnDest::IndirectOperand(dst, _) = ret_dest {
841                     self.store_return(&mut bx, ret_dest, &fn_abi.ret, dst.llval);
842                 }
843
844                 if let Some(target) = target {
845                     helper.funclet_br(self, &mut bx, target);
846                 } else {
847                     bx.unreachable();
848                 }
849
850                 return;
851             }
852         }
853
854         // Split the rust-call tupled arguments off.
855         let (first_args, untuple) = if abi == Abi::RustCall && !args.is_empty() {
856             let (tup, args) = args.split_last().unwrap();
857             (args, Some(tup))
858         } else {
859             (args, None)
860         };
861
862         let mut copied_constant_arguments = vec![];
863         'make_args: for (i, arg) in first_args.iter().enumerate() {
864             let mut op = self.codegen_operand(&mut bx, arg);
865
866             if let (0, Some(ty::InstanceDef::Virtual(_, idx))) = (i, def) {
867                 match op.val {
868                     Pair(data_ptr, meta) => {
869                         // In the case of Rc<Self>, we need to explicitly pass a
870                         // *mut RcBox<Self> with a Scalar (not ScalarPair) ABI. This is a hack
871                         // that is understood elsewhere in the compiler as a method on
872                         // `dyn Trait`.
873                         // To get a `*mut RcBox<Self>`, we just keep unwrapping newtypes until
874                         // we get a value of a built-in pointer type
875                         'descend_newtypes: while !op.layout.ty.is_unsafe_ptr()
876                             && !op.layout.ty.is_region_ptr()
877                         {
878                             for i in 0..op.layout.fields.count() {
879                                 let field = op.extract_field(&mut bx, i);
880                                 if !field.layout.is_zst() {
881                                     // we found the one non-zero-sized field that is allowed
882                                     // now find *its* non-zero-sized field, or stop if it's a
883                                     // pointer
884                                     op = field;
885                                     continue 'descend_newtypes;
886                                 }
887                             }
888
889                             span_bug!(span, "receiver has no non-zero-sized fields {:?}", op);
890                         }
891
892                         // now that we have `*dyn Trait` or `&dyn Trait`, split it up into its
893                         // data pointer and vtable. Look up the method in the vtable, and pass
894                         // the data pointer as the first argument
895                         llfn = Some(meth::VirtualIndex::from_index(idx).get_fn(
896                             &mut bx,
897                             meta,
898                             op.layout.ty,
899                             &fn_abi,
900                         ));
901                         llargs.push(data_ptr);
902                         continue 'make_args;
903                     }
904                     Ref(data_ptr, Some(meta), _) => {
905                         // by-value dynamic dispatch
906                         llfn = Some(meth::VirtualIndex::from_index(idx).get_fn(
907                             &mut bx,
908                             meta,
909                             op.layout.ty,
910                             &fn_abi,
911                         ));
912                         llargs.push(data_ptr);
913                         continue;
914                     }
915                     Immediate(_) => {
916                         let ty::Ref(_, ty, _) = op.layout.ty.kind() else {
917                             span_bug!(span, "can't codegen a virtual call on {:#?}", op);
918                         };
919                         if !ty.is_dyn_star() {
920                             span_bug!(span, "can't codegen a virtual call on {:#?}", op);
921                         }
922                         // FIXME(dyn-star): Make sure this is done on a &dyn* receiver
923                         let place = op.deref(bx.cx());
924                         let data_ptr = place.project_field(&mut bx, 0);
925                         let meta_ptr = place.project_field(&mut bx, 1);
926                         let meta = bx.load_operand(meta_ptr);
927                         llfn = Some(meth::VirtualIndex::from_index(idx).get_fn(
928                             &mut bx,
929                             meta.immediate(),
930                             op.layout.ty,
931                             &fn_abi,
932                         ));
933                         llargs.push(data_ptr.llval);
934                         continue;
935                     }
936                     _ => {
937                         span_bug!(span, "can't codegen a virtual call on {:#?}", op);
938                     }
939                 }
940             }
941
942             // The callee needs to own the argument memory if we pass it
943             // by-ref, so make a local copy of non-immediate constants.
944             match (arg, op.val) {
945                 (&mir::Operand::Copy(_), Ref(_, None, _))
946                 | (&mir::Operand::Constant(_), Ref(_, None, _)) => {
947                     let tmp = PlaceRef::alloca(&mut bx, op.layout);
948                     bx.lifetime_start(tmp.llval, tmp.layout.size);
949                     op.val.store(&mut bx, tmp);
950                     op.val = Ref(tmp.llval, None, tmp.align);
951                     copied_constant_arguments.push(tmp);
952                 }
953                 _ => {}
954             }
955
956             self.codegen_argument(&mut bx, op, &mut llargs, &fn_abi.args[i]);
957         }
958         let num_untupled = untuple.map(|tup| {
959             self.codegen_arguments_untupled(
960                 &mut bx,
961                 tup,
962                 &mut llargs,
963                 &fn_abi.args[first_args.len()..],
964             )
965         });
966
967         let needs_location =
968             instance.map_or(false, |i| i.def.requires_caller_location(self.cx.tcx()));
969         if needs_location {
970             let mir_args = if let Some(num_untupled) = num_untupled {
971                 first_args.len() + num_untupled
972             } else {
973                 args.len()
974             };
975             assert_eq!(
976                 fn_abi.args.len(),
977                 mir_args + 1,
978                 "#[track_caller] fn's must have 1 more argument in their ABI than in their MIR: {:?} {:?} {:?}",
979                 instance,
980                 fn_span,
981                 fn_abi,
982             );
983             let location =
984                 self.get_caller_location(&mut bx, mir::SourceInfo { span: fn_span, ..source_info });
985             debug!(
986                 "codegen_call_terminator({:?}): location={:?} (fn_span {:?})",
987                 terminator, location, fn_span
988             );
989
990             let last_arg = fn_abi.args.last().unwrap();
991             self.codegen_argument(&mut bx, location, &mut llargs, last_arg);
992         }
993
994         let (is_indirect_call, fn_ptr) = match (llfn, instance) {
995             (Some(llfn), _) => (true, llfn),
996             (None, Some(instance)) => (false, bx.get_fn_addr(instance)),
997             _ => span_bug!(span, "no llfn for call"),
998         };
999
1000         // For backends that support CFI using type membership (i.e., testing whether a given
1001         // pointer is associated with a type identifier).
1002         if bx.tcx().sess.is_sanitizer_cfi_enabled() && is_indirect_call {
1003             // Emit type metadata and checks.
1004             // FIXME(rcvalle): Add support for generalized identifiers.
1005             // FIXME(rcvalle): Create distinct unnamed MDNodes for internal identifiers.
1006             let typeid = typeid_for_fnabi(bx.tcx(), fn_abi);
1007             let typeid_metadata = self.cx.typeid_metadata(typeid);
1008
1009             // Test whether the function pointer is associated with the type identifier.
1010             let cond = bx.type_test(fn_ptr, typeid_metadata);
1011             let bb_pass = bx.append_sibling_block("type_test.pass");
1012             let bb_fail = bx.append_sibling_block("type_test.fail");
1013             bx.cond_br(cond, bb_pass, bb_fail);
1014
1015             bx.switch_to_block(bb_pass);
1016             helper.do_call(
1017                 self,
1018                 &mut bx,
1019                 fn_abi,
1020                 fn_ptr,
1021                 &llargs,
1022                 target.as_ref().map(|&target| (ret_dest, target)),
1023                 cleanup,
1024                 &copied_constant_arguments,
1025             );
1026
1027             bx.switch_to_block(bb_fail);
1028             bx.abort();
1029             bx.unreachable();
1030
1031             return;
1032         }
1033
1034         helper.do_call(
1035             self,
1036             &mut bx,
1037             fn_abi,
1038             fn_ptr,
1039             &llargs,
1040             target.as_ref().map(|&target| (ret_dest, target)),
1041             cleanup,
1042             &copied_constant_arguments,
1043         );
1044     }
1045
1046     fn codegen_asm_terminator(
1047         &mut self,
1048         helper: TerminatorCodegenHelper<'tcx>,
1049         mut bx: Bx,
1050         terminator: &mir::Terminator<'tcx>,
1051         template: &[ast::InlineAsmTemplatePiece],
1052         operands: &[mir::InlineAsmOperand<'tcx>],
1053         options: ast::InlineAsmOptions,
1054         line_spans: &[Span],
1055         destination: Option<mir::BasicBlock>,
1056         cleanup: Option<mir::BasicBlock>,
1057         instance: Instance<'_>,
1058     ) {
1059         let span = terminator.source_info.span;
1060
1061         let operands: Vec<_> = operands
1062             .iter()
1063             .map(|op| match *op {
1064                 mir::InlineAsmOperand::In { reg, ref value } => {
1065                     let value = self.codegen_operand(&mut bx, value);
1066                     InlineAsmOperandRef::In { reg, value }
1067                 }
1068                 mir::InlineAsmOperand::Out { reg, late, ref place } => {
1069                     let place = place.map(|place| self.codegen_place(&mut bx, place.as_ref()));
1070                     InlineAsmOperandRef::Out { reg, late, place }
1071                 }
1072                 mir::InlineAsmOperand::InOut { reg, late, ref in_value, ref out_place } => {
1073                     let in_value = self.codegen_operand(&mut bx, in_value);
1074                     let out_place =
1075                         out_place.map(|out_place| self.codegen_place(&mut bx, out_place.as_ref()));
1076                     InlineAsmOperandRef::InOut { reg, late, in_value, out_place }
1077                 }
1078                 mir::InlineAsmOperand::Const { ref value } => {
1079                     let const_value = self
1080                         .eval_mir_constant(value)
1081                         .unwrap_or_else(|_| span_bug!(span, "asm const cannot be resolved"));
1082                     let string = common::asm_const_to_str(
1083                         bx.tcx(),
1084                         span,
1085                         const_value,
1086                         bx.layout_of(value.ty()),
1087                     );
1088                     InlineAsmOperandRef::Const { string }
1089                 }
1090                 mir::InlineAsmOperand::SymFn { ref value } => {
1091                     let literal = self.monomorphize(value.literal);
1092                     if let ty::FnDef(def_id, substs) = *literal.ty().kind() {
1093                         let instance = ty::Instance::resolve_for_fn_ptr(
1094                             bx.tcx(),
1095                             ty::ParamEnv::reveal_all(),
1096                             def_id,
1097                             substs,
1098                         )
1099                         .unwrap();
1100                         InlineAsmOperandRef::SymFn { instance }
1101                     } else {
1102                         span_bug!(span, "invalid type for asm sym (fn)");
1103                     }
1104                 }
1105                 mir::InlineAsmOperand::SymStatic { def_id } => {
1106                     InlineAsmOperandRef::SymStatic { def_id }
1107                 }
1108             })
1109             .collect();
1110
1111         helper.do_inlineasm(
1112             self,
1113             &mut bx,
1114             template,
1115             &operands,
1116             options,
1117             line_spans,
1118             destination,
1119             cleanup,
1120             instance,
1121         );
1122     }
1123 }
1124
1125 impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
1126     pub fn codegen_block(&mut self, bb: mir::BasicBlock) {
1127         let llbb = self.llbb(bb);
1128         let mut bx = Bx::build(self.cx, llbb);
1129         let mir = self.mir;
1130         let data = &mir[bb];
1131
1132         debug!("codegen_block({:?}={:?})", bb, data);
1133
1134         for statement in &data.statements {
1135             bx = self.codegen_statement(bx, statement);
1136         }
1137
1138         self.codegen_terminator(bx, bb, data.terminator());
1139     }
1140
1141     fn codegen_terminator(
1142         &mut self,
1143         mut bx: Bx,
1144         bb: mir::BasicBlock,
1145         terminator: &'tcx mir::Terminator<'tcx>,
1146     ) {
1147         debug!("codegen_terminator: {:?}", terminator);
1148
1149         // Create the cleanup bundle, if needed.
1150         let funclet_bb = self.cleanup_kinds[bb].funclet_bb(bb);
1151         let helper = TerminatorCodegenHelper { bb, terminator, funclet_bb };
1152
1153         self.set_debug_loc(&mut bx, terminator.source_info);
1154         match terminator.kind {
1155             mir::TerminatorKind::Resume => self.codegen_resume_terminator(helper, bx),
1156
1157             mir::TerminatorKind::Abort => {
1158                 self.codegen_abort_terminator(helper, bx, terminator);
1159             }
1160
1161             mir::TerminatorKind::Goto { target } => {
1162                 helper.funclet_br(self, &mut bx, target);
1163             }
1164
1165             mir::TerminatorKind::SwitchInt { ref discr, switch_ty, ref targets } => {
1166                 self.codegen_switchint_terminator(helper, bx, discr, switch_ty, targets);
1167             }
1168
1169             mir::TerminatorKind::Return => {
1170                 self.codegen_return_terminator(bx);
1171             }
1172
1173             mir::TerminatorKind::Unreachable => {
1174                 bx.unreachable();
1175             }
1176
1177             mir::TerminatorKind::Drop { place, target, unwind } => {
1178                 self.codegen_drop_terminator(helper, bx, place, target, unwind);
1179             }
1180
1181             mir::TerminatorKind::Assert { ref cond, expected, ref msg, target, cleanup } => {
1182                 self.codegen_assert_terminator(
1183                     helper, bx, terminator, cond, expected, msg, target, cleanup,
1184                 );
1185             }
1186
1187             mir::TerminatorKind::DropAndReplace { .. } => {
1188                 bug!("undesugared DropAndReplace in codegen: {:?}", terminator);
1189             }
1190
1191             mir::TerminatorKind::Call {
1192                 ref func,
1193                 ref args,
1194                 destination,
1195                 target,
1196                 cleanup,
1197                 from_hir_call: _,
1198                 fn_span,
1199             } => {
1200                 self.codegen_call_terminator(
1201                     helper,
1202                     bx,
1203                     terminator,
1204                     func,
1205                     args,
1206                     destination,
1207                     target,
1208                     cleanup,
1209                     fn_span,
1210                 );
1211             }
1212             mir::TerminatorKind::GeneratorDrop | mir::TerminatorKind::Yield { .. } => {
1213                 bug!("generator ops in codegen")
1214             }
1215             mir::TerminatorKind::FalseEdge { .. } | mir::TerminatorKind::FalseUnwind { .. } => {
1216                 bug!("borrowck false edges in codegen")
1217             }
1218
1219             mir::TerminatorKind::InlineAsm {
1220                 template,
1221                 ref operands,
1222                 options,
1223                 line_spans,
1224                 destination,
1225                 cleanup,
1226             } => {
1227                 self.codegen_asm_terminator(
1228                     helper,
1229                     bx,
1230                     terminator,
1231                     template,
1232                     operands,
1233                     options,
1234                     line_spans,
1235                     destination,
1236                     cleanup,
1237                     self.instance,
1238                 );
1239             }
1240         }
1241     }
1242
1243     fn codegen_argument(
1244         &mut self,
1245         bx: &mut Bx,
1246         op: OperandRef<'tcx, Bx::Value>,
1247         llargs: &mut Vec<Bx::Value>,
1248         arg: &ArgAbi<'tcx, Ty<'tcx>>,
1249     ) {
1250         match arg.mode {
1251             PassMode::Ignore => return,
1252             PassMode::Cast(_, true) => {
1253                 // Fill padding with undef value, where applicable.
1254                 llargs.push(bx.const_undef(bx.reg_backend_type(&Reg::i32())));
1255             }
1256             PassMode::Pair(..) => match op.val {
1257                 Pair(a, b) => {
1258                     llargs.push(a);
1259                     llargs.push(b);
1260                     return;
1261                 }
1262                 _ => bug!("codegen_argument: {:?} invalid for pair argument", op),
1263             },
1264             PassMode::Indirect { attrs: _, extra_attrs: Some(_), on_stack: _ } => match op.val {
1265                 Ref(a, Some(b), _) => {
1266                     llargs.push(a);
1267                     llargs.push(b);
1268                     return;
1269                 }
1270                 _ => bug!("codegen_argument: {:?} invalid for unsized indirect argument", op),
1271             },
1272             _ => {}
1273         }
1274
1275         // Force by-ref if we have to load through a cast pointer.
1276         let (mut llval, align, by_ref) = match op.val {
1277             Immediate(_) | Pair(..) => match arg.mode {
1278                 PassMode::Indirect { .. } | PassMode::Cast(..) => {
1279                     let scratch = PlaceRef::alloca(bx, arg.layout);
1280                     op.val.store(bx, scratch);
1281                     (scratch.llval, scratch.align, true)
1282                 }
1283                 _ => (op.immediate_or_packed_pair(bx), arg.layout.align.abi, false),
1284             },
1285             Ref(llval, _, align) => {
1286                 if arg.is_indirect() && align < arg.layout.align.abi {
1287                     // `foo(packed.large_field)`. We can't pass the (unaligned) field directly. I
1288                     // think that ATM (Rust 1.16) we only pass temporaries, but we shouldn't
1289                     // have scary latent bugs around.
1290
1291                     let scratch = PlaceRef::alloca(bx, arg.layout);
1292                     base::memcpy_ty(
1293                         bx,
1294                         scratch.llval,
1295                         scratch.align,
1296                         llval,
1297                         align,
1298                         op.layout,
1299                         MemFlags::empty(),
1300                     );
1301                     (scratch.llval, scratch.align, true)
1302                 } else {
1303                     (llval, align, true)
1304                 }
1305             }
1306         };
1307
1308         if by_ref && !arg.is_indirect() {
1309             // Have to load the argument, maybe while casting it.
1310             if let PassMode::Cast(ty, _) = &arg.mode {
1311                 let llty = bx.cast_backend_type(ty);
1312                 let addr = bx.pointercast(llval, bx.type_ptr_to(llty));
1313                 llval = bx.load(llty, addr, align.min(arg.layout.align.abi));
1314             } else {
1315                 // We can't use `PlaceRef::load` here because the argument
1316                 // may have a type we don't treat as immediate, but the ABI
1317                 // used for this call is passing it by-value. In that case,
1318                 // the load would just produce `OperandValue::Ref` instead
1319                 // of the `OperandValue::Immediate` we need for the call.
1320                 llval = bx.load(bx.backend_type(arg.layout), llval, align);
1321                 if let abi::Abi::Scalar(scalar) = arg.layout.abi {
1322                     if scalar.is_bool() {
1323                         bx.range_metadata(llval, WrappingRange { start: 0, end: 1 });
1324                     }
1325                 }
1326                 // We store bools as `i8` so we need to truncate to `i1`.
1327                 llval = bx.to_immediate(llval, arg.layout);
1328             }
1329         }
1330
1331         llargs.push(llval);
1332     }
1333
1334     fn codegen_arguments_untupled(
1335         &mut self,
1336         bx: &mut Bx,
1337         operand: &mir::Operand<'tcx>,
1338         llargs: &mut Vec<Bx::Value>,
1339         args: &[ArgAbi<'tcx, Ty<'tcx>>],
1340     ) -> usize {
1341         let tuple = self.codegen_operand(bx, operand);
1342
1343         // Handle both by-ref and immediate tuples.
1344         if let Ref(llval, None, align) = tuple.val {
1345             let tuple_ptr = PlaceRef::new_sized_aligned(llval, tuple.layout, align);
1346             for i in 0..tuple.layout.fields.count() {
1347                 let field_ptr = tuple_ptr.project_field(bx, i);
1348                 let field = bx.load_operand(field_ptr);
1349                 self.codegen_argument(bx, field, llargs, &args[i]);
1350             }
1351         } else if let Ref(_, Some(_), _) = tuple.val {
1352             bug!("closure arguments must be sized")
1353         } else {
1354             // If the tuple is immediate, the elements are as well.
1355             for i in 0..tuple.layout.fields.count() {
1356                 let op = tuple.extract_field(bx, i);
1357                 self.codegen_argument(bx, op, llargs, &args[i]);
1358             }
1359         }
1360         tuple.layout.fields.count()
1361     }
1362
1363     fn get_caller_location(
1364         &mut self,
1365         bx: &mut Bx,
1366         mut source_info: mir::SourceInfo,
1367     ) -> OperandRef<'tcx, Bx::Value> {
1368         let tcx = bx.tcx();
1369
1370         let mut span_to_caller_location = |span: Span| {
1371             let topmost = span.ctxt().outer_expn().expansion_cause().unwrap_or(span);
1372             let caller = tcx.sess.source_map().lookup_char_pos(topmost.lo());
1373             let const_loc = tcx.const_caller_location((
1374                 Symbol::intern(&caller.file.name.prefer_remapped().to_string_lossy()),
1375                 caller.line as u32,
1376                 caller.col_display as u32 + 1,
1377             ));
1378             OperandRef::from_const(bx, const_loc, bx.tcx().caller_location_ty())
1379         };
1380
1381         // Walk up the `SourceScope`s, in case some of them are from MIR inlining.
1382         // If so, the starting `source_info.span` is in the innermost inlined
1383         // function, and will be replaced with outer callsite spans as long
1384         // as the inlined functions were `#[track_caller]`.
1385         loop {
1386             let scope_data = &self.mir.source_scopes[source_info.scope];
1387
1388             if let Some((callee, callsite_span)) = scope_data.inlined {
1389                 // Stop inside the most nested non-`#[track_caller]` function,
1390                 // before ever reaching its caller (which is irrelevant).
1391                 if !callee.def.requires_caller_location(tcx) {
1392                     return span_to_caller_location(source_info.span);
1393                 }
1394                 source_info.span = callsite_span;
1395             }
1396
1397             // Skip past all of the parents with `inlined: None`.
1398             match scope_data.inlined_parent_scope {
1399                 Some(parent) => source_info.scope = parent,
1400                 None => break,
1401             }
1402         }
1403
1404         // No inlined `SourceScope`s, or all of them were `#[track_caller]`.
1405         self.caller_location.unwrap_or_else(|| span_to_caller_location(source_info.span))
1406     }
1407
1408     fn get_personality_slot(&mut self, bx: &mut Bx) -> PlaceRef<'tcx, Bx::Value> {
1409         let cx = bx.cx();
1410         if let Some(slot) = self.personality_slot {
1411             slot
1412         } else {
1413             let layout = cx.layout_of(
1414                 cx.tcx().intern_tup(&[cx.tcx().mk_mut_ptr(cx.tcx().types.u8), cx.tcx().types.i32]),
1415             );
1416             let slot = PlaceRef::alloca(bx, layout);
1417             self.personality_slot = Some(slot);
1418             slot
1419         }
1420     }
1421
1422     /// Returns the landing/cleanup pad wrapper around the given basic block.
1423     // FIXME(eddyb) rename this to `eh_pad_for`.
1424     fn landing_pad_for(&mut self, bb: mir::BasicBlock) -> Bx::BasicBlock {
1425         if let Some(landing_pad) = self.landing_pads[bb] {
1426             return landing_pad;
1427         }
1428
1429         let landing_pad = self.landing_pad_for_uncached(bb);
1430         self.landing_pads[bb] = Some(landing_pad);
1431         landing_pad
1432     }
1433
1434     // FIXME(eddyb) rename this to `eh_pad_for_uncached`.
1435     fn landing_pad_for_uncached(&mut self, bb: mir::BasicBlock) -> Bx::BasicBlock {
1436         let llbb = self.llbb(bb);
1437         if base::wants_msvc_seh(self.cx.sess()) {
1438             let funclet;
1439             let ret_llbb;
1440             match self.mir[bb].terminator.as_ref().map(|t| &t.kind) {
1441                 // This is a basic block that we're aborting the program for,
1442                 // notably in an `extern` function. These basic blocks are inserted
1443                 // so that we assert that `extern` functions do indeed not panic,
1444                 // and if they do we abort the process.
1445                 //
1446                 // On MSVC these are tricky though (where we're doing funclets). If
1447                 // we were to do a cleanuppad (like below) the normal functions like
1448                 // `longjmp` would trigger the abort logic, terminating the
1449                 // program. Instead we insert the equivalent of `catch(...)` for C++
1450                 // which magically doesn't trigger when `longjmp` files over this
1451                 // frame.
1452                 //
1453                 // Lots more discussion can be found on #48251 but this codegen is
1454                 // modeled after clang's for:
1455                 //
1456                 //      try {
1457                 //          foo();
1458                 //      } catch (...) {
1459                 //          bar();
1460                 //      }
1461                 Some(&mir::TerminatorKind::Abort) => {
1462                     let cs_llbb =
1463                         Bx::append_block(self.cx, self.llfn, &format!("cs_funclet{:?}", bb));
1464                     let cp_llbb =
1465                         Bx::append_block(self.cx, self.llfn, &format!("cp_funclet{:?}", bb));
1466                     ret_llbb = cs_llbb;
1467
1468                     let mut cs_bx = Bx::build(self.cx, cs_llbb);
1469                     let cs = cs_bx.catch_switch(None, None, &[cp_llbb]);
1470
1471                     // The "null" here is actually a RTTI type descriptor for the
1472                     // C++ personality function, but `catch (...)` has no type so
1473                     // it's null. The 64 here is actually a bitfield which
1474                     // represents that this is a catch-all block.
1475                     let mut cp_bx = Bx::build(self.cx, cp_llbb);
1476                     let null = cp_bx.const_null(
1477                         cp_bx.type_i8p_ext(cp_bx.cx().data_layout().instruction_address_space),
1478                     );
1479                     let sixty_four = cp_bx.const_i32(64);
1480                     funclet = cp_bx.catch_pad(cs, &[null, sixty_four, null]);
1481                     cp_bx.br(llbb);
1482                 }
1483                 _ => {
1484                     let cleanup_llbb =
1485                         Bx::append_block(self.cx, self.llfn, &format!("funclet_{:?}", bb));
1486                     ret_llbb = cleanup_llbb;
1487                     let mut cleanup_bx = Bx::build(self.cx, cleanup_llbb);
1488                     funclet = cleanup_bx.cleanup_pad(None, &[]);
1489                     cleanup_bx.br(llbb);
1490                 }
1491             }
1492             self.funclets[bb] = Some(funclet);
1493             ret_llbb
1494         } else {
1495             let cleanup_llbb = Bx::append_block(self.cx, self.llfn, "cleanup");
1496             let mut cleanup_bx = Bx::build(self.cx, cleanup_llbb);
1497
1498             let llpersonality = self.cx.eh_personality();
1499             let llretty = self.landing_pad_type();
1500             let lp = cleanup_bx.cleanup_landing_pad(llretty, llpersonality);
1501
1502             let slot = self.get_personality_slot(&mut cleanup_bx);
1503             slot.storage_live(&mut cleanup_bx);
1504             Pair(cleanup_bx.extract_value(lp, 0), cleanup_bx.extract_value(lp, 1))
1505                 .store(&mut cleanup_bx, slot);
1506
1507             cleanup_bx.br(llbb);
1508             cleanup_llbb
1509         }
1510     }
1511
1512     fn landing_pad_type(&self) -> Bx::Type {
1513         let cx = self.cx;
1514         cx.type_struct(&[cx.type_i8p(), cx.type_i32()], false)
1515     }
1516
1517     fn unreachable_block(&mut self) -> Bx::BasicBlock {
1518         self.unreachable_block.unwrap_or_else(|| {
1519             let llbb = Bx::append_block(self.cx, self.llfn, "unreachable");
1520             let mut bx = Bx::build(self.cx, llbb);
1521             bx.unreachable();
1522             self.unreachable_block = Some(llbb);
1523             llbb
1524         })
1525     }
1526
1527     fn double_unwind_guard(&mut self) -> Bx::BasicBlock {
1528         self.double_unwind_guard.unwrap_or_else(|| {
1529             assert!(!base::wants_msvc_seh(self.cx.sess()));
1530
1531             let llbb = Bx::append_block(self.cx, self.llfn, "abort");
1532             let mut bx = Bx::build(self.cx, llbb);
1533             self.set_debug_loc(&mut bx, mir::SourceInfo::outermost(self.mir.span));
1534
1535             let llpersonality = self.cx.eh_personality();
1536             let llretty = self.landing_pad_type();
1537             bx.cleanup_landing_pad(llretty, llpersonality);
1538
1539             let (fn_abi, fn_ptr) = common::build_langcall(&bx, None, LangItem::PanicNoUnwind);
1540             let fn_ty = bx.fn_decl_backend_type(&fn_abi);
1541
1542             let llret = bx.call(fn_ty, Some(&fn_abi), fn_ptr, &[], None);
1543             bx.do_not_inline(llret);
1544
1545             bx.unreachable();
1546
1547             self.double_unwind_guard = Some(llbb);
1548             llbb
1549         })
1550     }
1551
1552     /// Get the backend `BasicBlock` for a MIR `BasicBlock`, either already
1553     /// cached in `self.cached_llbbs`, or created on demand (and cached).
1554     // FIXME(eddyb) rename `llbb` and other `ll`-prefixed things to use a
1555     // more backend-agnostic prefix such as `cg` (i.e. this would be `cgbb`).
1556     pub fn llbb(&mut self, bb: mir::BasicBlock) -> Bx::BasicBlock {
1557         self.cached_llbbs[bb].unwrap_or_else(|| {
1558             // FIXME(eddyb) only name the block if `fewer_names` is `false`.
1559             let llbb = Bx::append_block(self.cx, self.llfn, &format!("{:?}", bb));
1560             self.cached_llbbs[bb] = Some(llbb);
1561             llbb
1562         })
1563     }
1564
1565     fn make_return_dest(
1566         &mut self,
1567         bx: &mut Bx,
1568         dest: mir::Place<'tcx>,
1569         fn_ret: &ArgAbi<'tcx, Ty<'tcx>>,
1570         llargs: &mut Vec<Bx::Value>,
1571         is_intrinsic: bool,
1572     ) -> ReturnDest<'tcx, Bx::Value> {
1573         // If the return is ignored, we can just return a do-nothing `ReturnDest`.
1574         if fn_ret.is_ignore() {
1575             return ReturnDest::Nothing;
1576         }
1577         let dest = if let Some(index) = dest.as_local() {
1578             match self.locals[index] {
1579                 LocalRef::Place(dest) => dest,
1580                 LocalRef::UnsizedPlace(_) => bug!("return type must be sized"),
1581                 LocalRef::Operand(None) => {
1582                     // Handle temporary places, specifically `Operand` ones, as
1583                     // they don't have `alloca`s.
1584                     return if fn_ret.is_indirect() {
1585                         // Odd, but possible, case, we have an operand temporary,
1586                         // but the calling convention has an indirect return.
1587                         let tmp = PlaceRef::alloca(bx, fn_ret.layout);
1588                         tmp.storage_live(bx);
1589                         llargs.push(tmp.llval);
1590                         ReturnDest::IndirectOperand(tmp, index)
1591                     } else if is_intrinsic {
1592                         // Currently, intrinsics always need a location to store
1593                         // the result, so we create a temporary `alloca` for the
1594                         // result.
1595                         let tmp = PlaceRef::alloca(bx, fn_ret.layout);
1596                         tmp.storage_live(bx);
1597                         ReturnDest::IndirectOperand(tmp, index)
1598                     } else {
1599                         ReturnDest::DirectOperand(index)
1600                     };
1601                 }
1602                 LocalRef::Operand(Some(_)) => {
1603                     bug!("place local already assigned to");
1604                 }
1605             }
1606         } else {
1607             self.codegen_place(
1608                 bx,
1609                 mir::PlaceRef { local: dest.local, projection: &dest.projection },
1610             )
1611         };
1612         if fn_ret.is_indirect() {
1613             if dest.align < dest.layout.align.abi {
1614                 // Currently, MIR code generation does not create calls
1615                 // that store directly to fields of packed structs (in
1616                 // fact, the calls it creates write only to temps).
1617                 //
1618                 // If someone changes that, please update this code path
1619                 // to create a temporary.
1620                 span_bug!(self.mir.span, "can't directly store to unaligned value");
1621             }
1622             llargs.push(dest.llval);
1623             ReturnDest::Nothing
1624         } else {
1625             ReturnDest::Store(dest)
1626         }
1627     }
1628
1629     fn codegen_transmute(&mut self, bx: &mut Bx, src: &mir::Operand<'tcx>, dst: mir::Place<'tcx>) {
1630         if let Some(index) = dst.as_local() {
1631             match self.locals[index] {
1632                 LocalRef::Place(place) => self.codegen_transmute_into(bx, src, place),
1633                 LocalRef::UnsizedPlace(_) => bug!("transmute must not involve unsized locals"),
1634                 LocalRef::Operand(None) => {
1635                     let dst_layout = bx.layout_of(self.monomorphized_place_ty(dst.as_ref()));
1636                     assert!(!dst_layout.ty.has_erasable_regions());
1637                     let place = PlaceRef::alloca(bx, dst_layout);
1638                     place.storage_live(bx);
1639                     self.codegen_transmute_into(bx, src, place);
1640                     let op = bx.load_operand(place);
1641                     place.storage_dead(bx);
1642                     self.locals[index] = LocalRef::Operand(Some(op));
1643                     self.debug_introduce_local(bx, index);
1644                 }
1645                 LocalRef::Operand(Some(op)) => {
1646                     assert!(op.layout.is_zst(), "assigning to initialized SSAtemp");
1647                 }
1648             }
1649         } else {
1650             let dst = self.codegen_place(bx, dst.as_ref());
1651             self.codegen_transmute_into(bx, src, dst);
1652         }
1653     }
1654
1655     fn codegen_transmute_into(
1656         &mut self,
1657         bx: &mut Bx,
1658         src: &mir::Operand<'tcx>,
1659         dst: PlaceRef<'tcx, Bx::Value>,
1660     ) {
1661         let src = self.codegen_operand(bx, src);
1662
1663         // Special-case transmutes between scalars as simple bitcasts.
1664         match (src.layout.abi, dst.layout.abi) {
1665             (abi::Abi::Scalar(src_scalar), abi::Abi::Scalar(dst_scalar)) => {
1666                 // HACK(eddyb) LLVM doesn't like `bitcast`s between pointers and non-pointers.
1667                 if (src_scalar.primitive() == abi::Pointer)
1668                     == (dst_scalar.primitive() == abi::Pointer)
1669                 {
1670                     assert_eq!(src.layout.size, dst.layout.size);
1671
1672                     // NOTE(eddyb) the `from_immediate` and `to_immediate_scalar`
1673                     // conversions allow handling `bool`s the same as `u8`s.
1674                     let src = bx.from_immediate(src.immediate());
1675                     let src_as_dst = bx.bitcast(src, bx.backend_type(dst.layout));
1676                     Immediate(bx.to_immediate_scalar(src_as_dst, dst_scalar)).store(bx, dst);
1677                     return;
1678                 }
1679             }
1680             _ => {}
1681         }
1682
1683         let llty = bx.backend_type(src.layout);
1684         let cast_ptr = bx.pointercast(dst.llval, bx.type_ptr_to(llty));
1685         let align = src.layout.align.abi.min(dst.align);
1686         src.val.store(bx, PlaceRef::new_sized_aligned(cast_ptr, src.layout, align));
1687     }
1688
1689     // Stores the return value of a function call into it's final location.
1690     fn store_return(
1691         &mut self,
1692         bx: &mut Bx,
1693         dest: ReturnDest<'tcx, Bx::Value>,
1694         ret_abi: &ArgAbi<'tcx, Ty<'tcx>>,
1695         llval: Bx::Value,
1696     ) {
1697         use self::ReturnDest::*;
1698
1699         match dest {
1700             Nothing => (),
1701             Store(dst) => bx.store_arg(&ret_abi, llval, dst),
1702             IndirectOperand(tmp, index) => {
1703                 let op = bx.load_operand(tmp);
1704                 tmp.storage_dead(bx);
1705                 self.locals[index] = LocalRef::Operand(Some(op));
1706                 self.debug_introduce_local(bx, index);
1707             }
1708             DirectOperand(index) => {
1709                 // If there is a cast, we have to store and reload.
1710                 let op = if let PassMode::Cast(..) = ret_abi.mode {
1711                     let tmp = PlaceRef::alloca(bx, ret_abi.layout);
1712                     tmp.storage_live(bx);
1713                     bx.store_arg(&ret_abi, llval, tmp);
1714                     let op = bx.load_operand(tmp);
1715                     tmp.storage_dead(bx);
1716                     op
1717                 } else {
1718                     OperandRef::from_immediate_or_packed_pair(bx, llval, ret_abi.layout)
1719                 };
1720                 self.locals[index] = LocalRef::Operand(Some(op));
1721                 self.debug_introduce_local(bx, index);
1722             }
1723         }
1724     }
1725 }
1726
1727 enum ReturnDest<'tcx, V> {
1728     // Do nothing; the return value is indirect or ignored.
1729     Nothing,
1730     // Store the return value to the pointer.
1731     Store(PlaceRef<'tcx, V>),
1732     // Store an indirect return value to an operand local place.
1733     IndirectOperand(PlaceRef<'tcx, V>, mir::Local),
1734     // Store a direct return value to an operand local place.
1735     DirectOperand(mir::Local),
1736 }