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