]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_codegen_ssa/src/mir/block.rs
Rollup merge of #84461 - jyn514:remove-strip-item, r=GuillaumeGomez
[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_hir::lang_items::LangItem;
14 use rustc_index::vec::Idx;
15 use rustc_middle::mir::AssertKind;
16 use rustc_middle::mir::{self, SwitchTargets};
17 use rustc_middle::ty::layout::{FnAbiExt, HasTyCtxt};
18 use rustc_middle::ty::print::with_no_trimmed_paths;
19 use rustc_middle::ty::{self, Instance, Ty, TypeFoldable};
20 use rustc_span::source_map::Span;
21 use rustc_span::{sym, Symbol};
22 use rustc_target::abi::call::{ArgAbi, FnAbi, PassMode};
23 use rustc_target::abi::{self, LayoutOf};
24 use rustc_target::spec::abi::Abi;
25
26 /// Used by `FunctionCx::codegen_terminator` for emitting common patterns
27 /// e.g., creating a basic block, calling a function, etc.
28 struct TerminatorCodegenHelper<'tcx> {
29     bb: mir::BasicBlock,
30     terminator: &'tcx mir::Terminator<'tcx>,
31     funclet_bb: Option<mir::BasicBlock>,
32 }
33
34 impl<'a, 'tcx> TerminatorCodegenHelper<'tcx> {
35     /// Returns the associated funclet from `FunctionCx::funclets` for the
36     /// `funclet_bb` member if it is not `None`.
37     fn funclet<'b, Bx: BuilderMethods<'a, 'tcx>>(
38         &self,
39         fx: &'b FunctionCx<'a, 'tcx, Bx>,
40     ) -> Option<&'b Bx::Funclet> {
41         self.funclet_bb.and_then(|funcl| fx.funclets[funcl].as_ref())
42     }
43
44     fn lltarget<Bx: BuilderMethods<'a, 'tcx>>(
45         &self,
46         fx: &mut FunctionCx<'a, 'tcx, Bx>,
47         target: mir::BasicBlock,
48     ) -> (Bx::BasicBlock, bool) {
49         let span = self.terminator.source_info.span;
50         let lltarget = fx.blocks[target];
51         let target_funclet = fx.cleanup_kinds[target].funclet_bb(target);
52         match (self.funclet_bb, target_funclet) {
53             (None, None) => (lltarget, false),
54             (Some(f), Some(t_f)) if f == t_f || !base::wants_msvc_seh(fx.cx.tcx().sess) => {
55                 (lltarget, false)
56             }
57             // jump *into* cleanup - need a landing pad if GNU
58             (None, Some(_)) => (fx.landing_pad_to(target), false),
59             (Some(_), None) => span_bug!(span, "{:?} - jump out of cleanup?", self.terminator),
60             (Some(_), Some(_)) => (fx.landing_pad_to(target), true),
61         }
62     }
63
64     /// Create a basic block.
65     fn llblock<Bx: BuilderMethods<'a, 'tcx>>(
66         &self,
67         fx: &mut FunctionCx<'a, 'tcx, Bx>,
68         target: mir::BasicBlock,
69     ) -> Bx::BasicBlock {
70         let (lltarget, is_cleanupret) = self.lltarget(fx, target);
71         if is_cleanupret {
72             // MSVC cross-funclet jump - need a trampoline
73
74             debug!("llblock: creating cleanup trampoline for {:?}", target);
75             let name = &format!("{:?}_cleanup_trampoline_{:?}", self.bb, target);
76             let mut trampoline = fx.new_block(name);
77             trampoline.cleanup_ret(self.funclet(fx).unwrap(), Some(lltarget));
78             trampoline.llbb()
79         } else {
80             lltarget
81         }
82     }
83
84     fn funclet_br<Bx: BuilderMethods<'a, 'tcx>>(
85         &self,
86         fx: &mut FunctionCx<'a, 'tcx, Bx>,
87         bx: &mut Bx,
88         target: mir::BasicBlock,
89     ) {
90         let (lltarget, is_cleanupret) = self.lltarget(fx, target);
91         if is_cleanupret {
92             // micro-optimization: generate a `ret` rather than a jump
93             // to a trampoline.
94             bx.cleanup_ret(self.funclet(fx).unwrap(), Some(lltarget));
95         } else {
96             bx.br(lltarget);
97         }
98     }
99
100     /// Call `fn_ptr` of `fn_abi` with the arguments `llargs`, the optional
101     /// return destination `destination` and the cleanup function `cleanup`.
102     fn do_call<Bx: BuilderMethods<'a, 'tcx>>(
103         &self,
104         fx: &mut FunctionCx<'a, 'tcx, Bx>,
105         bx: &mut Bx,
106         fn_abi: FnAbi<'tcx, Ty<'tcx>>,
107         fn_ptr: Bx::Value,
108         llargs: &[Bx::Value],
109         destination: Option<(ReturnDest<'tcx, Bx::Value>, mir::BasicBlock)>,
110         cleanup: Option<mir::BasicBlock>,
111     ) {
112         // If there is a cleanup block and the function we're calling can unwind, then
113         // do an invoke, otherwise do a call.
114         if let Some(cleanup) = cleanup.filter(|_| fn_abi.can_unwind) {
115             let ret_bx = if let Some((_, target)) = destination {
116                 fx.blocks[target]
117             } else {
118                 fx.unreachable_block()
119             };
120             let invokeret =
121                 bx.invoke(fn_ptr, &llargs, ret_bx, self.llblock(fx, cleanup), self.funclet(fx));
122             bx.apply_attrs_callsite(&fn_abi, invokeret);
123
124             if let Some((ret_dest, target)) = destination {
125                 let mut ret_bx = fx.build_block(target);
126                 fx.set_debug_loc(&mut ret_bx, self.terminator.source_info);
127                 fx.store_return(&mut ret_bx, ret_dest, &fn_abi.ret, invokeret);
128             }
129         } else {
130             let llret = bx.call(fn_ptr, &llargs, self.funclet(fx));
131             bx.apply_attrs_callsite(&fn_abi, llret);
132             if fx.mir[self.bb].is_cleanup {
133                 // Cleanup is always the cold path. Don't inline
134                 // drop glue. Also, when there is a deeply-nested
135                 // struct, there are "symmetry" issues that cause
136                 // exponential inlining - see issue #41696.
137                 bx.do_not_inline(llret);
138             }
139
140             if let Some((ret_dest, target)) = destination {
141                 fx.store_return(bx, ret_dest, &fn_abi.ret, llret);
142                 self.funclet_br(fx, bx, target);
143             } else {
144                 bx.unreachable();
145             }
146         }
147     }
148 }
149
150 /// Codegen implementations for some terminator variants.
151 impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
152     /// Generates code for a `Resume` terminator.
153     fn codegen_resume_terminator(&mut self, helper: TerminatorCodegenHelper<'tcx>, mut bx: Bx) {
154         if let Some(funclet) = helper.funclet(self) {
155             bx.cleanup_ret(funclet, None);
156         } else {
157             let slot = self.get_personality_slot(&mut bx);
158             let lp0 = slot.project_field(&mut bx, 0);
159             let lp0 = bx.load_operand(lp0).immediate();
160             let lp1 = slot.project_field(&mut bx, 1);
161             let lp1 = bx.load_operand(lp1).immediate();
162             slot.storage_dead(&mut bx);
163
164             let mut lp = bx.const_undef(self.landing_pad_type());
165             lp = bx.insert_value(lp, lp0, 0);
166             lp = bx.insert_value(lp, lp1, 1);
167             bx.resume(lp);
168         }
169     }
170
171     fn codegen_switchint_terminator(
172         &mut self,
173         helper: TerminatorCodegenHelper<'tcx>,
174         mut bx: Bx,
175         discr: &mir::Operand<'tcx>,
176         switch_ty: Ty<'tcx>,
177         targets: &SwitchTargets,
178     ) {
179         let discr = self.codegen_operand(&mut bx, &discr);
180         // `switch_ty` is redundant, sanity-check that.
181         assert_eq!(discr.layout.ty, switch_ty);
182         let mut target_iter = targets.iter();
183         if target_iter.len() == 1 {
184             // If there are two targets (one conditional, one fallback), emit br instead of switch
185             let (test_value, target) = target_iter.next().unwrap();
186             let lltrue = helper.llblock(self, target);
187             let llfalse = helper.llblock(self, targets.otherwise());
188             if switch_ty == bx.tcx().types.bool {
189                 // Don't generate trivial icmps when switching on bool
190                 match test_value {
191                     0 => bx.cond_br(discr.immediate(), llfalse, lltrue),
192                     1 => bx.cond_br(discr.immediate(), lltrue, llfalse),
193                     _ => bug!(),
194                 }
195             } else {
196                 let switch_llty = bx.immediate_backend_type(bx.layout_of(switch_ty));
197                 let llval = bx.const_uint_big(switch_llty, test_value);
198                 let cmp = bx.icmp(IntPredicate::IntEQ, discr.immediate(), llval);
199                 bx.cond_br(cmp, lltrue, llfalse);
200             }
201         } else {
202             bx.switch(
203                 discr.immediate(),
204                 helper.llblock(self, targets.otherwise()),
205                 target_iter.map(|(value, target)| (value, helper.llblock(self, target))),
206             );
207         }
208     }
209
210     fn codegen_return_terminator(&mut self, mut bx: Bx) {
211         // Call `va_end` if this is the definition of a C-variadic function.
212         if self.fn_abi.c_variadic {
213             // The `VaList` "spoofed" argument is just after all the real arguments.
214             let va_list_arg_idx = self.fn_abi.args.len();
215             match self.locals[mir::Local::new(1 + va_list_arg_idx)] {
216                 LocalRef::Place(va_list) => {
217                     bx.va_end(va_list.llval);
218                 }
219                 _ => bug!("C-variadic function must have a `VaList` place"),
220             }
221         }
222         if self.fn_abi.ret.layout.abi.is_uninhabited() {
223             // Functions with uninhabited return values are marked `noreturn`,
224             // so we should make sure that we never actually do.
225             // We play it safe by using a well-defined `abort`, but we could go for immediate UB
226             // if that turns out to be helpful.
227             bx.abort();
228             // `abort` does not terminate the block, so we still need to generate
229             // an `unreachable` terminator after it.
230             bx.unreachable();
231             return;
232         }
233         let llval = match self.fn_abi.ret.mode {
234             PassMode::Ignore | PassMode::Indirect { .. } => {
235                 bx.ret_void();
236                 return;
237             }
238
239             PassMode::Direct(_) | PassMode::Pair(..) => {
240                 let op = self.codegen_consume(&mut bx, mir::Place::return_place().as_ref());
241                 if let Ref(llval, _, align) = op.val {
242                     bx.load(llval, align)
243                 } else {
244                     op.immediate_or_packed_pair(&mut bx)
245                 }
246             }
247
248             PassMode::Cast(cast_ty) => {
249                 let op = match self.locals[mir::RETURN_PLACE] {
250                     LocalRef::Operand(Some(op)) => op,
251                     LocalRef::Operand(None) => bug!("use of return before def"),
252                     LocalRef::Place(cg_place) => OperandRef {
253                         val: Ref(cg_place.llval, None, cg_place.align),
254                         layout: cg_place.layout,
255                     },
256                     LocalRef::UnsizedPlace(_) => bug!("return type must be sized"),
257                 };
258                 let llslot = match op.val {
259                     Immediate(_) | Pair(..) => {
260                         let scratch = PlaceRef::alloca(&mut bx, self.fn_abi.ret.layout);
261                         op.val.store(&mut bx, scratch);
262                         scratch.llval
263                     }
264                     Ref(llval, _, align) => {
265                         assert_eq!(align, op.layout.align.abi, "return place is unaligned!");
266                         llval
267                     }
268                 };
269                 let addr = bx.pointercast(llslot, bx.type_ptr_to(bx.cast_backend_type(&cast_ty)));
270                 bx.load(addr, self.fn_abi.ret.layout.align.abi)
271             }
272         };
273         bx.ret(llval);
274     }
275
276     fn codegen_drop_terminator(
277         &mut self,
278         helper: TerminatorCodegenHelper<'tcx>,
279         mut bx: Bx,
280         location: mir::Place<'tcx>,
281         target: mir::BasicBlock,
282         unwind: Option<mir::BasicBlock>,
283     ) {
284         let ty = location.ty(self.mir, bx.tcx()).ty;
285         let ty = self.monomorphize(ty);
286         let drop_fn = Instance::resolve_drop_in_place(bx.tcx(), ty);
287
288         if let ty::InstanceDef::DropGlue(_, None) = drop_fn.def {
289             // we don't actually need to drop anything.
290             helper.funclet_br(self, &mut bx, target);
291             return;
292         }
293
294         let place = self.codegen_place(&mut bx, location.as_ref());
295         let (args1, args2);
296         let mut args = if let Some(llextra) = place.llextra {
297             args2 = [place.llval, llextra];
298             &args2[..]
299         } else {
300             args1 = [place.llval];
301             &args1[..]
302         };
303         let (drop_fn, fn_abi) = match ty.kind() {
304             // FIXME(eddyb) perhaps move some of this logic into
305             // `Instance::resolve_drop_in_place`?
306             ty::Dynamic(..) => {
307                 let virtual_drop = Instance {
308                     def: ty::InstanceDef::Virtual(drop_fn.def_id(), 0),
309                     substs: drop_fn.substs,
310                 };
311                 let fn_abi = FnAbi::of_instance(&bx, virtual_drop, &[]);
312                 let vtable = args[1];
313                 args = &args[..1];
314                 (meth::DESTRUCTOR.get_fn(&mut bx, vtable, &fn_abi), fn_abi)
315             }
316             _ => (bx.get_fn_addr(drop_fn), FnAbi::of_instance(&bx, drop_fn, &[])),
317         };
318         helper.do_call(
319             self,
320             &mut bx,
321             fn_abi,
322             drop_fn,
323             args,
324             Some((ReturnDest::Nothing, target)),
325             unwind,
326         );
327     }
328
329     fn codegen_assert_terminator(
330         &mut self,
331         helper: TerminatorCodegenHelper<'tcx>,
332         mut bx: Bx,
333         terminator: &mir::Terminator<'tcx>,
334         cond: &mir::Operand<'tcx>,
335         expected: bool,
336         msg: &mir::AssertMessage<'tcx>,
337         target: mir::BasicBlock,
338         cleanup: Option<mir::BasicBlock>,
339     ) {
340         let span = terminator.source_info.span;
341         let cond = self.codegen_operand(&mut bx, cond).immediate();
342         let mut const_cond = bx.const_to_opt_u128(cond, false).map(|c| c == 1);
343
344         // This case can currently arise only from functions marked
345         // with #[rustc_inherit_overflow_checks] and inlined from
346         // another crate (mostly core::num generic/#[inline] fns),
347         // while the current crate doesn't use overflow checks.
348         // NOTE: Unlike binops, negation doesn't have its own
349         // checked operation, just a comparison with the minimum
350         // value, so we have to check for the assert message.
351         if !bx.check_overflow() {
352             if let AssertKind::OverflowNeg(_) = *msg {
353                 const_cond = Some(expected);
354             }
355         }
356
357         // Don't codegen the panic block if success if known.
358         if const_cond == Some(expected) {
359             helper.funclet_br(self, &mut bx, target);
360             return;
361         }
362
363         // Pass the condition through llvm.expect for branch hinting.
364         let cond = bx.expect(cond, expected);
365
366         // Create the failure block and the conditional branch to it.
367         let lltarget = helper.llblock(self, target);
368         let panic_block = self.new_block("panic");
369         if expected {
370             bx.cond_br(cond, lltarget, panic_block.llbb());
371         } else {
372             bx.cond_br(cond, panic_block.llbb(), lltarget);
373         }
374
375         // After this point, bx is the block for the call to panic.
376         bx = panic_block;
377         self.set_debug_loc(&mut bx, terminator.source_info);
378
379         // Get the location information.
380         let location = self.get_caller_location(&mut bx, terminator.source_info).immediate();
381
382         // Put together the arguments to the panic entry point.
383         let (lang_item, args) = match msg {
384             AssertKind::BoundsCheck { ref len, ref index } => {
385                 let len = self.codegen_operand(&mut bx, len).immediate();
386                 let index = self.codegen_operand(&mut bx, index).immediate();
387                 // It's `fn panic_bounds_check(index: usize, len: usize)`,
388                 // and `#[track_caller]` adds an implicit third argument.
389                 (LangItem::PanicBoundsCheck, vec![index, len, location])
390             }
391             _ => {
392                 let msg_str = Symbol::intern(msg.description());
393                 let msg = bx.const_str(msg_str);
394                 // It's `pub fn panic(expr: &str)`, with the wide reference being passed
395                 // as two arguments, and `#[track_caller]` adds an implicit third argument.
396                 (LangItem::Panic, vec![msg.0, msg.1, location])
397             }
398         };
399
400         // Obtain the panic entry point.
401         let def_id = common::langcall(bx.tcx(), Some(span), "", lang_item);
402         let instance = ty::Instance::mono(bx.tcx(), def_id);
403         let fn_abi = FnAbi::of_instance(&bx, instance, &[]);
404         let llfn = bx.get_fn_addr(instance);
405
406         // Codegen the actual panic invoke/call.
407         helper.do_call(self, &mut bx, fn_abi, llfn, &args, None, cleanup);
408     }
409
410     /// Returns `true` if this is indeed a panic intrinsic and codegen is done.
411     fn codegen_panic_intrinsic(
412         &mut self,
413         helper: &TerminatorCodegenHelper<'tcx>,
414         bx: &mut Bx,
415         intrinsic: Option<Symbol>,
416         instance: Option<Instance<'tcx>>,
417         source_info: mir::SourceInfo,
418         destination: &Option<(mir::Place<'tcx>, mir::BasicBlock)>,
419         cleanup: Option<mir::BasicBlock>,
420     ) -> bool {
421         // Emit a panic or a no-op for `assert_*` intrinsics.
422         // These are intrinsics that compile to panics so that we can get a message
423         // which mentions the offending type, even from a const context.
424         #[derive(Debug, PartialEq)]
425         enum AssertIntrinsic {
426             Inhabited,
427             ZeroValid,
428             UninitValid,
429         }
430         let panic_intrinsic = intrinsic.and_then(|i| match i {
431             sym::assert_inhabited => Some(AssertIntrinsic::Inhabited),
432             sym::assert_zero_valid => Some(AssertIntrinsic::ZeroValid),
433             sym::assert_uninit_valid => Some(AssertIntrinsic::UninitValid),
434             _ => None,
435         });
436         if let Some(intrinsic) = panic_intrinsic {
437             use AssertIntrinsic::*;
438             let ty = instance.unwrap().substs.type_at(0);
439             let layout = bx.layout_of(ty);
440             let do_panic = match intrinsic {
441                 Inhabited => layout.abi.is_uninhabited(),
442                 // We unwrap as the error type is `!`.
443                 ZeroValid => !layout.might_permit_raw_init(bx, /*zero:*/ true).unwrap(),
444                 // We unwrap as the error type is `!`.
445                 UninitValid => !layout.might_permit_raw_init(bx, /*zero:*/ false).unwrap(),
446             };
447             if do_panic {
448                 let msg_str = with_no_trimmed_paths(|| {
449                     if layout.abi.is_uninhabited() {
450                         // Use this error even for the other intrinsics as it is more precise.
451                         format!("attempted to instantiate uninhabited type `{}`", ty)
452                     } else if intrinsic == ZeroValid {
453                         format!("attempted to zero-initialize type `{}`, which is invalid", ty)
454                     } else {
455                         format!("attempted to leave type `{}` uninitialized, which is invalid", ty)
456                     }
457                 });
458                 let msg = bx.const_str(Symbol::intern(&msg_str));
459                 let location = self.get_caller_location(bx, source_info).immediate();
460
461                 // Obtain the panic entry point.
462                 // FIXME: dedup this with `codegen_assert_terminator` above.
463                 let def_id =
464                     common::langcall(bx.tcx(), Some(source_info.span), "", LangItem::Panic);
465                 let instance = ty::Instance::mono(bx.tcx(), def_id);
466                 let fn_abi = FnAbi::of_instance(bx, instance, &[]);
467                 let llfn = bx.get_fn_addr(instance);
468
469                 // Codegen the actual panic invoke/call.
470                 helper.do_call(
471                     self,
472                     bx,
473                     fn_abi,
474                     llfn,
475                     &[msg.0, msg.1, location],
476                     destination.as_ref().map(|(_, bb)| (ReturnDest::Nothing, *bb)),
477                     cleanup,
478                 );
479             } else {
480                 // a NOP
481                 let target = destination.as_ref().unwrap().1;
482                 helper.funclet_br(self, bx, target)
483             }
484             true
485         } else {
486             false
487         }
488     }
489
490     fn codegen_call_terminator(
491         &mut self,
492         helper: TerminatorCodegenHelper<'tcx>,
493         mut bx: Bx,
494         terminator: &mir::Terminator<'tcx>,
495         func: &mir::Operand<'tcx>,
496         args: &[mir::Operand<'tcx>],
497         destination: &Option<(mir::Place<'tcx>, mir::BasicBlock)>,
498         cleanup: Option<mir::BasicBlock>,
499         fn_span: Span,
500     ) {
501         let source_info = terminator.source_info;
502         let span = source_info.span;
503
504         // Create the callee. This is a fn ptr or zero-sized and hence a kind of scalar.
505         let callee = self.codegen_operand(&mut bx, func);
506
507         let (instance, mut llfn) = match *callee.layout.ty.kind() {
508             ty::FnDef(def_id, substs) => (
509                 Some(
510                     ty::Instance::resolve(bx.tcx(), ty::ParamEnv::reveal_all(), def_id, substs)
511                         .unwrap()
512                         .unwrap()
513                         .polymorphize(bx.tcx()),
514                 ),
515                 None,
516             ),
517             ty::FnPtr(_) => (None, Some(callee.immediate())),
518             _ => bug!("{} is not callable", callee.layout.ty),
519         };
520         let def = instance.map(|i| i.def);
521
522         if let Some(ty::InstanceDef::DropGlue(_, None)) = def {
523             // Empty drop glue; a no-op.
524             let &(_, target) = destination.as_ref().unwrap();
525             helper.funclet_br(self, &mut bx, target);
526             return;
527         }
528
529         // FIXME(eddyb) avoid computing this if possible, when `instance` is
530         // available - right now `sig` is only needed for getting the `abi`
531         // and figuring out how many extra args were passed to a C-variadic `fn`.
532         let sig = callee.layout.ty.fn_sig(bx.tcx());
533         let abi = sig.abi();
534
535         // Handle intrinsics old codegen wants Expr's for, ourselves.
536         let intrinsic = match def {
537             Some(ty::InstanceDef::Intrinsic(def_id)) => Some(bx.tcx().item_name(def_id)),
538             _ => None,
539         };
540
541         let extra_args = &args[sig.inputs().skip_binder().len()..];
542         let extra_args = extra_args
543             .iter()
544             .map(|op_arg| {
545                 let op_ty = op_arg.ty(self.mir, bx.tcx());
546                 self.monomorphize(op_ty)
547             })
548             .collect::<Vec<_>>();
549
550         let fn_abi = match instance {
551             Some(instance) => FnAbi::of_instance(&bx, instance, &extra_args),
552             None => FnAbi::of_fn_ptr(&bx, sig, &extra_args),
553         };
554
555         if intrinsic == Some(sym::transmute) {
556             if let Some(destination_ref) = destination.as_ref() {
557                 let &(dest, target) = destination_ref;
558                 self.codegen_transmute(&mut bx, &args[0], dest);
559                 helper.funclet_br(self, &mut bx, target);
560             } else {
561                 // If we are trying to transmute to an uninhabited type,
562                 // it is likely there is no allotted destination. In fact,
563                 // transmuting to an uninhabited type is UB, which means
564                 // we can do what we like. Here, we declare that transmuting
565                 // into an uninhabited type is impossible, so anything following
566                 // it must be unreachable.
567                 assert_eq!(fn_abi.ret.layout.abi, abi::Abi::Uninhabited);
568                 bx.unreachable();
569             }
570             return;
571         }
572
573         if self.codegen_panic_intrinsic(
574             &helper,
575             &mut bx,
576             intrinsic,
577             instance,
578             source_info,
579             destination,
580             cleanup,
581         ) {
582             return;
583         }
584
585         // The arguments we'll be passing. Plus one to account for outptr, if used.
586         let arg_count = fn_abi.args.len() + fn_abi.ret.is_indirect() as usize;
587         let mut llargs = Vec::with_capacity(arg_count);
588
589         // Prepare the return value destination
590         let ret_dest = if let Some((dest, _)) = *destination {
591             let is_intrinsic = intrinsic.is_some();
592             self.make_return_dest(&mut bx, dest, &fn_abi.ret, &mut llargs, is_intrinsic)
593         } else {
594             ReturnDest::Nothing
595         };
596
597         if intrinsic == Some(sym::caller_location) {
598             if let Some((_, target)) = destination.as_ref() {
599                 let location = self
600                     .get_caller_location(&mut bx, mir::SourceInfo { span: fn_span, ..source_info });
601
602                 if let ReturnDest::IndirectOperand(tmp, _) = ret_dest {
603                     location.val.store(&mut bx, tmp);
604                 }
605                 self.store_return(&mut bx, ret_dest, &fn_abi.ret, location.immediate());
606                 helper.funclet_br(self, &mut bx, *target);
607             }
608             return;
609         }
610
611         match intrinsic {
612             None | Some(sym::drop_in_place) => {}
613             Some(sym::copy_nonoverlapping) => unreachable!(),
614             Some(intrinsic) => {
615                 let dest = match ret_dest {
616                     _ if fn_abi.ret.is_indirect() => llargs[0],
617                     ReturnDest::Nothing => {
618                         bx.const_undef(bx.type_ptr_to(bx.arg_memory_ty(&fn_abi.ret)))
619                     }
620                     ReturnDest::IndirectOperand(dst, _) | ReturnDest::Store(dst) => dst.llval,
621                     ReturnDest::DirectOperand(_) => {
622                         bug!("Cannot use direct operand with an intrinsic call")
623                     }
624                 };
625
626                 let args: Vec<_> = args
627                     .iter()
628                     .enumerate()
629                     .map(|(i, arg)| {
630                         // The indices passed to simd_shuffle* in the
631                         // third argument must be constant. This is
632                         // checked by const-qualification, which also
633                         // promotes any complex rvalues to constants.
634                         if i == 2 && intrinsic.as_str().starts_with("simd_shuffle") {
635                             if let mir::Operand::Constant(constant) = arg {
636                                 let c = self.eval_mir_constant(constant);
637                                 let (llval, ty) =
638                                     self.simd_shuffle_indices(&bx, constant.span, constant.ty(), c);
639                                 return OperandRef {
640                                     val: Immediate(llval),
641                                     layout: bx.layout_of(ty),
642                                 };
643                             } else {
644                                 span_bug!(span, "shuffle indices must be constant");
645                             }
646                         }
647
648                         self.codegen_operand(&mut bx, arg)
649                     })
650                     .collect();
651
652                 Self::codegen_intrinsic_call(
653                     &mut bx,
654                     *instance.as_ref().unwrap(),
655                     &fn_abi,
656                     &args,
657                     dest,
658                     span,
659                 );
660
661                 if let ReturnDest::IndirectOperand(dst, _) = ret_dest {
662                     self.store_return(&mut bx, ret_dest, &fn_abi.ret, dst.llval);
663                 }
664
665                 if let Some((_, target)) = *destination {
666                     helper.funclet_br(self, &mut bx, target);
667                 } else {
668                     bx.unreachable();
669                 }
670
671                 return;
672             }
673         }
674
675         // Split the rust-call tupled arguments off.
676         let (first_args, untuple) = if abi == Abi::RustCall && !args.is_empty() {
677             let (tup, args) = args.split_last().unwrap();
678             (args, Some(tup))
679         } else {
680             (args, None)
681         };
682
683         'make_args: for (i, arg) in first_args.iter().enumerate() {
684             let mut op = self.codegen_operand(&mut bx, arg);
685
686             if let (0, Some(ty::InstanceDef::Virtual(_, idx))) = (i, def) {
687                 if let Pair(..) = op.val {
688                     // In the case of Rc<Self>, we need to explicitly pass a
689                     // *mut RcBox<Self> with a Scalar (not ScalarPair) ABI. This is a hack
690                     // that is understood elsewhere in the compiler as a method on
691                     // `dyn Trait`.
692                     // To get a `*mut RcBox<Self>`, we just keep unwrapping newtypes until
693                     // we get a value of a built-in pointer type
694                     'descend_newtypes: while !op.layout.ty.is_unsafe_ptr()
695                         && !op.layout.ty.is_region_ptr()
696                     {
697                         for i in 0..op.layout.fields.count() {
698                             let field = op.extract_field(&mut bx, i);
699                             if !field.layout.is_zst() {
700                                 // we found the one non-zero-sized field that is allowed
701                                 // now find *its* non-zero-sized field, or stop if it's a
702                                 // pointer
703                                 op = field;
704                                 continue 'descend_newtypes;
705                             }
706                         }
707
708                         span_bug!(span, "receiver has no non-zero-sized fields {:?}", op);
709                     }
710
711                     // now that we have `*dyn Trait` or `&dyn Trait`, split it up into its
712                     // data pointer and vtable. Look up the method in the vtable, and pass
713                     // the data pointer as the first argument
714                     match op.val {
715                         Pair(data_ptr, meta) => {
716                             llfn = Some(
717                                 meth::VirtualIndex::from_index(idx).get_fn(&mut bx, meta, &fn_abi),
718                             );
719                             llargs.push(data_ptr);
720                             continue 'make_args;
721                         }
722                         other => bug!("expected a Pair, got {:?}", other),
723                     }
724                 } else if let Ref(data_ptr, Some(meta), _) = op.val {
725                     // by-value dynamic dispatch
726                     llfn = Some(meth::VirtualIndex::from_index(idx).get_fn(&mut bx, meta, &fn_abi));
727                     llargs.push(data_ptr);
728                     continue;
729                 } else {
730                     span_bug!(span, "can't codegen a virtual call on {:?}", op);
731                 }
732             }
733
734             // The callee needs to own the argument memory if we pass it
735             // by-ref, so make a local copy of non-immediate constants.
736             match (arg, op.val) {
737                 (&mir::Operand::Copy(_), Ref(_, None, _))
738                 | (&mir::Operand::Constant(_), Ref(_, None, _)) => {
739                     let tmp = PlaceRef::alloca(&mut bx, op.layout);
740                     op.val.store(&mut bx, tmp);
741                     op.val = Ref(tmp.llval, None, tmp.align);
742                 }
743                 _ => {}
744             }
745
746             self.codegen_argument(&mut bx, op, &mut llargs, &fn_abi.args[i]);
747         }
748         if let Some(tup) = untuple {
749             self.codegen_arguments_untupled(
750                 &mut bx,
751                 tup,
752                 &mut llargs,
753                 &fn_abi.args[first_args.len()..],
754             )
755         }
756
757         let needs_location =
758             instance.map_or(false, |i| i.def.requires_caller_location(self.cx.tcx()));
759         if needs_location {
760             assert_eq!(
761                 fn_abi.args.len(),
762                 args.len() + 1,
763                 "#[track_caller] fn's must have 1 more argument in their ABI than in their MIR",
764             );
765             let location =
766                 self.get_caller_location(&mut bx, mir::SourceInfo { span: fn_span, ..source_info });
767             debug!(
768                 "codegen_call_terminator({:?}): location={:?} (fn_span {:?})",
769                 terminator, location, fn_span
770             );
771
772             let last_arg = fn_abi.args.last().unwrap();
773             self.codegen_argument(&mut bx, location, &mut llargs, last_arg);
774         }
775
776         let fn_ptr = match (llfn, instance) {
777             (Some(llfn), _) => llfn,
778             (None, Some(instance)) => bx.get_fn_addr(instance),
779             _ => span_bug!(span, "no llfn for call"),
780         };
781
782         helper.do_call(
783             self,
784             &mut bx,
785             fn_abi,
786             fn_ptr,
787             &llargs,
788             destination.as_ref().map(|&(_, target)| (ret_dest, target)),
789             cleanup,
790         );
791     }
792
793     fn codegen_asm_terminator(
794         &mut self,
795         helper: TerminatorCodegenHelper<'tcx>,
796         mut bx: Bx,
797         terminator: &mir::Terminator<'tcx>,
798         template: &[ast::InlineAsmTemplatePiece],
799         operands: &[mir::InlineAsmOperand<'tcx>],
800         options: ast::InlineAsmOptions,
801         line_spans: &[Span],
802         destination: Option<mir::BasicBlock>,
803     ) {
804         let span = terminator.source_info.span;
805
806         let operands: Vec<_> = operands
807             .iter()
808             .map(|op| match *op {
809                 mir::InlineAsmOperand::In { reg, ref value } => {
810                     let value = self.codegen_operand(&mut bx, value);
811                     InlineAsmOperandRef::In { reg, value }
812                 }
813                 mir::InlineAsmOperand::Out { reg, late, ref place } => {
814                     let place = place.map(|place| self.codegen_place(&mut bx, place.as_ref()));
815                     InlineAsmOperandRef::Out { reg, late, place }
816                 }
817                 mir::InlineAsmOperand::InOut { reg, late, ref in_value, ref out_place } => {
818                     let in_value = self.codegen_operand(&mut bx, in_value);
819                     let out_place =
820                         out_place.map(|out_place| self.codegen_place(&mut bx, out_place.as_ref()));
821                     InlineAsmOperandRef::InOut { reg, late, in_value, out_place }
822                 }
823                 mir::InlineAsmOperand::Const { ref value } => {
824                     let const_value = self
825                         .eval_mir_constant(value)
826                         .unwrap_or_else(|_| span_bug!(span, "asm const cannot be resolved"));
827                     let string = common::asm_const_to_str(
828                         bx.tcx(),
829                         span,
830                         const_value,
831                         bx.layout_of(value.ty()),
832                     );
833                     InlineAsmOperandRef::Const { string }
834                 }
835                 mir::InlineAsmOperand::SymFn { ref value } => {
836                     let literal = self.monomorphize(value.literal);
837                     if let ty::FnDef(def_id, substs) = *literal.ty().kind() {
838                         let instance = ty::Instance::resolve_for_fn_ptr(
839                             bx.tcx(),
840                             ty::ParamEnv::reveal_all(),
841                             def_id,
842                             substs,
843                         )
844                         .unwrap();
845                         InlineAsmOperandRef::SymFn { instance }
846                     } else {
847                         span_bug!(span, "invalid type for asm sym (fn)");
848                     }
849                 }
850                 mir::InlineAsmOperand::SymStatic { def_id } => {
851                     InlineAsmOperandRef::SymStatic { def_id }
852                 }
853             })
854             .collect();
855
856         bx.codegen_inline_asm(template, &operands, options, line_spans);
857
858         if let Some(target) = destination {
859             helper.funclet_br(self, &mut bx, target);
860         } else {
861             bx.unreachable();
862         }
863     }
864 }
865
866 impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
867     pub fn codegen_block(&mut self, bb: mir::BasicBlock) {
868         let mut bx = self.build_block(bb);
869         let mir = self.mir;
870         let data = &mir[bb];
871
872         debug!("codegen_block({:?}={:?})", bb, data);
873
874         for statement in &data.statements {
875             bx = self.codegen_statement(bx, statement);
876         }
877
878         self.codegen_terminator(bx, bb, data.terminator());
879     }
880
881     fn codegen_terminator(
882         &mut self,
883         mut bx: Bx,
884         bb: mir::BasicBlock,
885         terminator: &'tcx mir::Terminator<'tcx>,
886     ) {
887         debug!("codegen_terminator: {:?}", terminator);
888
889         // Create the cleanup bundle, if needed.
890         let funclet_bb = self.cleanup_kinds[bb].funclet_bb(bb);
891         let helper = TerminatorCodegenHelper { bb, terminator, funclet_bb };
892
893         self.set_debug_loc(&mut bx, terminator.source_info);
894         match terminator.kind {
895             mir::TerminatorKind::Resume => self.codegen_resume_terminator(helper, bx),
896
897             mir::TerminatorKind::Abort => {
898                 bx.abort();
899                 // `abort` does not terminate the block, so we still need to generate
900                 // an `unreachable` terminator after it.
901                 bx.unreachable();
902             }
903
904             mir::TerminatorKind::Goto { target } => {
905                 if bb == target {
906                     // This is an unconditional branch back to this same basic block. That means we
907                     // have something like a `loop {}` statement. LLVM versions before 12.0
908                     // miscompile this because they assume forward progress. For older versions
909                     // try to handle just this specific case which comes up commonly in practice
910                     // (e.g., in embedded code).
911                     //
912                     // NB: the `sideeffect` currently checks for the LLVM version used internally.
913                     bx.sideeffect();
914                 }
915
916                 helper.funclet_br(self, &mut bx, target);
917             }
918
919             mir::TerminatorKind::SwitchInt { ref discr, switch_ty, ref targets } => {
920                 self.codegen_switchint_terminator(helper, bx, discr, switch_ty, targets);
921             }
922
923             mir::TerminatorKind::Return => {
924                 self.codegen_return_terminator(bx);
925             }
926
927             mir::TerminatorKind::Unreachable => {
928                 bx.unreachable();
929             }
930
931             mir::TerminatorKind::Drop { place, target, unwind } => {
932                 self.codegen_drop_terminator(helper, bx, place, target, unwind);
933             }
934
935             mir::TerminatorKind::Assert { ref cond, expected, ref msg, target, cleanup } => {
936                 self.codegen_assert_terminator(
937                     helper, bx, terminator, cond, expected, msg, target, cleanup,
938                 );
939             }
940
941             mir::TerminatorKind::DropAndReplace { .. } => {
942                 bug!("undesugared DropAndReplace in codegen: {:?}", terminator);
943             }
944
945             mir::TerminatorKind::Call {
946                 ref func,
947                 ref args,
948                 ref destination,
949                 cleanup,
950                 from_hir_call: _,
951                 fn_span,
952             } => {
953                 self.codegen_call_terminator(
954                     helper,
955                     bx,
956                     terminator,
957                     func,
958                     args,
959                     destination,
960                     cleanup,
961                     fn_span,
962                 );
963             }
964             mir::TerminatorKind::GeneratorDrop | mir::TerminatorKind::Yield { .. } => {
965                 bug!("generator ops in codegen")
966             }
967             mir::TerminatorKind::FalseEdge { .. } | mir::TerminatorKind::FalseUnwind { .. } => {
968                 bug!("borrowck false edges in codegen")
969             }
970
971             mir::TerminatorKind::InlineAsm {
972                 template,
973                 ref operands,
974                 options,
975                 line_spans,
976                 destination,
977             } => {
978                 self.codegen_asm_terminator(
979                     helper,
980                     bx,
981                     terminator,
982                     template,
983                     operands,
984                     options,
985                     line_spans,
986                     destination,
987                 );
988             }
989         }
990     }
991
992     fn codegen_argument(
993         &mut self,
994         bx: &mut Bx,
995         op: OperandRef<'tcx, Bx::Value>,
996         llargs: &mut Vec<Bx::Value>,
997         arg: &ArgAbi<'tcx, Ty<'tcx>>,
998     ) {
999         // Fill padding with undef value, where applicable.
1000         if let Some(ty) = arg.pad {
1001             llargs.push(bx.const_undef(bx.reg_backend_type(&ty)))
1002         }
1003
1004         if arg.is_ignore() {
1005             return;
1006         }
1007
1008         if let PassMode::Pair(..) = arg.mode {
1009             match op.val {
1010                 Pair(a, b) => {
1011                     llargs.push(a);
1012                     llargs.push(b);
1013                     return;
1014                 }
1015                 _ => bug!("codegen_argument: {:?} invalid for pair argument", op),
1016             }
1017         } else if arg.is_unsized_indirect() {
1018             match op.val {
1019                 Ref(a, Some(b), _) => {
1020                     llargs.push(a);
1021                     llargs.push(b);
1022                     return;
1023                 }
1024                 _ => bug!("codegen_argument: {:?} invalid for unsized indirect argument", op),
1025             }
1026         }
1027
1028         // Force by-ref if we have to load through a cast pointer.
1029         let (mut llval, align, by_ref) = match op.val {
1030             Immediate(_) | Pair(..) => match arg.mode {
1031                 PassMode::Indirect { .. } | PassMode::Cast(_) => {
1032                     let scratch = PlaceRef::alloca(bx, arg.layout);
1033                     op.val.store(bx, scratch);
1034                     (scratch.llval, scratch.align, true)
1035                 }
1036                 _ => (op.immediate_or_packed_pair(bx), arg.layout.align.abi, false),
1037             },
1038             Ref(llval, _, align) => {
1039                 if arg.is_indirect() && align < arg.layout.align.abi {
1040                     // `foo(packed.large_field)`. We can't pass the (unaligned) field directly. I
1041                     // think that ATM (Rust 1.16) we only pass temporaries, but we shouldn't
1042                     // have scary latent bugs around.
1043
1044                     let scratch = PlaceRef::alloca(bx, arg.layout);
1045                     base::memcpy_ty(
1046                         bx,
1047                         scratch.llval,
1048                         scratch.align,
1049                         llval,
1050                         align,
1051                         op.layout,
1052                         MemFlags::empty(),
1053                     );
1054                     (scratch.llval, scratch.align, true)
1055                 } else {
1056                     (llval, align, true)
1057                 }
1058             }
1059         };
1060
1061         if by_ref && !arg.is_indirect() {
1062             // Have to load the argument, maybe while casting it.
1063             if let PassMode::Cast(ty) = arg.mode {
1064                 let addr = bx.pointercast(llval, bx.type_ptr_to(bx.cast_backend_type(&ty)));
1065                 llval = bx.load(addr, align.min(arg.layout.align.abi));
1066             } else {
1067                 // We can't use `PlaceRef::load` here because the argument
1068                 // may have a type we don't treat as immediate, but the ABI
1069                 // used for this call is passing it by-value. In that case,
1070                 // the load would just produce `OperandValue::Ref` instead
1071                 // of the `OperandValue::Immediate` we need for the call.
1072                 llval = bx.load(llval, align);
1073                 if let abi::Abi::Scalar(ref scalar) = arg.layout.abi {
1074                     if scalar.is_bool() {
1075                         bx.range_metadata(llval, 0..2);
1076                     }
1077                 }
1078                 // We store bools as `i8` so we need to truncate to `i1`.
1079                 llval = bx.to_immediate(llval, arg.layout);
1080             }
1081         }
1082
1083         llargs.push(llval);
1084     }
1085
1086     fn codegen_arguments_untupled(
1087         &mut self,
1088         bx: &mut Bx,
1089         operand: &mir::Operand<'tcx>,
1090         llargs: &mut Vec<Bx::Value>,
1091         args: &[ArgAbi<'tcx, Ty<'tcx>>],
1092     ) {
1093         let tuple = self.codegen_operand(bx, operand);
1094
1095         // Handle both by-ref and immediate tuples.
1096         if let Ref(llval, None, align) = tuple.val {
1097             let tuple_ptr = PlaceRef::new_sized_aligned(llval, tuple.layout, align);
1098             for i in 0..tuple.layout.fields.count() {
1099                 let field_ptr = tuple_ptr.project_field(bx, i);
1100                 let field = bx.load_operand(field_ptr);
1101                 self.codegen_argument(bx, field, llargs, &args[i]);
1102             }
1103         } else if let Ref(_, Some(_), _) = tuple.val {
1104             bug!("closure arguments must be sized")
1105         } else {
1106             // If the tuple is immediate, the elements are as well.
1107             for i in 0..tuple.layout.fields.count() {
1108                 let op = tuple.extract_field(bx, i);
1109                 self.codegen_argument(bx, op, llargs, &args[i]);
1110             }
1111         }
1112     }
1113
1114     fn get_caller_location(
1115         &mut self,
1116         bx: &mut Bx,
1117         mut source_info: mir::SourceInfo,
1118     ) -> OperandRef<'tcx, Bx::Value> {
1119         let tcx = bx.tcx();
1120
1121         let mut span_to_caller_location = |span: Span| {
1122             let topmost = span.ctxt().outer_expn().expansion_cause().unwrap_or(span);
1123             let caller = tcx.sess.source_map().lookup_char_pos(topmost.lo());
1124             let const_loc = tcx.const_caller_location((
1125                 Symbol::intern(&caller.file.name.prefer_remapped().to_string_lossy()),
1126                 caller.line as u32,
1127                 caller.col_display as u32 + 1,
1128             ));
1129             OperandRef::from_const(bx, const_loc, bx.tcx().caller_location_ty())
1130         };
1131
1132         // Walk up the `SourceScope`s, in case some of them are from MIR inlining.
1133         // If so, the starting `source_info.span` is in the innermost inlined
1134         // function, and will be replaced with outer callsite spans as long
1135         // as the inlined functions were `#[track_caller]`.
1136         loop {
1137             let scope_data = &self.mir.source_scopes[source_info.scope];
1138
1139             if let Some((callee, callsite_span)) = scope_data.inlined {
1140                 // Stop inside the most nested non-`#[track_caller]` function,
1141                 // before ever reaching its caller (which is irrelevant).
1142                 if !callee.def.requires_caller_location(tcx) {
1143                     return span_to_caller_location(source_info.span);
1144                 }
1145                 source_info.span = callsite_span;
1146             }
1147
1148             // Skip past all of the parents with `inlined: None`.
1149             match scope_data.inlined_parent_scope {
1150                 Some(parent) => source_info.scope = parent,
1151                 None => break,
1152             }
1153         }
1154
1155         // No inlined `SourceScope`s, or all of them were `#[track_caller]`.
1156         self.caller_location.unwrap_or_else(|| span_to_caller_location(source_info.span))
1157     }
1158
1159     fn get_personality_slot(&mut self, bx: &mut Bx) -> PlaceRef<'tcx, Bx::Value> {
1160         let cx = bx.cx();
1161         if let Some(slot) = self.personality_slot {
1162             slot
1163         } else {
1164             let layout = cx.layout_of(
1165                 cx.tcx().intern_tup(&[cx.tcx().mk_mut_ptr(cx.tcx().types.u8), cx.tcx().types.i32]),
1166             );
1167             let slot = PlaceRef::alloca(bx, layout);
1168             self.personality_slot = Some(slot);
1169             slot
1170         }
1171     }
1172
1173     /// Returns the landing-pad wrapper around the given basic block.
1174     ///
1175     /// No-op in MSVC SEH scheme.
1176     fn landing_pad_to(&mut self, target_bb: mir::BasicBlock) -> Bx::BasicBlock {
1177         if let Some(block) = self.landing_pads[target_bb] {
1178             return block;
1179         }
1180
1181         let block = self.blocks[target_bb];
1182         let landing_pad = self.landing_pad_uncached(block);
1183         self.landing_pads[target_bb] = Some(landing_pad);
1184         landing_pad
1185     }
1186
1187     fn landing_pad_uncached(&mut self, target_bb: Bx::BasicBlock) -> Bx::BasicBlock {
1188         if base::wants_msvc_seh(self.cx.sess()) {
1189             span_bug!(self.mir.span, "landing pad was not inserted?")
1190         }
1191
1192         let mut bx = self.new_block("cleanup");
1193
1194         let llpersonality = self.cx.eh_personality();
1195         let llretty = self.landing_pad_type();
1196         let lp = bx.landing_pad(llretty, llpersonality, 1);
1197         bx.set_cleanup(lp);
1198
1199         let slot = self.get_personality_slot(&mut bx);
1200         slot.storage_live(&mut bx);
1201         Pair(bx.extract_value(lp, 0), bx.extract_value(lp, 1)).store(&mut bx, slot);
1202
1203         bx.br(target_bb);
1204         bx.llbb()
1205     }
1206
1207     fn landing_pad_type(&self) -> Bx::Type {
1208         let cx = self.cx;
1209         cx.type_struct(&[cx.type_i8p(), cx.type_i32()], false)
1210     }
1211
1212     fn unreachable_block(&mut self) -> Bx::BasicBlock {
1213         self.unreachable_block.unwrap_or_else(|| {
1214             let mut bx = self.new_block("unreachable");
1215             bx.unreachable();
1216             self.unreachable_block = Some(bx.llbb());
1217             bx.llbb()
1218         })
1219     }
1220
1221     pub fn new_block(&self, name: &str) -> Bx {
1222         Bx::new_block(self.cx, self.llfn, name)
1223     }
1224
1225     pub fn build_block(&self, bb: mir::BasicBlock) -> Bx {
1226         let mut bx = Bx::with_cx(self.cx);
1227         bx.position_at_end(self.blocks[bb]);
1228         bx
1229     }
1230
1231     fn make_return_dest(
1232         &mut self,
1233         bx: &mut Bx,
1234         dest: mir::Place<'tcx>,
1235         fn_ret: &ArgAbi<'tcx, Ty<'tcx>>,
1236         llargs: &mut Vec<Bx::Value>,
1237         is_intrinsic: bool,
1238     ) -> ReturnDest<'tcx, Bx::Value> {
1239         // If the return is ignored, we can just return a do-nothing `ReturnDest`.
1240         if fn_ret.is_ignore() {
1241             return ReturnDest::Nothing;
1242         }
1243         let dest = if let Some(index) = dest.as_local() {
1244             match self.locals[index] {
1245                 LocalRef::Place(dest) => dest,
1246                 LocalRef::UnsizedPlace(_) => bug!("return type must be sized"),
1247                 LocalRef::Operand(None) => {
1248                     // Handle temporary places, specifically `Operand` ones, as
1249                     // they don't have `alloca`s.
1250                     return if fn_ret.is_indirect() {
1251                         // Odd, but possible, case, we have an operand temporary,
1252                         // but the calling convention has an indirect return.
1253                         let tmp = PlaceRef::alloca(bx, fn_ret.layout);
1254                         tmp.storage_live(bx);
1255                         llargs.push(tmp.llval);
1256                         ReturnDest::IndirectOperand(tmp, index)
1257                     } else if is_intrinsic {
1258                         // Currently, intrinsics always need a location to store
1259                         // the result, so we create a temporary `alloca` for the
1260                         // result.
1261                         let tmp = PlaceRef::alloca(bx, fn_ret.layout);
1262                         tmp.storage_live(bx);
1263                         ReturnDest::IndirectOperand(tmp, index)
1264                     } else {
1265                         ReturnDest::DirectOperand(index)
1266                     };
1267                 }
1268                 LocalRef::Operand(Some(_)) => {
1269                     bug!("place local already assigned to");
1270                 }
1271             }
1272         } else {
1273             self.codegen_place(
1274                 bx,
1275                 mir::PlaceRef { local: dest.local, projection: &dest.projection },
1276             )
1277         };
1278         if fn_ret.is_indirect() {
1279             if dest.align < dest.layout.align.abi {
1280                 // Currently, MIR code generation does not create calls
1281                 // that store directly to fields of packed structs (in
1282                 // fact, the calls it creates write only to temps).
1283                 //
1284                 // If someone changes that, please update this code path
1285                 // to create a temporary.
1286                 span_bug!(self.mir.span, "can't directly store to unaligned value");
1287             }
1288             llargs.push(dest.llval);
1289             ReturnDest::Nothing
1290         } else {
1291             ReturnDest::Store(dest)
1292         }
1293     }
1294
1295     fn codegen_transmute(&mut self, bx: &mut Bx, src: &mir::Operand<'tcx>, dst: mir::Place<'tcx>) {
1296         if let Some(index) = dst.as_local() {
1297             match self.locals[index] {
1298                 LocalRef::Place(place) => self.codegen_transmute_into(bx, src, place),
1299                 LocalRef::UnsizedPlace(_) => bug!("transmute must not involve unsized locals"),
1300                 LocalRef::Operand(None) => {
1301                     let dst_layout = bx.layout_of(self.monomorphized_place_ty(dst.as_ref()));
1302                     assert!(!dst_layout.ty.has_erasable_regions());
1303                     let place = PlaceRef::alloca(bx, dst_layout);
1304                     place.storage_live(bx);
1305                     self.codegen_transmute_into(bx, src, place);
1306                     let op = bx.load_operand(place);
1307                     place.storage_dead(bx);
1308                     self.locals[index] = LocalRef::Operand(Some(op));
1309                     self.debug_introduce_local(bx, index);
1310                 }
1311                 LocalRef::Operand(Some(op)) => {
1312                     assert!(op.layout.is_zst(), "assigning to initialized SSAtemp");
1313                 }
1314             }
1315         } else {
1316             let dst = self.codegen_place(bx, dst.as_ref());
1317             self.codegen_transmute_into(bx, src, dst);
1318         }
1319     }
1320
1321     fn codegen_transmute_into(
1322         &mut self,
1323         bx: &mut Bx,
1324         src: &mir::Operand<'tcx>,
1325         dst: PlaceRef<'tcx, Bx::Value>,
1326     ) {
1327         let src = self.codegen_operand(bx, src);
1328
1329         // Special-case transmutes between scalars as simple bitcasts.
1330         match (&src.layout.abi, &dst.layout.abi) {
1331             (abi::Abi::Scalar(src_scalar), abi::Abi::Scalar(dst_scalar)) => {
1332                 // HACK(eddyb) LLVM doesn't like `bitcast`s between pointers and non-pointers.
1333                 if (src_scalar.value == abi::Pointer) == (dst_scalar.value == abi::Pointer) {
1334                     assert_eq!(src.layout.size, dst.layout.size);
1335
1336                     // NOTE(eddyb) the `from_immediate` and `to_immediate_scalar`
1337                     // conversions allow handling `bool`s the same as `u8`s.
1338                     let src = bx.from_immediate(src.immediate());
1339                     let src_as_dst = bx.bitcast(src, bx.backend_type(dst.layout));
1340                     Immediate(bx.to_immediate_scalar(src_as_dst, dst_scalar)).store(bx, dst);
1341                     return;
1342                 }
1343             }
1344             _ => {}
1345         }
1346
1347         let llty = bx.backend_type(src.layout);
1348         let cast_ptr = bx.pointercast(dst.llval, bx.type_ptr_to(llty));
1349         let align = src.layout.align.abi.min(dst.align);
1350         src.val.store(bx, PlaceRef::new_sized_aligned(cast_ptr, src.layout, align));
1351     }
1352
1353     // Stores the return value of a function call into it's final location.
1354     fn store_return(
1355         &mut self,
1356         bx: &mut Bx,
1357         dest: ReturnDest<'tcx, Bx::Value>,
1358         ret_abi: &ArgAbi<'tcx, Ty<'tcx>>,
1359         llval: Bx::Value,
1360     ) {
1361         use self::ReturnDest::*;
1362
1363         match dest {
1364             Nothing => (),
1365             Store(dst) => bx.store_arg(&ret_abi, llval, dst),
1366             IndirectOperand(tmp, index) => {
1367                 let op = bx.load_operand(tmp);
1368                 tmp.storage_dead(bx);
1369                 self.locals[index] = LocalRef::Operand(Some(op));
1370                 self.debug_introduce_local(bx, index);
1371             }
1372             DirectOperand(index) => {
1373                 // If there is a cast, we have to store and reload.
1374                 let op = if let PassMode::Cast(_) = ret_abi.mode {
1375                     let tmp = PlaceRef::alloca(bx, ret_abi.layout);
1376                     tmp.storage_live(bx);
1377                     bx.store_arg(&ret_abi, llval, tmp);
1378                     let op = bx.load_operand(tmp);
1379                     tmp.storage_dead(bx);
1380                     op
1381                 } else {
1382                     OperandRef::from_immediate_or_packed_pair(bx, llval, ret_abi.layout)
1383                 };
1384                 self.locals[index] = LocalRef::Operand(Some(op));
1385                 self.debug_introduce_local(bx, index);
1386             }
1387         }
1388     }
1389 }
1390
1391 enum ReturnDest<'tcx, V> {
1392     // Do nothing; the return value is indirect or ignored.
1393     Nothing,
1394     // Store the return value to the pointer.
1395     Store(PlaceRef<'tcx, V>),
1396     // Store an indirect return value to an operand local place.
1397     IndirectOperand(PlaceRef<'tcx, V>, mir::Local),
1398     // Store a direct return value to an operand local place.
1399     DirectOperand(mir::Local),
1400 }