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