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