]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/mir/block.rs
Rollup merge of #39604 - est31:i128_tests, r=alexcrichton
[rust.git] / src / librustc_trans / 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, ValueRef, BasicBlockRef};
12 use rustc_const_eval::{ErrKind, ConstEvalErr, note_const_eval_err};
13 use rustc::middle::lang_items;
14 use rustc::ty::{self, layout, TypeFoldable};
15 use rustc::mir;
16 use abi::{Abi, FnType, ArgType};
17 use adt;
18 use base::{self, Lifetime};
19 use callee::{Callee, CalleeData, Fn, Intrinsic, NamedTupleConstructor, Virtual};
20 use builder::Builder;
21 use common::{self, Funclet};
22 use common::{C_bool, C_str_slice, C_struct, C_u32, C_undef};
23 use consts;
24 use Disr;
25 use machine::{llalign_of_min, llbitsize_of_real};
26 use meth;
27 use type_of::{self, align_of};
28 use glue;
29 use type_::Type;
30
31 use rustc_data_structures::indexed_vec::IndexVec;
32 use rustc_data_structures::fx::FxHashMap;
33 use syntax::symbol::Symbol;
34
35 use std::cmp;
36
37 use super::{MirContext, LocalRef};
38 use super::analyze::CleanupKind;
39 use super::constant::Const;
40 use super::lvalue::{Alignment, LvalueRef};
41 use super::operand::OperandRef;
42 use super::operand::OperandValue::{Pair, Ref, Immediate};
43
44 impl<'a, 'tcx> MirContext<'a, 'tcx> {
45     pub fn trans_block(&mut self, bb: mir::BasicBlock,
46         funclets: &IndexVec<mir::BasicBlock, Option<Funclet>>) {
47         let mut bcx = self.get_builder(bb);
48         let data = &self.mir[bb];
49
50         debug!("trans_block({:?}={:?})", bb, data);
51
52         let funclet = match self.cleanup_kinds[bb] {
53             CleanupKind::Internal { funclet } => funclets[funclet].as_ref(),
54             _ => funclets[bb].as_ref(),
55         };
56
57         // Create the cleanup bundle, if needed.
58         let cleanup_pad = funclet.map(|lp| lp.cleanuppad());
59         let cleanup_bundle = funclet.map(|l| l.bundle());
60
61         let funclet_br = |this: &Self, bcx: Builder, bb: mir::BasicBlock| {
62             let lltarget = this.blocks[bb];
63             if let Some(cp) = cleanup_pad {
64                 match this.cleanup_kinds[bb] {
65                     CleanupKind::Funclet => {
66                         // micro-optimization: generate a `ret` rather than a jump
67                         // to a return block
68                         bcx.cleanup_ret(cp, Some(lltarget));
69                     }
70                     CleanupKind::Internal { .. } => bcx.br(lltarget),
71                     CleanupKind::NotCleanup => bug!("jump from cleanup bb to bb {:?}", bb)
72                 }
73             } else {
74                 bcx.br(lltarget);
75             }
76         };
77
78         let llblock = |this: &mut Self, target: mir::BasicBlock| {
79             let lltarget = this.blocks[target];
80
81             if let Some(cp) = cleanup_pad {
82                 match this.cleanup_kinds[target] {
83                     CleanupKind::Funclet => {
84                         // MSVC cross-funclet jump - need a trampoline
85
86                         debug!("llblock: creating cleanup trampoline for {:?}", target);
87                         let name = &format!("{:?}_cleanup_trampoline_{:?}", bb, target);
88                         let trampoline = this.new_block(name);
89                         trampoline.cleanup_ret(cp, Some(lltarget));
90                         trampoline.llbb()
91                     }
92                     CleanupKind::Internal { .. } => lltarget,
93                     CleanupKind::NotCleanup =>
94                         bug!("jump from cleanup bb {:?} to bb {:?}", bb, target)
95                 }
96             } else {
97                 if let (CleanupKind::NotCleanup, CleanupKind::Funclet) =
98                     (this.cleanup_kinds[bb], this.cleanup_kinds[target])
99                 {
100                     // jump *into* cleanup - need a landing pad if GNU
101                     this.landing_pad_to(target)
102                 } else {
103                     lltarget
104                 }
105             }
106         };
107
108         for statement in &data.statements {
109             bcx = self.trans_statement(bcx, statement);
110         }
111
112         let terminator = data.terminator();
113         debug!("trans_block: terminator: {:?}", terminator);
114
115         let span = terminator.source_info.span;
116         self.set_debug_loc(&bcx, terminator.source_info);
117         match terminator.kind {
118             mir::TerminatorKind::Resume => {
119                 if let Some(cleanup_pad) = cleanup_pad {
120                     bcx.cleanup_ret(cleanup_pad, None);
121                 } else {
122                     let ps = self.get_personality_slot(&bcx);
123                     let lp = bcx.load(ps, None);
124                     Lifetime::End.call(&bcx, ps);
125                     if !bcx.sess().target.target.options.custom_unwind_resume {
126                         bcx.resume(lp);
127                     } else {
128                         let exc_ptr = bcx.extract_value(lp, 0);
129                         bcx.call(bcx.ccx.eh_unwind_resume(), &[exc_ptr], cleanup_bundle);
130                         bcx.unreachable();
131                     }
132                 }
133             }
134
135             mir::TerminatorKind::Goto { target } => {
136                 funclet_br(self, bcx, target);
137             }
138
139             mir::TerminatorKind::If { ref cond, targets: (true_bb, false_bb) } => {
140                 let cond = self.trans_operand(&bcx, cond);
141
142                 let lltrue = llblock(self, true_bb);
143                 let llfalse = llblock(self, false_bb);
144                 bcx.cond_br(cond.immediate(), lltrue, llfalse);
145             }
146
147             mir::TerminatorKind::Switch { ref discr, ref adt_def, ref targets } => {
148                 let discr_lvalue = self.trans_lvalue(&bcx, discr);
149                 let ty = discr_lvalue.ty.to_ty(bcx.tcx());
150                 let discr = adt::trans_get_discr(
151                     &bcx, ty, discr_lvalue.llval, discr_lvalue.alignment,
152                     None, true);
153
154                 let mut bb_hist = FxHashMap();
155                 for target in targets {
156                     *bb_hist.entry(target).or_insert(0) += 1;
157                 }
158                 let (default_bb, default_blk) = match bb_hist.iter().max_by_key(|&(_, c)| c) {
159                     // If a single target basic blocks is predominant, promote that to be the
160                     // default case for the switch instruction to reduce the size of the generated
161                     // code. This is especially helpful in cases like an if-let on a huge enum.
162                     // Note: This optimization is only valid for exhaustive matches.
163                     Some((&&bb, &c)) if c > targets.len() / 2 => {
164                         (Some(bb), llblock(self, bb))
165                     }
166                     // We're generating an exhaustive switch, so the else branch
167                     // can't be hit.  Branching to an unreachable instruction
168                     // lets LLVM know this
169                     _ => (None, self.unreachable_block())
170                 };
171                 let switch = bcx.switch(discr, default_blk, targets.len());
172                 assert_eq!(adt_def.variants.len(), targets.len());
173                 for (adt_variant, &target) in adt_def.variants.iter().zip(targets) {
174                     if default_bb != Some(target) {
175                         let llbb = llblock(self, target);
176                         let llval = adt::trans_case(&bcx, ty, Disr::from(adt_variant.disr_val));
177                         bcx.add_case(switch, llval, llbb)
178                     }
179                 }
180             }
181
182             mir::TerminatorKind::SwitchInt { ref discr, switch_ty, ref values, ref targets } => {
183                 let (otherwise, targets) = targets.split_last().unwrap();
184                 let lv = self.trans_lvalue(&bcx, discr);
185                 let discr = bcx.load(lv.llval, lv.alignment.to_align());
186                 let discr = base::to_immediate(&bcx, discr, switch_ty);
187                 let switch = bcx.switch(discr, llblock(self, *otherwise), values.len());
188                 for (value, target) in values.iter().zip(targets) {
189                     let val = Const::from_constval(bcx.ccx, value.clone(), switch_ty);
190                     let llbb = llblock(self, *target);
191                     bcx.add_case(switch, val.llval, llbb)
192                 }
193             }
194
195             mir::TerminatorKind::Return => {
196                 let ret = self.fn_ty.ret;
197                 if ret.is_ignore() || ret.is_indirect() {
198                     bcx.ret_void();
199                     return;
200                 }
201
202                 let llval = if let Some(cast_ty) = ret.cast {
203                     let op = match self.locals[mir::RETURN_POINTER] {
204                         LocalRef::Operand(Some(op)) => op,
205                         LocalRef::Operand(None) => bug!("use of return before def"),
206                         LocalRef::Lvalue(tr_lvalue) => {
207                             OperandRef {
208                                 val: Ref(tr_lvalue.llval, tr_lvalue.alignment),
209                                 ty: tr_lvalue.ty.to_ty(bcx.tcx())
210                             }
211                         }
212                     };
213                     let llslot = match op.val {
214                         Immediate(_) | Pair(..) => {
215                             let llscratch = bcx.alloca(ret.original_ty, "ret");
216                             self.store_operand(&bcx, llscratch, None, op);
217                             llscratch
218                         }
219                         Ref(llval, align) => {
220                             assert_eq!(align, Alignment::AbiAligned,
221                                        "return pointer is unaligned!");
222                             llval
223                         }
224                     };
225                     let load = bcx.load(
226                         bcx.pointercast(llslot, cast_ty.ptr_to()),
227                         Some(llalign_of_min(bcx.ccx, ret.ty)));
228                     load
229                 } else {
230                     let op = self.trans_consume(&bcx, &mir::Lvalue::Local(mir::RETURN_POINTER));
231                     if let Ref(llval, align) = op.val {
232                         base::load_ty(&bcx, llval, align, op.ty)
233                     } else {
234                         op.pack_if_pair(&bcx).immediate()
235                     }
236                 };
237                 bcx.ret(llval);
238             }
239
240             mir::TerminatorKind::Unreachable => {
241                 bcx.unreachable();
242             }
243
244             mir::TerminatorKind::Drop { ref location, target, unwind } => {
245                 let ty = location.ty(&self.mir, bcx.tcx()).to_ty(bcx.tcx());
246                 let ty = self.monomorphize(&ty);
247
248                 // Double check for necessity to drop
249                 if !bcx.ccx.shared().type_needs_drop(ty) {
250                     funclet_br(self, bcx, target);
251                     return;
252                 }
253
254                 let mut lvalue = self.trans_lvalue(&bcx, location);
255                 let drop_fn = glue::get_drop_glue(bcx.ccx, ty);
256                 let drop_ty = glue::get_drop_glue_type(bcx.ccx.shared(), ty);
257                 if bcx.ccx.shared().type_is_sized(ty) && drop_ty != ty {
258                     lvalue.llval = bcx.pointercast(
259                         lvalue.llval, type_of::type_of(bcx.ccx, drop_ty).ptr_to());
260                 }
261                 let args = &[lvalue.llval, lvalue.llextra][..1 + lvalue.has_extra() as usize];
262                 if let Some(unwind) = unwind {
263                     bcx.invoke(
264                         drop_fn,
265                         args,
266                         self.blocks[target],
267                         llblock(self, unwind),
268                         cleanup_bundle
269                     );
270                 } else {
271                     bcx.call(drop_fn, args, cleanup_bundle);
272                     funclet_br(self, bcx, target);
273                 }
274             }
275
276             mir::TerminatorKind::Assert { ref cond, expected, ref msg, target, cleanup } => {
277                 let cond = self.trans_operand(&bcx, cond).immediate();
278                 let mut const_cond = common::const_to_opt_u128(cond, false).map(|c| c == 1);
279
280                 // This case can currently arise only from functions marked
281                 // with #[rustc_inherit_overflow_checks] and inlined from
282                 // another crate (mostly core::num generic/#[inline] fns),
283                 // while the current crate doesn't use overflow checks.
284                 // NOTE: Unlike binops, negation doesn't have its own
285                 // checked operation, just a comparison with the minimum
286                 // value, so we have to check for the assert message.
287                 if !bcx.ccx.check_overflow() {
288                     use rustc_const_math::ConstMathErr::Overflow;
289                     use rustc_const_math::Op::Neg;
290
291                     if let mir::AssertMessage::Math(Overflow(Neg)) = *msg {
292                         const_cond = Some(expected);
293                     }
294                 }
295
296                 // Don't translate the panic block if success if known.
297                 if const_cond == Some(expected) {
298                     funclet_br(self, bcx, target);
299                     return;
300                 }
301
302                 // Pass the condition through llvm.expect for branch hinting.
303                 let expect = bcx.ccx.get_intrinsic(&"llvm.expect.i1");
304                 let cond = bcx.call(expect, &[cond, C_bool(bcx.ccx, expected)], None);
305
306                 // Create the failure block and the conditional branch to it.
307                 let lltarget = llblock(self, target);
308                 let panic_block = self.new_block("panic");
309                 if expected {
310                     bcx.cond_br(cond, lltarget, panic_block.llbb());
311                 } else {
312                     bcx.cond_br(cond, panic_block.llbb(), lltarget);
313                 }
314
315                 // After this point, bcx is the block for the call to panic.
316                 bcx = panic_block;
317                 self.set_debug_loc(&bcx, terminator.source_info);
318
319                 // Get the location information.
320                 let loc = bcx.sess().codemap().lookup_char_pos(span.lo);
321                 let filename = Symbol::intern(&loc.file.name).as_str();
322                 let filename = C_str_slice(bcx.ccx, filename);
323                 let line = C_u32(bcx.ccx, loc.line as u32);
324
325                 // Put together the arguments to the panic entry point.
326                 let (lang_item, args, const_err) = match *msg {
327                     mir::AssertMessage::BoundsCheck { ref len, ref index } => {
328                         let len = self.trans_operand(&mut bcx, len).immediate();
329                         let index = self.trans_operand(&mut bcx, index).immediate();
330
331                         let const_err = common::const_to_opt_u128(len, false)
332                             .and_then(|len| common::const_to_opt_u128(index, false)
333                                 .map(|index| ErrKind::IndexOutOfBounds {
334                                     len: len as u64,
335                                     index: index as u64
336                                 }));
337
338                         let file_line = C_struct(bcx.ccx, &[filename, line], false);
339                         let align = llalign_of_min(bcx.ccx, common::val_ty(file_line));
340                         let file_line = consts::addr_of(bcx.ccx,
341                                                         file_line,
342                                                         align,
343                                                         "panic_bounds_check_loc");
344                         (lang_items::PanicBoundsCheckFnLangItem,
345                          vec![file_line, index, len],
346                          const_err)
347                     }
348                     mir::AssertMessage::Math(ref err) => {
349                         let msg_str = Symbol::intern(err.description()).as_str();
350                         let msg_str = C_str_slice(bcx.ccx, msg_str);
351                         let msg_file_line = C_struct(bcx.ccx,
352                                                      &[msg_str, filename, line],
353                                                      false);
354                         let align = llalign_of_min(bcx.ccx, common::val_ty(msg_file_line));
355                         let msg_file_line = consts::addr_of(bcx.ccx,
356                                                             msg_file_line,
357                                                             align,
358                                                             "panic_loc");
359                         (lang_items::PanicFnLangItem,
360                          vec![msg_file_line],
361                          Some(ErrKind::Math(err.clone())))
362                     }
363                 };
364
365                 // If we know we always panic, and the error message
366                 // is also constant, then we can produce a warning.
367                 if const_cond == Some(!expected) {
368                     if let Some(err) = const_err {
369                         let err = ConstEvalErr{ span: span, kind: err };
370                         let mut diag = bcx.tcx().sess.struct_span_warn(
371                             span, "this expression will panic at run-time");
372                         note_const_eval_err(bcx.tcx(), &err, span, "expression", &mut diag);
373                         diag.emit();
374                     }
375                 }
376
377                 // Obtain the panic entry point.
378                 let def_id = common::langcall(bcx.tcx(), Some(span), "", lang_item);
379                 let callee = Callee::def(bcx.ccx, def_id,
380                     bcx.ccx.empty_substs_for_def_id(def_id));
381                 let llfn = callee.reify(bcx.ccx);
382
383                 // Translate the actual panic invoke/call.
384                 if let Some(unwind) = cleanup {
385                     bcx.invoke(llfn,
386                                &args,
387                                self.unreachable_block(),
388                                llblock(self, unwind),
389                                cleanup_bundle);
390                 } else {
391                     bcx.call(llfn, &args, cleanup_bundle);
392                     bcx.unreachable();
393                 }
394             }
395
396             mir::TerminatorKind::DropAndReplace { .. } => {
397                 bug!("undesugared DropAndReplace in trans: {:?}", data);
398             }
399
400             mir::TerminatorKind::Call { ref func, ref args, ref destination, ref cleanup } => {
401                 // Create the callee. This is a fn ptr or zero-sized and hence a kind of scalar.
402                 let callee = self.trans_operand(&bcx, func);
403
404                 let (mut callee, abi, sig) = match callee.ty.sty {
405                     ty::TyFnDef(def_id, substs, f) => {
406                         (Callee::def(bcx.ccx, def_id, substs), f.abi, &f.sig)
407                     }
408                     ty::TyFnPtr(f) => {
409                         (Callee {
410                             data: Fn(callee.immediate()),
411                             ty: callee.ty
412                         }, f.abi, &f.sig)
413                     }
414                     _ => bug!("{} is not callable", callee.ty)
415                 };
416
417                 let sig = bcx.tcx().erase_late_bound_regions_and_normalize(sig);
418
419                 // Handle intrinsics old trans wants Expr's for, ourselves.
420                 let intrinsic = match (&callee.ty.sty, &callee.data) {
421                     (&ty::TyFnDef(def_id, ..), &Intrinsic) => {
422                         Some(bcx.tcx().item_name(def_id).as_str())
423                     }
424                     _ => None
425                 };
426                 let mut intrinsic = intrinsic.as_ref().map(|s| &s[..]);
427
428                 if intrinsic == Some("move_val_init") {
429                     let &(_, target) = destination.as_ref().unwrap();
430                     // The first argument is a thin destination pointer.
431                     let llptr = self.trans_operand(&bcx, &args[0]).immediate();
432                     let val = self.trans_operand(&bcx, &args[1]);
433                     self.store_operand(&bcx, llptr, None, val);
434                     funclet_br(self, bcx, target);
435                     return;
436                 }
437
438                 if intrinsic == Some("transmute") {
439                     let &(ref dest, target) = destination.as_ref().unwrap();
440                     self.trans_transmute(&bcx, &args[0], dest);
441                     funclet_br(self, bcx, target);
442                     return;
443                 }
444
445                 let extra_args = &args[sig.inputs().len()..];
446                 let extra_args = extra_args.iter().map(|op_arg| {
447                     let op_ty = op_arg.ty(&self.mir, bcx.tcx());
448                     self.monomorphize(&op_ty)
449                 }).collect::<Vec<_>>();
450                 let fn_ty = callee.direct_fn_type(bcx.ccx, &extra_args);
451
452                 if intrinsic == Some("drop_in_place") {
453                     let &(_, target) = destination.as_ref().unwrap();
454                     let ty = if let ty::TyFnDef(_, substs, _) = callee.ty.sty {
455                         substs.type_at(0)
456                     } else {
457                         bug!("Unexpected ty: {}", callee.ty);
458                     };
459
460                     // Double check for necessity to drop
461                     if !bcx.ccx.shared().type_needs_drop(ty) {
462                         funclet_br(self, bcx, target);
463                         return;
464                     }
465
466                     let drop_fn = glue::get_drop_glue(bcx.ccx, ty);
467                     let llty = fn_ty.llvm_type(bcx.ccx).ptr_to();
468                     callee.data = Fn(bcx.pointercast(drop_fn, llty));
469                     intrinsic = None;
470                 }
471
472                 // The arguments we'll be passing. Plus one to account for outptr, if used.
473                 let arg_count = fn_ty.args.len() + fn_ty.ret.is_indirect() as usize;
474                 let mut llargs = Vec::with_capacity(arg_count);
475
476                 // Prepare the return value destination
477                 let ret_dest = if let Some((ref dest, _)) = *destination {
478                     let is_intrinsic = if let Intrinsic = callee.data {
479                         true
480                     } else {
481                         false
482                     };
483                     self.make_return_dest(&bcx, dest, &fn_ty.ret, &mut llargs, is_intrinsic)
484                 } else {
485                     ReturnDest::Nothing
486                 };
487
488                 // Split the rust-call tupled arguments off.
489                 let (first_args, untuple) = if abi == Abi::RustCall && !args.is_empty() {
490                     let (tup, args) = args.split_last().unwrap();
491                     (args, Some(tup))
492                 } else {
493                     (&args[..], None)
494                 };
495
496                 let is_shuffle = intrinsic.map_or(false, |name| {
497                     name.starts_with("simd_shuffle")
498                 });
499                 let mut idx = 0;
500                 for arg in first_args {
501                     // The indices passed to simd_shuffle* in the
502                     // third argument must be constant. This is
503                     // checked by const-qualification, which also
504                     // promotes any complex rvalues to constants.
505                     if is_shuffle && idx == 2 {
506                         match *arg {
507                             mir::Operand::Consume(_) => {
508                                 span_bug!(span, "shuffle indices must be constant");
509                             }
510                             mir::Operand::Constant(ref constant) => {
511                                 let val = self.trans_constant(&bcx, constant);
512                                 llargs.push(val.llval);
513                                 idx += 1;
514                                 continue;
515                             }
516                         }
517                     }
518
519                     let op = self.trans_operand(&bcx, arg);
520                     self.trans_argument(&bcx, op, &mut llargs, &fn_ty,
521                                         &mut idx, &mut callee.data);
522                 }
523                 if let Some(tup) = untuple {
524                     self.trans_arguments_untupled(&bcx, tup, &mut llargs, &fn_ty,
525                                                   &mut idx, &mut callee.data)
526                 }
527
528                 let fn_ptr = match callee.data {
529                     NamedTupleConstructor(_) => {
530                         // FIXME translate this like mir::Rvalue::Aggregate.
531                         callee.reify(bcx.ccx)
532                     }
533                     Intrinsic => {
534                         use intrinsic::trans_intrinsic_call;
535
536                         let (dest, llargs) = match ret_dest {
537                             _ if fn_ty.ret.is_indirect() => {
538                                 (llargs[0], &llargs[1..])
539                             }
540                             ReturnDest::Nothing => {
541                                 (C_undef(fn_ty.ret.original_ty.ptr_to()), &llargs[..])
542                             }
543                             ReturnDest::IndirectOperand(dst, _) |
544                             ReturnDest::Store(dst) => (dst, &llargs[..]),
545                             ReturnDest::DirectOperand(_) =>
546                                 bug!("Cannot use direct operand with an intrinsic call")
547                         };
548
549                         trans_intrinsic_call(&bcx, callee.ty, &fn_ty, &llargs, dest,
550                             terminator.source_info.span);
551
552                         if let ReturnDest::IndirectOperand(dst, _) = ret_dest {
553                             // Make a fake operand for store_return
554                             let op = OperandRef {
555                                 val: Ref(dst, Alignment::AbiAligned),
556                                 ty: sig.output(),
557                             };
558                             self.store_return(&bcx, ret_dest, fn_ty.ret, op);
559                         }
560
561                         if let Some((_, target)) = *destination {
562                             funclet_br(self, bcx, target);
563                         } else {
564                             bcx.unreachable();
565                         }
566
567                         return;
568                     }
569                     Fn(f) => f,
570                     Virtual(_) => bug!("Virtual fn ptr not extracted")
571                 };
572
573                 // Many different ways to call a function handled here
574                 if let &Some(cleanup) = cleanup {
575                     let ret_bcx = if let Some((_, target)) = *destination {
576                         self.blocks[target]
577                     } else {
578                         self.unreachable_block()
579                     };
580                     let invokeret = bcx.invoke(fn_ptr,
581                                                &llargs,
582                                                ret_bcx,
583                                                llblock(self, cleanup),
584                                                cleanup_bundle);
585                     fn_ty.apply_attrs_callsite(invokeret);
586
587                     if let Some((_, target)) = *destination {
588                         let ret_bcx = self.get_builder(target);
589                         self.set_debug_loc(&ret_bcx, terminator.source_info);
590                         let op = OperandRef {
591                             val: Immediate(invokeret),
592                             ty: sig.output(),
593                         };
594                         self.store_return(&ret_bcx, ret_dest, fn_ty.ret, op);
595                     }
596                 } else {
597                     let llret = bcx.call(fn_ptr, &llargs, cleanup_bundle);
598                     fn_ty.apply_attrs_callsite(llret);
599                     if let Some((_, target)) = *destination {
600                         let op = OperandRef {
601                             val: Immediate(llret),
602                             ty: sig.output(),
603                         };
604                         self.store_return(&bcx, ret_dest, fn_ty.ret, op);
605                         funclet_br(self, bcx, target);
606                     } else {
607                         bcx.unreachable();
608                     }
609                 }
610             }
611         }
612     }
613
614     fn trans_argument(&mut self,
615                       bcx: &Builder<'a, 'tcx>,
616                       op: OperandRef<'tcx>,
617                       llargs: &mut Vec<ValueRef>,
618                       fn_ty: &FnType,
619                       next_idx: &mut usize,
620                       callee: &mut CalleeData) {
621         if let Pair(a, b) = op.val {
622             // Treat the values in a fat pointer separately.
623             if common::type_is_fat_ptr(bcx.ccx, op.ty) {
624                 let (ptr, meta) = (a, b);
625                 if *next_idx == 0 {
626                     if let Virtual(idx) = *callee {
627                         let llfn = meth::get_virtual_method(bcx, meta, idx);
628                         let llty = fn_ty.llvm_type(bcx.ccx).ptr_to();
629                         *callee = Fn(bcx.pointercast(llfn, llty));
630                     }
631                 }
632
633                 let imm_op = |x| OperandRef {
634                     val: Immediate(x),
635                     // We won't be checking the type again.
636                     ty: bcx.tcx().types.err
637                 };
638                 self.trans_argument(bcx, imm_op(ptr), llargs, fn_ty, next_idx, callee);
639                 self.trans_argument(bcx, imm_op(meta), llargs, fn_ty, next_idx, callee);
640                 return;
641             }
642         }
643
644         let arg = &fn_ty.args[*next_idx];
645         *next_idx += 1;
646
647         // Fill padding with undef value, where applicable.
648         if let Some(ty) = arg.pad {
649             llargs.push(C_undef(ty));
650         }
651
652         if arg.is_ignore() {
653             return;
654         }
655
656         // Force by-ref if we have to load through a cast pointer.
657         let (mut llval, align, by_ref) = match op.val {
658             Immediate(_) | Pair(..) => {
659                 if arg.is_indirect() || arg.cast.is_some() {
660                     let llscratch = bcx.alloca(arg.original_ty, "arg");
661                     self.store_operand(bcx, llscratch, None, op);
662                     (llscratch, Alignment::AbiAligned, true)
663                 } else {
664                     (op.pack_if_pair(bcx).immediate(), Alignment::AbiAligned, false)
665                 }
666             }
667             Ref(llval, Alignment::Packed) if arg.is_indirect() => {
668                 // `foo(packed.large_field)`. We can't pass the (unaligned) field directly. I
669                 // think that ATM (Rust 1.16) we only pass temporaries, but we shouldn't
670                 // have scary latent bugs around.
671
672                 let llscratch = bcx.alloca(arg.original_ty, "arg");
673                 base::memcpy_ty(bcx, llscratch, llval, op.ty, Some(1));
674                 (llscratch, Alignment::AbiAligned, true)
675             }
676             Ref(llval, align) => (llval, align, true)
677         };
678
679         if by_ref && !arg.is_indirect() {
680             // Have to load the argument, maybe while casting it.
681             if arg.original_ty == Type::i1(bcx.ccx) {
682                 // We store bools as i8 so we need to truncate to i1.
683                 llval = bcx.load_range_assert(llval, 0, 2, llvm::False, None);
684                 llval = bcx.trunc(llval, arg.original_ty);
685             } else if let Some(ty) = arg.cast {
686                 llval = bcx.load(bcx.pointercast(llval, ty.ptr_to()),
687                                  align.min_with(llalign_of_min(bcx.ccx, arg.ty)));
688             } else {
689                 llval = bcx.load(llval, align.to_align());
690             }
691         }
692
693         llargs.push(llval);
694     }
695
696     fn trans_arguments_untupled(&mut self,
697                                 bcx: &Builder<'a, 'tcx>,
698                                 operand: &mir::Operand<'tcx>,
699                                 llargs: &mut Vec<ValueRef>,
700                                 fn_ty: &FnType,
701                                 next_idx: &mut usize,
702                                 callee: &mut CalleeData) {
703         let tuple = self.trans_operand(bcx, operand);
704
705         let arg_types = match tuple.ty.sty {
706             ty::TyTuple(ref tys, _) => tys,
707             _ => span_bug!(self.mir.span,
708                            "bad final argument to \"rust-call\" fn {:?}", tuple.ty)
709         };
710
711         // Handle both by-ref and immediate tuples.
712         match tuple.val {
713             Ref(llval, align) => {
714                 for (n, &ty) in arg_types.iter().enumerate() {
715                     let ptr = LvalueRef::new_sized_ty(llval, tuple.ty, align);
716                     let (ptr, align) = ptr.trans_field_ptr(bcx, n);
717                     let val = if common::type_is_fat_ptr(bcx.ccx, ty) {
718                         let (lldata, llextra) = base::load_fat_ptr(bcx, ptr, align, ty);
719                         Pair(lldata, llextra)
720                     } else {
721                         // trans_argument will load this if it needs to
722                         Ref(ptr, align)
723                     };
724                     let op = OperandRef {
725                         val: val,
726                         ty: ty
727                     };
728                     self.trans_argument(bcx, op, llargs, fn_ty, next_idx, callee);
729                 }
730
731             }
732             Immediate(llval) => {
733                 let l = bcx.ccx.layout_of(tuple.ty);
734                 let v = if let layout::Univariant { ref variant, .. } = *l {
735                     variant
736                 } else {
737                     bug!("Not a tuple.");
738                 };
739                 for (n, &ty) in arg_types.iter().enumerate() {
740                     let mut elem = bcx.extract_value(llval, v.memory_index[n] as usize);
741                     // Truncate bools to i1, if needed
742                     if ty.is_bool() && common::val_ty(elem) != Type::i1(bcx.ccx) {
743                         elem = bcx.trunc(elem, Type::i1(bcx.ccx));
744                     }
745                     // If the tuple is immediate, the elements are as well
746                     let op = OperandRef {
747                         val: Immediate(elem),
748                         ty: ty
749                     };
750                     self.trans_argument(bcx, op, llargs, fn_ty, next_idx, callee);
751                 }
752             }
753             Pair(a, b) => {
754                 let elems = [a, b];
755                 for (n, &ty) in arg_types.iter().enumerate() {
756                     let mut elem = elems[n];
757                     // Truncate bools to i1, if needed
758                     if ty.is_bool() && common::val_ty(elem) != Type::i1(bcx.ccx) {
759                         elem = bcx.trunc(elem, Type::i1(bcx.ccx));
760                     }
761                     // Pair is always made up of immediates
762                     let op = OperandRef {
763                         val: Immediate(elem),
764                         ty: ty
765                     };
766                     self.trans_argument(bcx, op, llargs, fn_ty, next_idx, callee);
767                 }
768             }
769         }
770
771     }
772
773     fn get_personality_slot(&mut self, bcx: &Builder<'a, 'tcx>) -> ValueRef {
774         let ccx = bcx.ccx;
775         if let Some(slot) = self.llpersonalityslot {
776             slot
777         } else {
778             let llretty = Type::struct_(ccx, &[Type::i8p(ccx), Type::i32(ccx)], false);
779             let slot = bcx.alloca(llretty, "personalityslot");
780             self.llpersonalityslot = Some(slot);
781             Lifetime::Start.call(bcx, slot);
782             slot
783         }
784     }
785
786     /// Return the landingpad wrapper around the given basic block
787     ///
788     /// No-op in MSVC SEH scheme.
789     fn landing_pad_to(&mut self, target_bb: mir::BasicBlock) -> BasicBlockRef {
790         if let Some(block) = self.landing_pads[target_bb] {
791             return block;
792         }
793
794         if base::wants_msvc_seh(self.ccx.sess()) {
795             return self.blocks[target_bb];
796         }
797
798         let target = self.get_builder(target_bb);
799
800         let bcx = self.new_block("cleanup");
801         self.landing_pads[target_bb] = Some(bcx.llbb());
802
803         let ccx = bcx.ccx;
804         let llpersonality = self.ccx.eh_personality();
805         let llretty = Type::struct_(ccx, &[Type::i8p(ccx), Type::i32(ccx)], false);
806         let llretval = bcx.landing_pad(llretty, llpersonality, 1, self.llfn);
807         bcx.set_cleanup(llretval);
808         let slot = self.get_personality_slot(&bcx);
809         bcx.store(llretval, slot, None);
810         bcx.br(target.llbb());
811         bcx.llbb()
812     }
813
814     fn unreachable_block(&mut self) -> BasicBlockRef {
815         self.unreachable_block.unwrap_or_else(|| {
816             let bl = self.new_block("unreachable");
817             bl.unreachable();
818             self.unreachable_block = Some(bl.llbb());
819             bl.llbb()
820         })
821     }
822
823     pub fn new_block(&self, name: &str) -> Builder<'a, 'tcx> {
824         Builder::new_block(self.ccx, self.llfn, name)
825     }
826
827     pub fn get_builder(&self, bb: mir::BasicBlock) -> Builder<'a, 'tcx> {
828         let builder = Builder::with_ccx(self.ccx);
829         builder.position_at_end(self.blocks[bb]);
830         builder
831     }
832
833     fn make_return_dest(&mut self, bcx: &Builder<'a, 'tcx>,
834                         dest: &mir::Lvalue<'tcx>, fn_ret_ty: &ArgType,
835                         llargs: &mut Vec<ValueRef>, is_intrinsic: bool) -> ReturnDest {
836         // If the return is ignored, we can just return a do-nothing ReturnDest
837         if fn_ret_ty.is_ignore() {
838             return ReturnDest::Nothing;
839         }
840         let dest = if let mir::Lvalue::Local(index) = *dest {
841             let ret_ty = self.monomorphized_lvalue_ty(dest);
842             match self.locals[index] {
843                 LocalRef::Lvalue(dest) => dest,
844                 LocalRef::Operand(None) => {
845                     // Handle temporary lvalues, specifically Operand ones, as
846                     // they don't have allocas
847                     return if fn_ret_ty.is_indirect() {
848                         // Odd, but possible, case, we have an operand temporary,
849                         // but the calling convention has an indirect return.
850                         let tmp = LvalueRef::alloca(bcx, ret_ty, "tmp_ret");
851                         llargs.push(tmp.llval);
852                         ReturnDest::IndirectOperand(tmp.llval, index)
853                     } else if is_intrinsic {
854                         // Currently, intrinsics always need a location to store
855                         // the result. so we create a temporary alloca for the
856                         // result
857                         let tmp = LvalueRef::alloca(bcx, ret_ty, "tmp_ret");
858                         ReturnDest::IndirectOperand(tmp.llval, index)
859                     } else {
860                         ReturnDest::DirectOperand(index)
861                     };
862                 }
863                 LocalRef::Operand(Some(_)) => {
864                     bug!("lvalue local already assigned to");
865                 }
866             }
867         } else {
868             self.trans_lvalue(bcx, dest)
869         };
870         if fn_ret_ty.is_indirect() {
871             llargs.push(dest.llval);
872             ReturnDest::Nothing
873         } else {
874             ReturnDest::Store(dest.llval)
875         }
876     }
877
878     fn trans_transmute(&mut self, bcx: &Builder<'a, 'tcx>,
879                        src: &mir::Operand<'tcx>,
880                        dst: &mir::Lvalue<'tcx>) {
881         if let mir::Lvalue::Local(index) = *dst {
882             match self.locals[index] {
883                 LocalRef::Lvalue(lvalue) => self.trans_transmute_into(bcx, src, &lvalue),
884                 LocalRef::Operand(None) => {
885                     let lvalue_ty = self.monomorphized_lvalue_ty(dst);
886                     assert!(!lvalue_ty.has_erasable_regions());
887                     let lvalue = LvalueRef::alloca(bcx, lvalue_ty, "transmute_temp");
888                     self.trans_transmute_into(bcx, src, &lvalue);
889                     let op = self.trans_load(bcx, lvalue.llval, lvalue.alignment, lvalue_ty);
890                     self.locals[index] = LocalRef::Operand(Some(op));
891                 }
892                 LocalRef::Operand(Some(_)) => {
893                     let ty = self.monomorphized_lvalue_ty(dst);
894                     assert!(common::type_is_zero_size(bcx.ccx, ty),
895                             "assigning to initialized SSAtemp");
896                 }
897             }
898         } else {
899             let dst = self.trans_lvalue(bcx, dst);
900             self.trans_transmute_into(bcx, src, &dst);
901         }
902     }
903
904     fn trans_transmute_into(&mut self, bcx: &Builder<'a, 'tcx>,
905                             src: &mir::Operand<'tcx>,
906                             dst: &LvalueRef<'tcx>) {
907         let mut val = self.trans_operand(bcx, src);
908         if let ty::TyFnDef(def_id, substs, _) = val.ty.sty {
909             let llouttype = type_of::type_of(bcx.ccx, dst.ty.to_ty(bcx.tcx()));
910             let out_type_size = llbitsize_of_real(bcx.ccx, llouttype);
911             if out_type_size != 0 {
912                 // FIXME #19925 Remove this hack after a release cycle.
913                 let f = Callee::def(bcx.ccx, def_id, substs);
914                 let ty = match f.ty.sty {
915                     ty::TyFnDef(.., f) => bcx.tcx().mk_fn_ptr(f),
916                     _ => f.ty
917                 };
918                 val = OperandRef {
919                     val: Immediate(f.reify(bcx.ccx)),
920                     ty: ty
921                 };
922             }
923         }
924
925         let llty = type_of::type_of(bcx.ccx, val.ty);
926         let cast_ptr = bcx.pointercast(dst.llval, llty.ptr_to());
927         let in_type = val.ty;
928         let out_type = dst.ty.to_ty(bcx.tcx());;
929         let llalign = cmp::min(align_of(bcx.ccx, in_type), align_of(bcx.ccx, out_type));
930         self.store_operand(bcx, cast_ptr, Some(llalign), val);
931     }
932
933
934     // Stores the return value of a function call into it's final location.
935     fn store_return(&mut self,
936                     bcx: &Builder<'a, 'tcx>,
937                     dest: ReturnDest,
938                     ret_ty: ArgType,
939                     op: OperandRef<'tcx>) {
940         use self::ReturnDest::*;
941
942         match dest {
943             Nothing => (),
944             Store(dst) => ret_ty.store(bcx, op.immediate(), dst),
945             IndirectOperand(tmp, index) => {
946                 let op = self.trans_load(bcx, tmp, Alignment::AbiAligned, op.ty);
947                 self.locals[index] = LocalRef::Operand(Some(op));
948             }
949             DirectOperand(index) => {
950                 // If there is a cast, we have to store and reload.
951                 let op = if ret_ty.cast.is_some() {
952                     let tmp = LvalueRef::alloca(bcx, op.ty, "tmp_ret");
953                     ret_ty.store(bcx, op.immediate(), tmp.llval);
954                     self.trans_load(bcx, tmp.llval, tmp.alignment, op.ty)
955                 } else {
956                     op.unpack_if_pair(bcx)
957                 };
958                 self.locals[index] = LocalRef::Operand(Some(op));
959             }
960         }
961     }
962 }
963
964 enum ReturnDest {
965     // Do nothing, the return value is indirect or ignored
966     Nothing,
967     // Store the return value to the pointer
968     Store(ValueRef),
969     // Stores an indirect return value to an operand local lvalue
970     IndirectOperand(ValueRef, mir::Local),
971     // Stores a direct return value to an operand local lvalue
972     DirectOperand(mir::Local)
973 }