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