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