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