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.
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.
11 use llvm::{self, ValueRef, BasicBlockRef};
12 use rustc::middle::lang_items;
13 use rustc::ty::{self, Ty, TypeFoldable};
14 use rustc::ty::layout::{self, LayoutOf};
16 use abi::{Abi, ArgType, ArgTypeExt, FnType, FnTypeExt, LlvmType, PassMode};
20 use common::{self, C_bool, C_str_slice, C_struct, C_u32, C_uint_big, C_undef};
24 use type_of::LayoutLlvmExt;
27 use syntax::symbol::Symbol;
30 use super::{FunctionCx, LocalRef};
31 use super::place::PlaceRef;
32 use super::operand::OperandRef;
33 use super::operand::OperandValue::{Pair, Ref, Immediate};
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];
40 debug!("trans_block({:?}={:?})", bb, data);
42 for statement in &data.statements {
43 bx = self.trans_statement(bx, statement);
46 self.trans_terminator(bx, bb, data.terminator());
49 fn trans_terminator(&mut self,
50 mut bx: Builder<'a, 'tcx>,
52 terminator: &mir::Terminator<'tcx>)
54 debug!("trans_terminator: {:?}", terminator);
56 // Create the cleanup bundle, if needed.
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());
62 let cleanup_pad = funclet.map(|lp| lp.cleanuppad());
63 let cleanup_bundle = funclet.map(|l| l.bundle());
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),
71 if f == t_f || !base::wants_msvc_seh(tcx.sess)
74 // jump *into* cleanup - need a landing pad if GNU
75 (this.landing_pad_to(target), false)
77 (Some(_), None) => span_bug!(span, "{:?} - jump out of cleanup?", terminator),
78 (Some(_), Some(_)) => {
79 (this.landing_pad_to(target), true)
84 let llblock = |this: &mut Self, target: mir::BasicBlock| {
85 let (lltarget, is_cleanupret) = lltarget(this, target);
87 // MSVC cross-funclet jump - need a trampoline
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));
99 let funclet_br = |this: &mut Self, bx: Builder, target: mir::BasicBlock| {
100 let (lltarget, is_cleanupret) = lltarget(this, target);
102 // micro-optimization: generate a `ret` rather than a jump
104 bx.cleanup_ret(cleanup_pad.unwrap(), Some(lltarget));
112 bx: Builder<'a, 'tcx>,
113 fn_ty: FnType<'tcx, Ty<'tcx>>,
116 destination: Option<(ReturnDest<'tcx>, mir::BasicBlock)>,
117 cleanup: Option<mir::BasicBlock>
119 if let Some(cleanup) = cleanup {
120 let ret_bx = if let Some((_, target)) = destination {
123 this.unreachable_block()
125 let invokeret = bx.invoke(fn_ptr,
128 llblock(this, cleanup),
130 fn_ty.apply_attrs_callsite(invokeret);
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);
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);
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);
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);
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);
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);
174 bx.call(bx.cx.eh_unwind_resume(), &[lp0], cleanup_bundle);
180 mir::TerminatorKind::Abort => {
181 // Call core::intrinsics::abort()
182 let fnname = bx.cx.get_intrinsic(&("llvm.trap"));
183 bx.call(fnname, &[], None);
187 mir::TerminatorKind::Goto { target } => {
188 funclet_br(self, bx, target);
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);
199 assert_eq!(&values[..], &[1]);
200 bx.cond_br(discr.immediate(), lltrue, llfalse);
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)
215 mir::TerminatorKind::Return => {
216 let llval = match self.fn_ty.ret.mode {
217 PassMode::Ignore | PassMode::Indirect(_) => {
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)
227 op.immediate_or_packed_pair(&bx)
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) => {
237 val: Ref(tr_place.llval, tr_place.align),
238 layout: tr_place.layout
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);
248 Ref(llval, align) => {
249 assert_eq!(align.abi(), op.layout.align.abi(),
250 "return place is unaligned!");
255 bx.pointercast(llslot, cast_ty.llvm_type(bx.cx).ptr_to()),
256 self.fn_ty.ret.layout.align)
262 mir::TerminatorKind::Unreachable => {
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);
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);
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().normalize_erasing_late_bound_regions(
285 ty::ParamEnv::reveal_all(),
288 let fn_ty = FnType::new_vtable(bx.cx, sig, &[]);
290 (meth::DESTRUCTOR.get_fn(&bx, place.llextra, &fn_ty), fn_ty)
293 (callee::get_fn(bx.cx, drop_fn),
294 FnType::of_instance(bx.cx, &drop_fn))
297 do_call(self, bx, fn_ty, drop_fn, args,
298 Some((ReturnDest::Nothing, target)),
302 mir::TerminatorKind::Assert { ref cond, expected, ref msg, target, cleanup } => {
303 let cond = self.trans_operand(&bx, cond).immediate();
304 let mut const_cond = common::const_to_opt_u128(cond, false).map(|c| c == 1);
306 // This case can currently arise only from functions marked
307 // with #[rustc_inherit_overflow_checks] and inlined from
308 // another crate (mostly core::num generic/#[inline] fns),
309 // while the current crate doesn't use overflow checks.
310 // NOTE: Unlike binops, negation doesn't have its own
311 // checked operation, just a comparison with the minimum
312 // value, so we have to check for the assert message.
313 if !bx.cx.check_overflow {
314 use rustc_const_math::ConstMathErr::Overflow;
315 use rustc_const_math::Op::Neg;
317 if let mir::AssertMessage::Math(Overflow(Neg)) = *msg {
318 const_cond = Some(expected);
322 // Don't translate the panic block if success if known.
323 if const_cond == Some(expected) {
324 funclet_br(self, bx, target);
328 // Pass the condition through llvm.expect for branch hinting.
329 let expect = bx.cx.get_intrinsic(&"llvm.expect.i1");
330 let cond = bx.call(expect, &[cond, C_bool(bx.cx, expected)], None);
332 // Create the failure block and the conditional branch to it.
333 let lltarget = llblock(self, target);
334 let panic_block = self.new_block("panic");
336 bx.cond_br(cond, lltarget, panic_block.llbb());
338 bx.cond_br(cond, panic_block.llbb(), lltarget);
341 // After this point, bx is the block for the call to panic.
343 self.set_debug_loc(&bx, terminator.source_info);
345 // Get the location information.
346 let loc = bx.sess().codemap().lookup_char_pos(span.lo());
347 let filename = Symbol::intern(&loc.file.name.to_string()).as_str();
348 let filename = C_str_slice(bx.cx, filename);
349 let line = C_u32(bx.cx, loc.line as u32);
350 let col = C_u32(bx.cx, loc.col.to_usize() as u32 + 1);
351 let align = tcx.data_layout.aggregate_align
352 .max(tcx.data_layout.i32_align)
353 .max(tcx.data_layout.pointer_align);
355 // Put together the arguments to the panic entry point.
356 let (lang_item, args) = match *msg {
357 mir::AssertMessage::BoundsCheck { ref len, ref index } => {
358 let len = self.trans_operand(&mut bx, len).immediate();
359 let index = self.trans_operand(&mut bx, index).immediate();
361 let file_line_col = C_struct(bx.cx, &[filename, line, col], false);
362 let file_line_col = consts::addr_of(bx.cx,
365 "panic_bounds_check_loc");
366 (lang_items::PanicBoundsCheckFnLangItem,
367 vec![file_line_col, index, len])
369 mir::AssertMessage::Math(ref err) => {
370 let msg_str = Symbol::intern(err.description()).as_str();
371 let msg_str = C_str_slice(bx.cx, msg_str);
372 let msg_file_line_col = C_struct(bx.cx,
373 &[msg_str, filename, line, col],
375 let msg_file_line_col = consts::addr_of(bx.cx,
379 (lang_items::PanicFnLangItem,
380 vec![msg_file_line_col])
382 mir::AssertMessage::GeneratorResumedAfterReturn |
383 mir::AssertMessage::GeneratorResumedAfterPanic => {
384 let str = if let mir::AssertMessage::GeneratorResumedAfterReturn = *msg {
385 "generator resumed after completion"
387 "generator resumed after panicking"
389 let msg_str = Symbol::intern(str).as_str();
390 let msg_str = C_str_slice(bx.cx, msg_str);
391 let msg_file_line_col = C_struct(bx.cx,
392 &[msg_str, filename, line, col],
394 let msg_file_line_col = consts::addr_of(bx.cx,
398 (lang_items::PanicFnLangItem,
399 vec![msg_file_line_col])
403 // Obtain the panic entry point.
404 let def_id = common::langcall(bx.tcx(), Some(span), "", lang_item);
405 let instance = ty::Instance::mono(bx.tcx(), def_id);
406 let fn_ty = FnType::of_instance(bx.cx, &instance);
407 let llfn = callee::get_fn(bx.cx, instance);
409 // Translate the actual panic invoke/call.
410 do_call(self, bx, fn_ty, llfn, &args, None, cleanup);
413 mir::TerminatorKind::DropAndReplace { .. } => {
414 bug!("undesugared DropAndReplace in trans: {:?}", terminator);
417 mir::TerminatorKind::Call { ref func, ref args, ref destination, cleanup } => {
418 // Create the callee. This is a fn ptr or zero-sized and hence a kind of scalar.
419 let callee = self.trans_operand(&bx, func);
421 let (instance, mut llfn) = match callee.layout.ty.sty {
422 ty::TyFnDef(def_id, substs) => {
423 (Some(ty::Instance::resolve(bx.cx.tcx,
424 ty::ParamEnv::reveal_all(),
430 (None, Some(callee.immediate()))
432 _ => bug!("{} is not callable", callee.layout.ty)
434 let def = instance.map(|i| i.def);
435 let sig = callee.layout.ty.fn_sig(bx.tcx());
436 let sig = bx.tcx().normalize_erasing_late_bound_regions(
437 ty::ParamEnv::reveal_all(),
442 // Handle intrinsics old trans wants Expr's for, ourselves.
443 let intrinsic = match def {
444 Some(ty::InstanceDef::Intrinsic(def_id))
445 => Some(bx.tcx().item_name(def_id)),
448 let intrinsic = intrinsic.as_ref().map(|s| &s[..]);
450 if intrinsic == Some("transmute") {
451 let &(ref dest, target) = destination.as_ref().unwrap();
452 self.trans_transmute(&bx, &args[0], dest);
453 funclet_br(self, bx, target);
457 let extra_args = &args[sig.inputs().len()..];
458 let extra_args = extra_args.iter().map(|op_arg| {
459 let op_ty = op_arg.ty(self.mir, bx.tcx());
460 self.monomorphize(&op_ty)
461 }).collect::<Vec<_>>();
463 let fn_ty = match def {
464 Some(ty::InstanceDef::Virtual(..)) => {
465 FnType::new_vtable(bx.cx, sig, &extra_args)
467 Some(ty::InstanceDef::DropGlue(_, None)) => {
468 // empty drop glue - a nop.
469 let &(_, target) = destination.as_ref().unwrap();
470 funclet_br(self, bx, target);
473 _ => FnType::new(bx.cx, sig, &extra_args)
476 // The arguments we'll be passing. Plus one to account for outptr, if used.
477 let arg_count = fn_ty.args.len() + fn_ty.ret.is_indirect() as usize;
478 let mut llargs = Vec::with_capacity(arg_count);
480 // Prepare the return value destination
481 let ret_dest = if let Some((ref dest, _)) = *destination {
482 let is_intrinsic = intrinsic.is_some();
483 self.make_return_dest(&bx, dest, &fn_ty.ret, &mut llargs,
489 if intrinsic.is_some() && intrinsic != Some("drop_in_place") {
490 use intrinsic::trans_intrinsic_call;
492 let dest = match ret_dest {
493 _ if fn_ty.ret.is_indirect() => llargs[0],
494 ReturnDest::Nothing => {
495 C_undef(fn_ty.ret.memory_ty(bx.cx).ptr_to())
497 ReturnDest::IndirectOperand(dst, _) |
498 ReturnDest::Store(dst) => dst.llval,
499 ReturnDest::DirectOperand(_) =>
500 bug!("Cannot use direct operand with an intrinsic call")
503 let args: Vec<_> = args.iter().enumerate().map(|(i, arg)| {
504 // The indices passed to simd_shuffle* in the
505 // third argument must be constant. This is
506 // checked by const-qualification, which also
507 // promotes any complex rvalues to constants.
508 if i == 2 && intrinsic.unwrap().starts_with("simd_shuffle") {
510 mir::Operand::Copy(_) |
511 mir::Operand::Move(_) => {
512 span_bug!(span, "shuffle indices must be constant");
514 mir::Operand::Constant(ref constant) => {
515 let (llval, ty) = self.simd_shuffle_indices(
520 val: Immediate(llval),
521 layout: bx.cx.layout_of(ty)
527 self.trans_operand(&bx, arg)
531 let callee_ty = instance.as_ref().unwrap().ty(bx.cx.tcx);
532 trans_intrinsic_call(&bx, callee_ty, &fn_ty, &args, dest,
533 terminator.source_info.span);
535 if let ReturnDest::IndirectOperand(dst, _) = ret_dest {
536 self.store_return(&bx, ret_dest, &fn_ty.ret, dst.llval);
539 if let Some((_, target)) = *destination {
540 funclet_br(self, bx, target);
548 // Split the rust-call tupled arguments off.
549 let (first_args, untuple) = if abi == Abi::RustCall && !args.is_empty() {
550 let (tup, args) = args.split_last().unwrap();
556 for (i, arg) in first_args.iter().enumerate() {
557 let mut op = self.trans_operand(&bx, arg);
558 if let (0, Some(ty::InstanceDef::Virtual(_, idx))) = (i, def) {
559 if let Pair(data_ptr, meta) = op.val {
560 llfn = Some(meth::VirtualIndex::from_index(idx)
561 .get_fn(&bx, meta, &fn_ty));
562 llargs.push(data_ptr);
567 // The callee needs to own the argument memory if we pass it
568 // by-ref, so make a local copy of non-immediate constants.
569 match (arg, op.val) {
570 (&mir::Operand::Copy(_), Ref(..)) |
571 (&mir::Operand::Constant(_), Ref(..)) => {
572 let tmp = PlaceRef::alloca(&bx, op.layout, "const");
573 op.val.store(&bx, tmp);
574 op.val = Ref(tmp.llval, tmp.align);
579 self.trans_argument(&bx, op, &mut llargs, &fn_ty.args[i]);
581 if let Some(tup) = untuple {
582 self.trans_arguments_untupled(&bx, tup, &mut llargs,
583 &fn_ty.args[first_args.len()..])
586 let fn_ptr = match (llfn, instance) {
587 (Some(llfn), _) => llfn,
588 (None, Some(instance)) => callee::get_fn(bx.cx, instance),
589 _ => span_bug!(span, "no llfn for call"),
592 do_call(self, bx, fn_ty, fn_ptr, &llargs,
593 destination.as_ref().map(|&(_, target)| (ret_dest, target)),
596 mir::TerminatorKind::GeneratorDrop |
597 mir::TerminatorKind::Yield { .. } => bug!("generator ops in trans"),
598 mir::TerminatorKind::FalseEdges { .. } |
599 mir::TerminatorKind::FalseUnwind { .. } => bug!("borrowck false edges in trans"),
603 fn trans_argument(&mut self,
604 bx: &Builder<'a, 'tcx>,
605 op: OperandRef<'tcx>,
606 llargs: &mut Vec<ValueRef>,
607 arg: &ArgType<'tcx, Ty<'tcx>>) {
608 // Fill padding with undef value, where applicable.
609 if let Some(ty) = arg.pad {
610 llargs.push(C_undef(ty.llvm_type(bx.cx)));
617 if let PassMode::Pair(..) = arg.mode {
624 _ => bug!("trans_argument: {:?} invalid for pair arugment", op)
628 // Force by-ref if we have to load through a cast pointer.
629 let (mut llval, align, by_ref) = match op.val {
630 Immediate(_) | Pair(..) => {
632 PassMode::Indirect(_) | PassMode::Cast(_) => {
633 let scratch = PlaceRef::alloca(bx, arg.layout, "arg");
634 op.val.store(bx, scratch);
635 (scratch.llval, scratch.align, true)
638 (op.immediate_or_packed_pair(bx), arg.layout.align, false)
642 Ref(llval, align) => {
643 if arg.is_indirect() && align.abi() < arg.layout.align.abi() {
644 // `foo(packed.large_field)`. We can't pass the (unaligned) field directly. I
645 // think that ATM (Rust 1.16) we only pass temporaries, but we shouldn't
646 // have scary latent bugs around.
648 let scratch = PlaceRef::alloca(bx, arg.layout, "arg");
649 base::memcpy_ty(bx, scratch.llval, llval, op.layout, align);
650 (scratch.llval, scratch.align, true)
657 if by_ref && !arg.is_indirect() {
658 // Have to load the argument, maybe while casting it.
659 if let PassMode::Cast(ty) = arg.mode {
660 llval = bx.load(bx.pointercast(llval, ty.llvm_type(bx.cx).ptr_to()),
661 align.min(arg.layout.align));
663 // We can't use `PlaceRef::load` here because the argument
664 // may have a type we don't treat as immediate, but the ABI
665 // used for this call is passing it by-value. In that case,
666 // the load would just produce `OperandValue::Ref` instead
667 // of the `OperandValue::Immediate` we need for the call.
668 llval = bx.load(llval, align);
669 if let layout::Abi::Scalar(ref scalar) = arg.layout.abi {
670 if scalar.is_bool() {
671 bx.range_metadata(llval, 0..2);
674 // We store bools as i8 so we need to truncate to i1.
675 llval = base::to_immediate(bx, llval, arg.layout);
682 fn trans_arguments_untupled(&mut self,
683 bx: &Builder<'a, 'tcx>,
684 operand: &mir::Operand<'tcx>,
685 llargs: &mut Vec<ValueRef>,
686 args: &[ArgType<'tcx, Ty<'tcx>>]) {
687 let tuple = self.trans_operand(bx, operand);
689 // Handle both by-ref and immediate tuples.
690 if let Ref(llval, align) = tuple.val {
691 let tuple_ptr = PlaceRef::new_sized(llval, tuple.layout, align);
692 for i in 0..tuple.layout.fields.count() {
693 let field_ptr = tuple_ptr.project_field(bx, i);
694 self.trans_argument(bx, field_ptr.load(bx), llargs, &args[i]);
697 // If the tuple is immediate, the elements are as well.
698 for i in 0..tuple.layout.fields.count() {
699 let op = tuple.extract_field(bx, i);
700 self.trans_argument(bx, op, llargs, &args[i]);
705 fn get_personality_slot(&mut self, bx: &Builder<'a, 'tcx>) -> PlaceRef<'tcx> {
707 if let Some(slot) = self.personality_slot {
710 let layout = cx.layout_of(cx.tcx.intern_tup(&[
711 cx.tcx.mk_mut_ptr(cx.tcx.types.u8),
714 let slot = PlaceRef::alloca(bx, layout, "personalityslot");
715 self.personality_slot = Some(slot);
720 /// Return the landingpad wrapper around the given basic block
722 /// No-op in MSVC SEH scheme.
723 fn landing_pad_to(&mut self, target_bb: mir::BasicBlock) -> BasicBlockRef {
724 if let Some(block) = self.landing_pads[target_bb] {
728 let block = self.blocks[target_bb];
729 let landing_pad = self.landing_pad_uncached(block);
730 self.landing_pads[target_bb] = Some(landing_pad);
734 fn landing_pad_uncached(&mut self, target_bb: BasicBlockRef) -> BasicBlockRef {
735 if base::wants_msvc_seh(self.cx.sess()) {
736 span_bug!(self.mir.span, "landing pad was not inserted?")
739 let bx = self.new_block("cleanup");
741 let llpersonality = self.cx.eh_personality();
742 let llretty = self.landing_pad_type();
743 let lp = bx.landing_pad(llretty, llpersonality, 1);
746 let slot = self.get_personality_slot(&bx);
747 slot.storage_live(&bx);
748 Pair(bx.extract_value(lp, 0), bx.extract_value(lp, 1)).store(&bx, slot);
754 fn landing_pad_type(&self) -> Type {
756 Type::struct_(cx, &[Type::i8p(cx), Type::i32(cx)], false)
759 fn unreachable_block(&mut self) -> BasicBlockRef {
760 self.unreachable_block.unwrap_or_else(|| {
761 let bl = self.new_block("unreachable");
763 self.unreachable_block = Some(bl.llbb());
768 pub fn new_block(&self, name: &str) -> Builder<'a, 'tcx> {
769 Builder::new_block(self.cx, self.llfn, name)
772 pub fn build_block(&self, bb: mir::BasicBlock) -> Builder<'a, 'tcx> {
773 let bx = Builder::with_cx(self.cx);
774 bx.position_at_end(self.blocks[bb]);
778 fn make_return_dest(&mut self, bx: &Builder<'a, 'tcx>,
779 dest: &mir::Place<'tcx>, fn_ret: &ArgType<'tcx, Ty<'tcx>>,
780 llargs: &mut Vec<ValueRef>, is_intrinsic: bool)
781 -> ReturnDest<'tcx> {
782 // If the return is ignored, we can just return a do-nothing ReturnDest
783 if fn_ret.is_ignore() {
784 return ReturnDest::Nothing;
786 let dest = if let mir::Place::Local(index) = *dest {
787 match self.locals[index] {
788 LocalRef::Place(dest) => dest,
789 LocalRef::Operand(None) => {
790 // Handle temporary places, specifically Operand ones, as
791 // they don't have allocas
792 return if fn_ret.is_indirect() {
793 // Odd, but possible, case, we have an operand temporary,
794 // but the calling convention has an indirect return.
795 let tmp = PlaceRef::alloca(bx, fn_ret.layout, "tmp_ret");
796 tmp.storage_live(bx);
797 llargs.push(tmp.llval);
798 ReturnDest::IndirectOperand(tmp, index)
799 } else if is_intrinsic {
800 // Currently, intrinsics always need a location to store
801 // the result. so we create a temporary alloca for the
803 let tmp = PlaceRef::alloca(bx, fn_ret.layout, "tmp_ret");
804 tmp.storage_live(bx);
805 ReturnDest::IndirectOperand(tmp, index)
807 ReturnDest::DirectOperand(index)
810 LocalRef::Operand(Some(_)) => {
811 bug!("place local already assigned to");
815 self.trans_place(bx, dest)
817 if fn_ret.is_indirect() {
818 if dest.align.abi() < dest.layout.align.abi() {
819 // Currently, MIR code generation does not create calls
820 // that store directly to fields of packed structs (in
821 // fact, the calls it creates write only to temps),
823 // If someone changes that, please update this code path
824 // to create a temporary.
825 span_bug!(self.mir.span, "can't directly store to unaligned value");
827 llargs.push(dest.llval);
830 ReturnDest::Store(dest)
834 fn trans_transmute(&mut self, bx: &Builder<'a, 'tcx>,
835 src: &mir::Operand<'tcx>,
836 dst: &mir::Place<'tcx>) {
837 if let mir::Place::Local(index) = *dst {
838 match self.locals[index] {
839 LocalRef::Place(place) => self.trans_transmute_into(bx, src, place),
840 LocalRef::Operand(None) => {
841 let dst_layout = bx.cx.layout_of(self.monomorphized_place_ty(dst));
842 assert!(!dst_layout.ty.has_erasable_regions());
843 let place = PlaceRef::alloca(bx, dst_layout, "transmute_temp");
844 place.storage_live(bx);
845 self.trans_transmute_into(bx, src, place);
846 let op = place.load(bx);
847 place.storage_dead(bx);
848 self.locals[index] = LocalRef::Operand(Some(op));
850 LocalRef::Operand(Some(op)) => {
851 assert!(op.layout.is_zst(),
852 "assigning to initialized SSAtemp");
856 let dst = self.trans_place(bx, dst);
857 self.trans_transmute_into(bx, src, dst);
861 fn trans_transmute_into(&mut self, bx: &Builder<'a, 'tcx>,
862 src: &mir::Operand<'tcx>,
863 dst: PlaceRef<'tcx>) {
864 let src = self.trans_operand(bx, src);
865 let llty = src.layout.llvm_type(bx.cx);
866 let cast_ptr = bx.pointercast(dst.llval, llty.ptr_to());
867 let align = src.layout.align.min(dst.layout.align);
868 src.val.store(bx, PlaceRef::new_sized(cast_ptr, src.layout, align));
872 // Stores the return value of a function call into it's final location.
873 fn store_return(&mut self,
874 bx: &Builder<'a, 'tcx>,
875 dest: ReturnDest<'tcx>,
876 ret_ty: &ArgType<'tcx, Ty<'tcx>>,
878 use self::ReturnDest::*;
882 Store(dst) => ret_ty.store(bx, llval, dst),
883 IndirectOperand(tmp, index) => {
884 let op = tmp.load(bx);
885 tmp.storage_dead(bx);
886 self.locals[index] = LocalRef::Operand(Some(op));
888 DirectOperand(index) => {
889 // If there is a cast, we have to store and reload.
890 let op = if let PassMode::Cast(_) = ret_ty.mode {
891 let tmp = PlaceRef::alloca(bx, ret_ty.layout, "tmp_ret");
892 tmp.storage_live(bx);
893 ret_ty.store(bx, llval, tmp);
894 let op = tmp.load(bx);
895 tmp.storage_dead(bx);
898 OperandRef::from_immediate_or_packed_pair(bx, llval, ret_ty.layout)
900 self.locals[index] = LocalRef::Operand(Some(op));
906 enum ReturnDest<'tcx> {
907 // Do nothing, the return value is indirect or ignored
909 // Store the return value to the pointer
910 Store(PlaceRef<'tcx>),
911 // Stores an indirect return value to an operand local place
912 IndirectOperand(PlaceRef<'tcx>, mir::Local),
913 // Stores a direct return value to an operand local place
914 DirectOperand(mir::Local)