]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_ssa/mir/block.rs
Rollup merge of #61705 - petrhosek:llvm-cflags, r=alexcrichton
[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::InterpError;
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::LocalInternedString;
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: 'a, 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);
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);
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 mir::interpret::InterpError::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 = LocalInternedString::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             InterpError::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 str = msg.description();
422                 let msg_str = LocalInternedString::intern(str);
423                 let msg_file_line_col = bx.static_panic_msg(
424                     Some(msg_str),
425                     filename,
426                     line,
427                     col,
428                     "panic_loc",
429                 );
430                 (lang_items::PanicFnLangItem,
431                     vec![msg_file_line_col])
432             }
433         };
434
435         // Obtain the panic entry point.
436         let def_id = common::langcall(bx.tcx(), Some(span), "", lang_item);
437         let instance = ty::Instance::mono(bx.tcx(), def_id);
438         let fn_ty = FnType::of_instance(&bx, &instance);
439         let llfn = bx.get_fn(instance);
440
441         // Codegen the actual panic invoke/call.
442         helper.do_call(self, &mut bx, fn_ty, llfn, &args, None, cleanup);
443     }
444
445     fn codegen_call_terminator<'b>(
446         &mut self,
447         helper: TerminatorCodegenHelper<'b, 'tcx>,
448         mut bx: Bx,
449         terminator: &mir::Terminator<'tcx>,
450         func: &mir::Operand<'tcx>,
451         args: &Vec<mir::Operand<'tcx>>,
452         destination: &Option<(mir::Place<'tcx>, mir::BasicBlock)>,
453         cleanup: Option<mir::BasicBlock>,
454     ) {
455         let span = terminator.source_info.span;
456         // Create the callee. This is a fn ptr or zero-sized and hence a kind of scalar.
457         let callee = self.codegen_operand(&mut bx, func);
458
459         let (instance, mut llfn) = match callee.layout.ty.sty {
460             ty::FnDef(def_id, substs) => {
461                 (Some(ty::Instance::resolve(bx.tcx(),
462                                             ty::ParamEnv::reveal_all(),
463                                             def_id,
464                                             substs).unwrap()),
465                  None)
466             }
467             ty::FnPtr(_) => {
468                 (None, Some(callee.immediate()))
469             }
470             _ => bug!("{} is not callable", callee.layout.ty),
471         };
472         let def = instance.map(|i| i.def);
473         let sig = callee.layout.ty.fn_sig(bx.tcx());
474         let sig = bx.tcx().normalize_erasing_late_bound_regions(
475             ty::ParamEnv::reveal_all(),
476             &sig,
477         );
478         let abi = sig.abi;
479
480         // Handle intrinsics old codegen wants Expr's for, ourselves.
481         let intrinsic = match def {
482             Some(ty::InstanceDef::Intrinsic(def_id)) =>
483                 Some(bx.tcx().item_name(def_id).as_str()),
484             _ => None
485         };
486         let intrinsic = intrinsic.as_ref().map(|s| &s[..]);
487
488         if intrinsic == Some("transmute") {
489             if let Some(destination_ref) = destination.as_ref() {
490                 let &(ref dest, target) = destination_ref;
491                 self.codegen_transmute(&mut bx, &args[0], dest);
492                 helper.funclet_br(self, &mut bx, target);
493             } else {
494                 // If we are trying to transmute to an uninhabited type,
495                 // it is likely there is no allotted destination. In fact,
496                 // transmuting to an uninhabited type is UB, which means
497                 // we can do what we like. Here, we declare that transmuting
498                 // into an uninhabited type is impossible, so anything following
499                 // it must be unreachable.
500                 assert_eq!(bx.layout_of(sig.output()).abi, layout::Abi::Uninhabited);
501                 bx.unreachable();
502             }
503             return;
504         }
505
506         // The "spoofed" `VaList` added to a C-variadic functions signature
507         // should not be included in the `extra_args` calculation.
508         let extra_args_start_idx = sig.inputs().len() - if sig.c_variadic { 1 } else { 0 };
509         let extra_args = &args[extra_args_start_idx..];
510         let extra_args = extra_args.iter().map(|op_arg| {
511             let op_ty = op_arg.ty(self.mir, bx.tcx());
512             self.monomorphize(&op_ty)
513         }).collect::<Vec<_>>();
514
515         let fn_ty = match def {
516             Some(ty::InstanceDef::Virtual(..)) => {
517                 FnType::new_vtable(&bx, sig, &extra_args)
518             }
519             Some(ty::InstanceDef::DropGlue(_, None)) => {
520                 // Empty drop glue; a no-op.
521                 let &(_, target) = destination.as_ref().unwrap();
522                 helper.funclet_br(self, &mut bx, target);
523                 return;
524             }
525             _ => FnType::new(&bx, sig, &extra_args)
526         };
527
528         // Emit a panic or a no-op for `panic_if_uninhabited`.
529         if intrinsic == Some("panic_if_uninhabited") {
530             let ty = instance.unwrap().substs.type_at(0);
531             let layout = bx.layout_of(ty);
532             if layout.abi.is_uninhabited() {
533                 let loc = bx.sess().source_map().lookup_char_pos(span.lo());
534                 let filename = LocalInternedString::intern(&loc.file.name.to_string());
535                 let line = bx.const_u32(loc.line as u32);
536                 let col = bx.const_u32(loc.col.to_usize() as u32 + 1);
537
538                 let str = format!(
539                     "Attempted to instantiate uninhabited type {}",
540                     ty
541                 );
542                 let msg_str = LocalInternedString::intern(&str);
543                 let msg_file_line_col = bx.static_panic_msg(
544                     Some(msg_str),
545                     filename,
546                     line,
547                     col,
548                     "panic_loc",
549                 );
550
551                 // Obtain the panic entry point.
552                 let def_id =
553                     common::langcall(bx.tcx(), Some(span), "", lang_items::PanicFnLangItem);
554                 let instance = ty::Instance::mono(bx.tcx(), def_id);
555                 let fn_ty = FnType::of_instance(&bx, &instance);
556                 let llfn = bx.get_fn(instance);
557
558                 // Codegen the actual panic invoke/call.
559                 helper.do_call(
560                     self,
561                     &mut bx,
562                     fn_ty,
563                     llfn,
564                     &[msg_file_line_col],
565                     destination.as_ref().map(|(_, bb)| (ReturnDest::Nothing, *bb)),
566                     cleanup,
567                 );
568             } else {
569                 // a NOP
570                 helper.funclet_br(self, &mut bx, destination.as_ref().unwrap().1)
571             }
572             return;
573         }
574
575         // The arguments we'll be passing. Plus one to account for outptr, if used.
576         let arg_count = fn_ty.args.len() + fn_ty.ret.is_indirect() as usize;
577         let mut llargs = Vec::with_capacity(arg_count);
578
579         // Prepare the return value destination
580         let ret_dest = if let Some((ref dest, _)) = *destination {
581             let is_intrinsic = intrinsic.is_some();
582             self.make_return_dest(&mut bx, dest, &fn_ty.ret, &mut llargs,
583                                   is_intrinsic)
584         } else {
585             ReturnDest::Nothing
586         };
587
588         if intrinsic.is_some() && intrinsic != Some("drop_in_place") {
589             let dest = match ret_dest {
590                 _ if fn_ty.ret.is_indirect() => llargs[0],
591                 ReturnDest::Nothing =>
592                     bx.const_undef(bx.type_ptr_to(bx.memory_ty(&fn_ty.ret))),
593                 ReturnDest::IndirectOperand(dst, _) | ReturnDest::Store(dst) =>
594                     dst.llval,
595                 ReturnDest::DirectOperand(_) =>
596                     bug!("Cannot use direct operand with an intrinsic call"),
597             };
598
599             let args: Vec<_> = args.iter().enumerate().map(|(i, arg)| {
600                 // The indices passed to simd_shuffle* in the
601                 // third argument must be constant. This is
602                 // checked by const-qualification, which also
603                 // promotes any complex rvalues to constants.
604                 if i == 2 && intrinsic.unwrap().starts_with("simd_shuffle") {
605                     match *arg {
606                         // The shuffle array argument is usually not an explicit constant,
607                         // but specified directly in the code. This means it gets promoted
608                         // and we can then extract the value by evaluating the promoted.
609                         mir::Operand::Copy(
610                             Place::Base(
611                                 PlaceBase::Static(
612                                     box Static { kind: StaticKind::Promoted(promoted), ty }
613                                 )
614                             )
615                         ) |
616                         mir::Operand::Move(
617                             Place::Base(
618                                 PlaceBase::Static(
619                                     box Static { kind: StaticKind::Promoted(promoted), ty }
620                                 )
621                             )
622                         ) => {
623                             let param_env = ty::ParamEnv::reveal_all();
624                             let cid = mir::interpret::GlobalId {
625                                 instance: self.instance,
626                                 promoted: Some(promoted),
627                             };
628                             let c = bx.tcx().const_eval(param_env.and(cid));
629                             let (llval, ty) = self.simd_shuffle_indices(
630                                 &bx,
631                                 terminator.source_info.span,
632                                 ty,
633                                 c,
634                             );
635                             return OperandRef {
636                                 val: Immediate(llval),
637                                 layout: bx.layout_of(ty),
638                             };
639
640                         }
641                         mir::Operand::Copy(_) |
642                         mir::Operand::Move(_) => {
643                             span_bug!(span, "shuffle indices must be constant");
644                         }
645                         mir::Operand::Constant(ref constant) => {
646                             let c = self.eval_mir_constant(constant);
647                             let (llval, ty) = self.simd_shuffle_indices(
648                                 &bx,
649                                 constant.span,
650                                 constant.ty,
651                                 c,
652                             );
653                             return OperandRef {
654                                 val: Immediate(llval),
655                                 layout: bx.layout_of(ty)
656                             };
657                         }
658                     }
659                 }
660
661                 self.codegen_operand(&mut bx, arg)
662             }).collect();
663
664
665             let callee_ty = instance.as_ref().unwrap().ty(bx.tcx());
666             bx.codegen_intrinsic_call(callee_ty, &fn_ty, &args, dest,
667                                       terminator.source_info.span);
668
669             if let ReturnDest::IndirectOperand(dst, _) = ret_dest {
670                 self.store_return(&mut bx, ret_dest, &fn_ty.ret, dst.llval);
671             }
672
673             if let Some((_, target)) = *destination {
674                 helper.funclet_br(self, &mut bx, target);
675             } else {
676                 bx.unreachable();
677             }
678
679             return;
680         }
681
682         // Split the rust-call tupled arguments off.
683         let (first_args, untuple) = if abi == Abi::RustCall && !args.is_empty() {
684             let (tup, args) = args.split_last().unwrap();
685             (args, Some(tup))
686         } else {
687             (&args[..], None)
688         };
689
690         // Useful determining if the current argument is the "spoofed" `VaList`
691         let last_arg_idx = if sig.inputs().is_empty() {
692             None
693         } else {
694             Some(sig.inputs().len() - 1)
695         };
696         'make_args: for (i, arg) in first_args.iter().enumerate() {
697             // If this is a C-variadic function the function signature contains
698             // an "spoofed" `VaList`. This argument is ignored, but we need to
699             // populate it with a dummy operand so that the users real arguments
700             // are not overwritten.
701             let i = if sig.c_variadic && last_arg_idx.map(|x| i >= x).unwrap_or(false) {
702                 if i + 1 < fn_ty.args.len() {
703                     i + 1
704                 } else {
705                     break 'make_args
706                 }
707             } else {
708                 i
709             };
710             let mut op = self.codegen_operand(&mut bx, arg);
711
712             if let (0, Some(ty::InstanceDef::Virtual(_, idx))) = (i, def) {
713                 if let Pair(..) = op.val {
714                     // In the case of Rc<Self>, we need to explicitly pass a
715                     // *mut RcBox<Self> with a Scalar (not ScalarPair) ABI. This is a hack
716                     // that is understood elsewhere in the compiler as a method on
717                     // `dyn Trait`.
718                     // To get a `*mut RcBox<Self>`, we just keep unwrapping newtypes until
719                     // we get a value of a built-in pointer type
720                     'descend_newtypes: while !op.layout.ty.is_unsafe_ptr()
721                                     && !op.layout.ty.is_region_ptr()
722                     {
723                         'iter_fields: for i in 0..op.layout.fields.count() {
724                             let field = op.extract_field(&mut bx, i);
725                             if !field.layout.is_zst() {
726                                 // we found the one non-zero-sized field that is allowed
727                                 // now find *its* non-zero-sized field, or stop if it's a
728                                 // pointer
729                                 op = field;
730                                 continue 'descend_newtypes
731                             }
732                         }
733
734                         span_bug!(span, "receiver has no non-zero-sized fields {:?}", op);
735                     }
736
737                     // now that we have `*dyn Trait` or `&dyn Trait`, split it up into its
738                     // data pointer and vtable. Look up the method in the vtable, and pass
739                     // the data pointer as the first argument
740                     match op.val {
741                         Pair(data_ptr, meta) => {
742                             llfn = Some(meth::VirtualIndex::from_index(idx)
743                                 .get_fn(&mut bx, meta, &fn_ty));
744                             llargs.push(data_ptr);
745                             continue 'make_args
746                         }
747                         other => bug!("expected a Pair, got {:?}", other),
748                     }
749                 } else if let Ref(data_ptr, Some(meta), _) = op.val {
750                     // by-value dynamic dispatch
751                     llfn = Some(meth::VirtualIndex::from_index(idx)
752                         .get_fn(&mut bx, meta, &fn_ty));
753                     llargs.push(data_ptr);
754                     continue;
755                 } else {
756                     span_bug!(span, "can't codegen a virtual call on {:?}", op);
757                 }
758             }
759
760             // The callee needs to own the argument memory if we pass it
761             // by-ref, so make a local copy of non-immediate constants.
762             match (arg, op.val) {
763                 (&mir::Operand::Copy(_), Ref(_, None, _)) |
764                 (&mir::Operand::Constant(_), Ref(_, None, _)) => {
765                     let tmp = PlaceRef::alloca(&mut bx, op.layout, "const");
766                     op.val.store(&mut bx, tmp);
767                     op.val = Ref(tmp.llval, None, tmp.align);
768                 }
769                 _ => {}
770             }
771
772             self.codegen_argument(&mut bx, op, &mut llargs, &fn_ty.args[i]);
773         }
774         if let Some(tup) = untuple {
775             self.codegen_arguments_untupled(&mut bx, tup, &mut llargs,
776                 &fn_ty.args[first_args.len()..])
777         }
778
779         let fn_ptr = match (llfn, instance) {
780             (Some(llfn), _) => llfn,
781             (None, Some(instance)) => bx.get_fn(instance),
782             _ => span_bug!(span, "no llfn for call"),
783         };
784
785         helper.do_call(self, &mut bx, fn_ty, fn_ptr, &llargs,
786                        destination.as_ref().map(|&(_, target)| (ret_dest, target)),
787                        cleanup);
788     }
789 }
790
791 impl<'a, 'tcx: 'a, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
792     pub fn codegen_block(
793         &mut self,
794         bb: mir::BasicBlock,
795     ) {
796         let mut bx = self.build_block(bb);
797         let data = &self.mir[bb];
798
799         debug!("codegen_block({:?}={:?})", bb, data);
800
801         for statement in &data.statements {
802             bx = self.codegen_statement(bx, statement);
803         }
804
805         self.codegen_terminator(bx, bb, data.terminator());
806     }
807
808     fn codegen_terminator(
809         &mut self,
810         mut bx: Bx,
811         bb: mir::BasicBlock,
812         terminator: &mir::Terminator<'tcx>
813     ) {
814         debug!("codegen_terminator: {:?}", terminator);
815
816         // Create the cleanup bundle, if needed.
817         let funclet_bb = self.cleanup_kinds[bb].funclet_bb(bb);
818         let helper = TerminatorCodegenHelper {
819             bb: &bb, terminator, funclet_bb
820         };
821
822         self.set_debug_loc(&mut bx, terminator.source_info);
823         match terminator.kind {
824             mir::TerminatorKind::Resume => {
825                 self.codegen_resume_terminator(helper, bx)
826             }
827
828             mir::TerminatorKind::Abort => {
829                 bx.abort();
830                 bx.unreachable();
831             }
832
833             mir::TerminatorKind::Goto { target } => {
834                 helper.funclet_br(self, &mut bx, target);
835             }
836
837             mir::TerminatorKind::SwitchInt {
838                 ref discr, switch_ty, ref values, ref targets
839             } => {
840                 self.codegen_switchint_terminator(helper, bx, discr, switch_ty,
841                                                   values, targets);
842             }
843
844             mir::TerminatorKind::Return => {
845                 self.codegen_return_terminator(bx);
846             }
847
848             mir::TerminatorKind::Unreachable => {
849                 bx.unreachable();
850             }
851
852             mir::TerminatorKind::Drop { ref location, target, unwind } => {
853                 self.codegen_drop_terminator(helper, bx, location, target, unwind);
854             }
855
856             mir::TerminatorKind::Assert { ref cond, expected, ref msg, target, cleanup } => {
857                 self.codegen_assert_terminator(helper, bx, terminator, cond,
858                                                expected, msg, target, cleanup);
859             }
860
861             mir::TerminatorKind::DropAndReplace { .. } => {
862                 bug!("undesugared DropAndReplace in codegen: {:?}", terminator);
863             }
864
865             mir::TerminatorKind::Call {
866                 ref func,
867                 ref args,
868                 ref destination,
869                 cleanup,
870                 from_hir_call: _
871             } => {
872                 self.codegen_call_terminator(helper, bx, terminator, func,
873                                              args, destination, cleanup);
874             }
875             mir::TerminatorKind::GeneratorDrop |
876             mir::TerminatorKind::Yield { .. } => bug!("generator ops in codegen"),
877             mir::TerminatorKind::FalseEdges { .. } |
878             mir::TerminatorKind::FalseUnwind { .. } => bug!("borrowck false edges in codegen"),
879         }
880     }
881
882     fn codegen_argument(
883         &mut self,
884         bx: &mut Bx,
885         op: OperandRef<'tcx, Bx::Value>,
886         llargs: &mut Vec<Bx::Value>,
887         arg: &ArgType<'tcx, Ty<'tcx>>
888     ) {
889         // Fill padding with undef value, where applicable.
890         if let Some(ty) = arg.pad {
891             llargs.push(bx.const_undef(bx.reg_backend_type(&ty)))
892         }
893
894         if arg.is_ignore() {
895             return;
896         }
897
898         if let PassMode::Pair(..) = arg.mode {
899             match op.val {
900                 Pair(a, b) => {
901                     llargs.push(a);
902                     llargs.push(b);
903                     return;
904                 }
905                 _ => bug!("codegen_argument: {:?} invalid for pair argument", op)
906             }
907         } else if arg.is_unsized_indirect() {
908             match op.val {
909                 Ref(a, Some(b), _) => {
910                     llargs.push(a);
911                     llargs.push(b);
912                     return;
913                 }
914                 _ => bug!("codegen_argument: {:?} invalid for unsized indirect argument", op)
915             }
916         }
917
918         // Force by-ref if we have to load through a cast pointer.
919         let (mut llval, align, by_ref) = match op.val {
920             Immediate(_) | Pair(..) => {
921                 match arg.mode {
922                     PassMode::Indirect(..) | PassMode::Cast(_) => {
923                         let scratch = PlaceRef::alloca(bx, arg.layout, "arg");
924                         op.val.store(bx, scratch);
925                         (scratch.llval, scratch.align, true)
926                     }
927                     _ => {
928                         (op.immediate_or_packed_pair(bx), arg.layout.align.abi, false)
929                     }
930                 }
931             }
932             Ref(llval, _, align) => {
933                 if arg.is_indirect() && align < arg.layout.align.abi {
934                     // `foo(packed.large_field)`. We can't pass the (unaligned) field directly. I
935                     // think that ATM (Rust 1.16) we only pass temporaries, but we shouldn't
936                     // have scary latent bugs around.
937
938                     let scratch = PlaceRef::alloca(bx, arg.layout, "arg");
939                     base::memcpy_ty(bx, scratch.llval, scratch.align, llval, align,
940                                     op.layout, MemFlags::empty());
941                     (scratch.llval, scratch.align, true)
942                 } else {
943                     (llval, align, true)
944                 }
945             }
946         };
947
948         if by_ref && !arg.is_indirect() {
949             // Have to load the argument, maybe while casting it.
950             if let PassMode::Cast(ty) = arg.mode {
951                 let addr = bx.pointercast(llval, bx.type_ptr_to(
952                     bx.cast_backend_type(&ty))
953                 );
954                 llval = bx.load(addr, align.min(arg.layout.align.abi));
955             } else {
956                 // We can't use `PlaceRef::load` here because the argument
957                 // may have a type we don't treat as immediate, but the ABI
958                 // used for this call is passing it by-value. In that case,
959                 // the load would just produce `OperandValue::Ref` instead
960                 // of the `OperandValue::Immediate` we need for the call.
961                 llval = bx.load(llval, align);
962                 if let layout::Abi::Scalar(ref scalar) = arg.layout.abi {
963                     if scalar.is_bool() {
964                         bx.range_metadata(llval, 0..2);
965                     }
966                 }
967                 // We store bools as `i8` so we need to truncate to `i1`.
968                 llval = base::to_immediate(bx, llval, arg.layout);
969             }
970         }
971
972         llargs.push(llval);
973     }
974
975     fn codegen_arguments_untupled(
976         &mut self,
977         bx: &mut Bx,
978         operand: &mir::Operand<'tcx>,
979         llargs: &mut Vec<Bx::Value>,
980         args: &[ArgType<'tcx, Ty<'tcx>>]
981     ) {
982         let tuple = self.codegen_operand(bx, operand);
983
984         // Handle both by-ref and immediate tuples.
985         if let Ref(llval, None, align) = tuple.val {
986             let tuple_ptr = PlaceRef::new_sized(llval, tuple.layout, align);
987             for i in 0..tuple.layout.fields.count() {
988                 let field_ptr = tuple_ptr.project_field(bx, i);
989                 let field = bx.load_operand(field_ptr);
990                 self.codegen_argument(bx, field, llargs, &args[i]);
991             }
992         } else if let Ref(_, Some(_), _) = tuple.val {
993             bug!("closure arguments must be sized")
994         } else {
995             // If the tuple is immediate, the elements are as well.
996             for i in 0..tuple.layout.fields.count() {
997                 let op = tuple.extract_field(bx, i);
998                 self.codegen_argument(bx, op, llargs, &args[i]);
999             }
1000         }
1001     }
1002
1003     fn get_personality_slot(
1004         &mut self,
1005         bx: &mut Bx
1006     ) -> PlaceRef<'tcx, Bx::Value> {
1007         let cx = bx.cx();
1008         if let Some(slot) = self.personality_slot {
1009             slot
1010         } else {
1011             let layout = cx.layout_of(cx.tcx().intern_tup(&[
1012                 cx.tcx().mk_mut_ptr(cx.tcx().types.u8),
1013                 cx.tcx().types.i32
1014             ]));
1015             let slot = PlaceRef::alloca(bx, layout, "personalityslot");
1016             self.personality_slot = Some(slot);
1017             slot
1018         }
1019     }
1020
1021     /// Returns the landing-pad wrapper around the given basic block.
1022     ///
1023     /// No-op in MSVC SEH scheme.
1024     fn landing_pad_to(
1025         &mut self,
1026         target_bb: mir::BasicBlock
1027     ) -> Bx::BasicBlock {
1028         if let Some(block) = self.landing_pads[target_bb] {
1029             return block;
1030         }
1031
1032         let block = self.blocks[target_bb];
1033         let landing_pad = self.landing_pad_uncached(block);
1034         self.landing_pads[target_bb] = Some(landing_pad);
1035         landing_pad
1036     }
1037
1038     fn landing_pad_uncached(
1039         &mut self,
1040         target_bb: Bx::BasicBlock
1041     ) -> Bx::BasicBlock {
1042         if base::wants_msvc_seh(self.cx.sess()) {
1043             span_bug!(self.mir.span, "landing pad was not inserted?")
1044         }
1045
1046         let mut bx = self.new_block("cleanup");
1047
1048         let llpersonality = self.cx.eh_personality();
1049         let llretty = self.landing_pad_type();
1050         let lp = bx.landing_pad(llretty, llpersonality, 1);
1051         bx.set_cleanup(lp);
1052
1053         let slot = self.get_personality_slot(&mut bx);
1054         slot.storage_live(&mut bx);
1055         Pair(bx.extract_value(lp, 0), bx.extract_value(lp, 1)).store(&mut bx, slot);
1056
1057         bx.br(target_bb);
1058         bx.llbb()
1059     }
1060
1061     fn landing_pad_type(&self) -> Bx::Type {
1062         let cx = self.cx;
1063         cx.type_struct(&[cx.type_i8p(), cx.type_i32()], false)
1064     }
1065
1066     fn unreachable_block(
1067         &mut self
1068     ) -> Bx::BasicBlock {
1069         self.unreachable_block.unwrap_or_else(|| {
1070             let mut bx = self.new_block("unreachable");
1071             bx.unreachable();
1072             self.unreachable_block = Some(bx.llbb());
1073             bx.llbb()
1074         })
1075     }
1076
1077     pub fn new_block(&self, name: &str) -> Bx {
1078         Bx::new_block(self.cx, self.llfn, name)
1079     }
1080
1081     pub fn build_block(
1082         &self,
1083         bb: mir::BasicBlock
1084     ) -> Bx {
1085         let mut bx = Bx::with_cx(self.cx);
1086         bx.position_at_end(self.blocks[bb]);
1087         bx
1088     }
1089
1090     fn make_return_dest(
1091         &mut self,
1092         bx: &mut Bx,
1093         dest: &mir::Place<'tcx>,
1094         fn_ret: &ArgType<'tcx, Ty<'tcx>>,
1095         llargs: &mut Vec<Bx::Value>, is_intrinsic: bool
1096     ) -> ReturnDest<'tcx, Bx::Value> {
1097         // If the return is ignored, we can just return a do-nothing `ReturnDest`.
1098         if fn_ret.is_ignore() {
1099             return ReturnDest::Nothing;
1100         }
1101         let dest = if let mir::Place::Base(mir::PlaceBase::Local(index)) = *dest {
1102             match self.locals[index] {
1103                 LocalRef::Place(dest) => dest,
1104                 LocalRef::UnsizedPlace(_) => bug!("return type must be sized"),
1105                 LocalRef::Operand(None) => {
1106                     // Handle temporary places, specifically `Operand` ones, as
1107                     // they don't have `alloca`s.
1108                     return if fn_ret.is_indirect() {
1109                         // Odd, but possible, case, we have an operand temporary,
1110                         // but the calling convention has an indirect return.
1111                         let tmp = PlaceRef::alloca(bx, fn_ret.layout, "tmp_ret");
1112                         tmp.storage_live(bx);
1113                         llargs.push(tmp.llval);
1114                         ReturnDest::IndirectOperand(tmp, index)
1115                     } else if is_intrinsic {
1116                         // Currently, intrinsics always need a location to store
1117                         // the result, so we create a temporary `alloca` for the
1118                         // result.
1119                         let tmp = PlaceRef::alloca(bx, fn_ret.layout, "tmp_ret");
1120                         tmp.storage_live(bx);
1121                         ReturnDest::IndirectOperand(tmp, index)
1122                     } else {
1123                         ReturnDest::DirectOperand(index)
1124                     };
1125                 }
1126                 LocalRef::Operand(Some(_)) => {
1127                     bug!("place local already assigned to");
1128                 }
1129             }
1130         } else {
1131             self.codegen_place(bx, dest)
1132         };
1133         if fn_ret.is_indirect() {
1134             if dest.align < dest.layout.align.abi {
1135                 // Currently, MIR code generation does not create calls
1136                 // that store directly to fields of packed structs (in
1137                 // fact, the calls it creates write only to temps).
1138                 //
1139                 // If someone changes that, please update this code path
1140                 // to create a temporary.
1141                 span_bug!(self.mir.span, "can't directly store to unaligned value");
1142             }
1143             llargs.push(dest.llval);
1144             ReturnDest::Nothing
1145         } else {
1146             ReturnDest::Store(dest)
1147         }
1148     }
1149
1150     fn codegen_transmute(
1151         &mut self,
1152         bx: &mut Bx,
1153         src: &mir::Operand<'tcx>,
1154         dst: &mir::Place<'tcx>
1155     ) {
1156         if let mir::Place::Base(mir::PlaceBase::Local(index)) = *dst {
1157             match self.locals[index] {
1158                 LocalRef::Place(place) => self.codegen_transmute_into(bx, src, place),
1159                 LocalRef::UnsizedPlace(_) => bug!("transmute must not involve unsized locals"),
1160                 LocalRef::Operand(None) => {
1161                     let dst_layout = bx.layout_of(self.monomorphized_place_ty(dst));
1162                     assert!(!dst_layout.ty.has_erasable_regions());
1163                     let place = PlaceRef::alloca(bx, dst_layout, "transmute_temp");
1164                     place.storage_live(bx);
1165                     self.codegen_transmute_into(bx, src, place);
1166                     let op = bx.load_operand(place);
1167                     place.storage_dead(bx);
1168                     self.locals[index] = LocalRef::Operand(Some(op));
1169                 }
1170                 LocalRef::Operand(Some(op)) => {
1171                     assert!(op.layout.is_zst(),
1172                             "assigning to initialized SSAtemp");
1173                 }
1174             }
1175         } else {
1176             let dst = self.codegen_place(bx, dst);
1177             self.codegen_transmute_into(bx, src, dst);
1178         }
1179     }
1180
1181     fn codegen_transmute_into(
1182         &mut self,
1183         bx: &mut Bx,
1184         src: &mir::Operand<'tcx>,
1185         dst: PlaceRef<'tcx, Bx::Value>
1186     ) {
1187         let src = self.codegen_operand(bx, src);
1188         let llty = bx.backend_type(src.layout);
1189         let cast_ptr = bx.pointercast(dst.llval, bx.type_ptr_to(llty));
1190         let align = src.layout.align.abi.min(dst.align);
1191         src.val.store(bx, PlaceRef::new_sized(cast_ptr, src.layout, align));
1192     }
1193
1194
1195     // Stores the return value of a function call into it's final location.
1196     fn store_return(
1197         &mut self,
1198         bx: &mut Bx,
1199         dest: ReturnDest<'tcx, Bx::Value>,
1200         ret_ty: &ArgType<'tcx, Ty<'tcx>>,
1201         llval: Bx::Value
1202     ) {
1203         use self::ReturnDest::*;
1204
1205         match dest {
1206             Nothing => (),
1207             Store(dst) => bx.store_arg_ty(&ret_ty, llval, dst),
1208             IndirectOperand(tmp, index) => {
1209                 let op = bx.load_operand(tmp);
1210                 tmp.storage_dead(bx);
1211                 self.locals[index] = LocalRef::Operand(Some(op));
1212             }
1213             DirectOperand(index) => {
1214                 // If there is a cast, we have to store and reload.
1215                 let op = if let PassMode::Cast(_) = ret_ty.mode {
1216                     let tmp = PlaceRef::alloca(bx, ret_ty.layout, "tmp_ret");
1217                     tmp.storage_live(bx);
1218                     bx.store_arg_ty(&ret_ty, llval, tmp);
1219                     let op = bx.load_operand(tmp);
1220                     tmp.storage_dead(bx);
1221                     op
1222                 } else {
1223                     OperandRef::from_immediate_or_packed_pair(bx, llval, ret_ty.layout)
1224                 };
1225                 self.locals[index] = LocalRef::Operand(Some(op));
1226             }
1227         }
1228     }
1229 }
1230
1231 enum ReturnDest<'tcx, V> {
1232     // Do nothing; the return value is indirect or ignored.
1233     Nothing,
1234     // Store the return value to the pointer.
1235     Store(PlaceRef<'tcx, V>),
1236     // Store an indirect return value to an operand local place.
1237     IndirectOperand(PlaceRef<'tcx, V>, mir::Local),
1238     // Store a direct return value to an operand local place.
1239     DirectOperand(mir::Local)
1240 }