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