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