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