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