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