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