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