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, BasicBlock};
12 use rustc::middle::lang_items;
13 use rustc::ty::{self, Ty, TypeFoldable};
14 use rustc::ty::layout::{self, LayoutOf};
16 use rustc::mir::interpret::EvalErrorKind;
17 use abi::{Abi, ArgType, ArgTypeExt, FnType, FnTypeExt, LlvmType, PassMode};
20 use builder::{Builder, MemFlags};
21 use common::{self, IntPredicate};
25 use type_of::LayoutLlvmExt;
29 use interfaces::{BuilderMethods, CommonMethods, TypeMethods};
31 use syntax::symbol::Symbol;
34 use super::{FunctionCx, LocalRef};
35 use super::place::PlaceRef;
36 use super::operand::OperandRef;
37 use super::operand::OperandValue::{Pair, Ref, Immediate};
39 impl FunctionCx<'a, 'll, 'tcx, &'ll Value> {
40 pub fn codegen_block(&mut self, bb: mir::BasicBlock) {
41 let mut bx = self.build_block(bb);
42 let data = &self.mir[bb];
44 debug!("codegen_block({:?}={:?})", bb, data);
46 for statement in &data.statements {
47 bx = self.codegen_statement(bx, statement);
50 self.codegen_terminator(bx, bb, data.terminator());
53 fn codegen_terminator(&mut self,
54 mut bx: Builder<'a, 'll, 'tcx>,
56 terminator: &mir::Terminator<'tcx>)
58 debug!("codegen_terminator: {:?}", terminator);
60 // Create the cleanup bundle, if needed.
62 let span = terminator.source_info.span;
63 let funclet_bb = self.cleanup_kinds[bb].funclet_bb(bb);
64 let funclet = funclet_bb.and_then(|funclet_bb| self.funclets[funclet_bb].as_ref());
66 let cleanup_pad = funclet.map(|lp| lp.cleanuppad());
67 let cleanup_bundle = funclet.map(|l| l.bundle());
69 let lltarget = |this: &mut Self, target: mir::BasicBlock| {
70 let lltarget = this.blocks[target];
71 let target_funclet = this.cleanup_kinds[target].funclet_bb(target);
72 match (funclet_bb, target_funclet) {
73 (None, None) => (lltarget, false),
75 if f == t_f || !base::wants_msvc_seh(tcx.sess)
78 // jump *into* cleanup - need a landing pad if GNU
79 (this.landing_pad_to(target), false)
81 (Some(_), None) => span_bug!(span, "{:?} - jump out of cleanup?", terminator),
82 (Some(_), Some(_)) => {
83 (this.landing_pad_to(target), true)
88 let llblock = |this: &mut Self, target: mir::BasicBlock| {
89 let (lltarget, is_cleanupret) = lltarget(this, target);
91 // MSVC cross-funclet jump - need a trampoline
93 debug!("llblock: creating cleanup trampoline for {:?}", target);
94 let name = &format!("{:?}_cleanup_trampoline_{:?}", bb, target);
95 let trampoline = this.new_block(name);
96 trampoline.cleanup_ret(cleanup_pad.unwrap(), Some(lltarget));
104 |this: &mut Self, bx: Builder<'_, 'll, '_>, target: mir::BasicBlock| {
105 let (lltarget, is_cleanupret) = lltarget(this, target);
107 // micro-optimization: generate a `ret` rather than a jump
109 bx.cleanup_ret(cleanup_pad.unwrap(), Some(lltarget));
117 bx: Builder<'a, 'll, 'tcx>,
118 fn_ty: FnType<'tcx, Ty<'tcx>>,
120 llargs: &[&'ll Value],
121 destination: Option<(ReturnDest<'tcx, &'ll Value>, mir::BasicBlock)>,
122 cleanup: Option<mir::BasicBlock>
124 if let Some(cleanup) = cleanup {
125 let ret_bx = if let Some((_, target)) = destination {
128 this.unreachable_block()
130 let invokeret = bx.invoke(fn_ptr,
133 llblock(this, cleanup),
135 fn_ty.apply_attrs_callsite(&bx, invokeret);
137 if let Some((ret_dest, target)) = destination {
138 let ret_bx = this.build_block(target);
139 this.set_debug_loc(&ret_bx, terminator.source_info);
140 this.store_return(&ret_bx, ret_dest, &fn_ty.ret, invokeret);
143 let llret = bx.call(fn_ptr, &llargs, cleanup_bundle);
144 fn_ty.apply_attrs_callsite(&bx, llret);
145 if this.mir[bb].is_cleanup {
146 // Cleanup is always the cold path. Don't inline
147 // drop glue. Also, when there is a deeply-nested
148 // struct, there are "symmetry" issues that cause
149 // exponential inlining - see issue #41696.
150 llvm::Attribute::NoInline.apply_callsite(llvm::AttributePlace::Function, llret);
153 if let Some((ret_dest, target)) = destination {
154 this.store_return(&bx, ret_dest, &fn_ty.ret, llret);
155 funclet_br(this, bx, target);
162 self.set_debug_loc(&bx, terminator.source_info);
163 match terminator.kind {
164 mir::TerminatorKind::Resume => {
165 if let Some(cleanup_pad) = cleanup_pad {
166 bx.cleanup_ret(cleanup_pad, None);
168 let slot = self.get_personality_slot(&bx);
169 let lp0 = slot.project_field(&bx, 0).load(&bx).immediate();
170 let lp1 = slot.project_field(&bx, 1).load(&bx).immediate();
171 slot.storage_dead(&bx);
173 if !bx.sess().target.target.options.custom_unwind_resume {
174 let mut lp = bx.cx().c_undef(self.landing_pad_type());
175 lp = bx.insert_value(lp, lp0, 0);
176 lp = bx.insert_value(lp, lp1, 1);
179 bx.call(bx.cx().eh_unwind_resume(), &[lp0], cleanup_bundle);
185 mir::TerminatorKind::Abort => {
186 // Call core::intrinsics::abort()
187 let fnname = bx.cx().get_intrinsic(&("llvm.trap"));
188 bx.call(fnname, &[], None);
192 mir::TerminatorKind::Goto { target } => {
193 funclet_br(self, bx, target);
196 mir::TerminatorKind::SwitchInt { ref discr, switch_ty, ref values, ref targets } => {
197 let discr = self.codegen_operand(&bx, discr);
198 if targets.len() == 2 {
199 // If there are two targets, emit br instead of switch
200 let lltrue = llblock(self, targets[0]);
201 let llfalse = llblock(self, targets[1]);
202 if switch_ty == bx.tcx().types.bool {
203 // Don't generate trivial icmps when switching on bool
204 if let [0] = values[..] {
205 bx.cond_br(discr.immediate(), llfalse, lltrue);
207 assert_eq!(&values[..], &[1]);
208 bx.cond_br(discr.immediate(), lltrue, llfalse);
211 let switch_llty = bx.cx().layout_of(switch_ty).immediate_llvm_type(bx.cx());
212 let llval = bx.cx().c_uint_big(switch_llty, values[0]);
213 let cmp = bx.icmp(IntPredicate::IntEQ, discr.immediate(), llval);
214 bx.cond_br(cmp, lltrue, llfalse);
217 let (otherwise, targets) = targets.split_last().unwrap();
218 let switch = bx.switch(discr.immediate(),
219 llblock(self, *otherwise),
221 let switch_llty = bx.cx().layout_of(switch_ty).immediate_llvm_type(bx.cx());
222 for (&value, target) in values.iter().zip(targets) {
223 let llval =bx.cx().c_uint_big(switch_llty, value);
224 let llbb = llblock(self, *target);
225 bx.add_case(switch, llval, llbb)
230 mir::TerminatorKind::Return => {
231 let llval = match self.fn_ty.ret.mode {
232 PassMode::Ignore | PassMode::Indirect(..) => {
237 PassMode::Direct(_) | PassMode::Pair(..) => {
238 let op = self.codegen_consume(&bx, &mir::Place::Local(mir::RETURN_PLACE));
239 if let Ref(llval, _, align) = op.val {
240 bx.load(llval, align)
242 op.immediate_or_packed_pair(&bx)
246 PassMode::Cast(cast_ty) => {
247 let op = match self.locals[mir::RETURN_PLACE] {
248 LocalRef::Operand(Some(op)) => op,
249 LocalRef::Operand(None) => bug!("use of return before def"),
250 LocalRef::Place(cg_place) => {
252 val: Ref(cg_place.llval, None, cg_place.align),
253 layout: cg_place.layout
256 LocalRef::UnsizedPlace(_) => bug!("return type must be sized"),
258 let llslot = match op.val {
259 Immediate(_) | Pair(..) => {
260 let scratch = PlaceRef::alloca(&bx, self.fn_ty.ret.layout, "ret");
261 op.val.store(&bx, scratch);
264 Ref(llval, _, align) => {
265 assert_eq!(align.abi(), op.layout.align.abi(),
266 "return place is unaligned!");
271 bx.pointercast(llslot, bx.cx().ptr_to(cast_ty.llvm_type(bx.cx()))),
272 self.fn_ty.ret.layout.align)
278 mir::TerminatorKind::Unreachable => {
282 mir::TerminatorKind::Drop { ref location, target, unwind } => {
283 let ty = location.ty(self.mir, bx.tcx()).to_ty(bx.tcx());
284 let ty = self.monomorphize(&ty);
285 let drop_fn = monomorphize::resolve_drop_in_place(bx.cx().tcx, ty);
287 if let ty::InstanceDef::DropGlue(_, None) = drop_fn.def {
288 // we don't actually need to drop anything.
289 funclet_br(self, bx, target);
293 let place = self.codegen_place(&bx, location);
295 let mut args = if let Some(llextra) = place.llextra {
296 args2 = [place.llval, llextra];
299 args1 = [place.llval];
302 let (drop_fn, fn_ty) = match ty.sty {
304 let sig = drop_fn.fn_sig(bx.tcx());
305 let sig = bx.tcx().normalize_erasing_late_bound_regions(
306 ty::ParamEnv::reveal_all(),
309 let fn_ty = FnType::new_vtable(bx.cx(), sig, &[]);
310 let vtable = args[1];
312 (meth::DESTRUCTOR.get_fn(&bx, vtable, &fn_ty), fn_ty)
315 (callee::get_fn(bx.cx(), drop_fn),
316 FnType::of_instance(bx.cx(), &drop_fn))
319 do_call(self, bx, fn_ty, drop_fn, args,
320 Some((ReturnDest::Nothing, target)),
324 mir::TerminatorKind::Assert { ref cond, expected, ref msg, target, cleanup } => {
325 let cond = self.codegen_operand(&bx, cond).immediate();
326 let mut const_cond = bx.cx().const_to_opt_u128(cond, false).map(|c| c == 1);
328 // This case can currently arise only from functions marked
329 // with #[rustc_inherit_overflow_checks] and inlined from
330 // another crate (mostly core::num generic/#[inline] fns),
331 // while the current crate doesn't use overflow checks.
332 // NOTE: Unlike binops, negation doesn't have its own
333 // checked operation, just a comparison with the minimum
334 // value, so we have to check for the assert message.
335 if !bx.cx().check_overflow {
336 if let mir::interpret::EvalErrorKind::OverflowNeg = *msg {
337 const_cond = Some(expected);
341 // Don't codegen the panic block if success if known.
342 if const_cond == Some(expected) {
343 funclet_br(self, bx, target);
347 // Pass the condition through llvm.expect for branch hinting.
348 let expect = bx.cx().get_intrinsic(&"llvm.expect.i1");
349 let cond = bx.call(expect, &[cond, bx.cx().c_bool(expected)], None);
351 // Create the failure block and the conditional branch to it.
352 let lltarget = llblock(self, target);
353 let panic_block = self.new_block("panic");
355 bx.cond_br(cond, lltarget, panic_block.llbb());
357 bx.cond_br(cond, panic_block.llbb(), lltarget);
360 // After this point, bx is the block for the call to panic.
362 self.set_debug_loc(&bx, terminator.source_info);
364 // Get the location information.
365 let loc = bx.sess().source_map().lookup_char_pos(span.lo());
366 let filename = Symbol::intern(&loc.file.name.to_string()).as_str();
367 let filename = bx.cx().c_str_slice(filename);
368 let line = bx.cx().c_u32(loc.line as u32);
369 let col = bx.cx().c_u32(loc.col.to_usize() as u32 + 1);
370 let align = tcx.data_layout.aggregate_align
371 .max(tcx.data_layout.i32_align)
372 .max(tcx.data_layout.pointer_align);
374 // Put together the arguments to the panic entry point.
375 let (lang_item, args) = match *msg {
376 EvalErrorKind::BoundsCheck { ref len, ref index } => {
377 let len = self.codegen_operand(&mut bx, len).immediate();
378 let index = self.codegen_operand(&mut bx, index).immediate();
380 let file_line_col = bx.cx().c_struct(&[filename, line, col], false);
381 let file_line_col = consts::addr_of(bx.cx(),
384 Some("panic_bounds_check_loc"));
385 (lang_items::PanicBoundsCheckFnLangItem,
386 vec![file_line_col, index, len])
389 let str = msg.description();
390 let msg_str = Symbol::intern(str).as_str();
391 let msg_str = bx.cx().c_str_slice(msg_str);
392 let msg_file_line_col = bx.cx().c_struct(
393 &[msg_str, filename, line, col],
396 let msg_file_line_col = consts::addr_of(bx.cx(),
400 (lang_items::PanicFnLangItem,
401 vec![msg_file_line_col])
405 // Obtain the panic entry point.
406 let def_id = common::langcall(bx.tcx(), Some(span), "", lang_item);
407 let instance = ty::Instance::mono(bx.tcx(), def_id);
408 let fn_ty = FnType::of_instance(bx.cx(), &instance);
409 let llfn = callee::get_fn(bx.cx(), instance);
411 // Codegen the actual panic invoke/call.
412 do_call(self, bx, fn_ty, llfn, &args, None, cleanup);
415 mir::TerminatorKind::DropAndReplace { .. } => {
416 bug!("undesugared DropAndReplace in codegen: {:?}", terminator);
419 mir::TerminatorKind::Call {
426 // Create the callee. This is a fn ptr or zero-sized and hence a kind of scalar.
427 let callee = self.codegen_operand(&bx, func);
429 let (instance, mut llfn) = match callee.layout.ty.sty {
430 ty::FnDef(def_id, substs) => {
431 (Some(ty::Instance::resolve(bx.cx().tcx,
432 ty::ParamEnv::reveal_all(),
438 (None, Some(callee.immediate()))
440 _ => bug!("{} is not callable", callee.layout.ty)
442 let def = instance.map(|i| i.def);
443 let sig = callee.layout.ty.fn_sig(bx.tcx());
444 let sig = bx.tcx().normalize_erasing_late_bound_regions(
445 ty::ParamEnv::reveal_all(),
450 // Handle intrinsics old codegen wants Expr's for, ourselves.
451 let intrinsic = match def {
452 Some(ty::InstanceDef::Intrinsic(def_id))
453 => Some(bx.tcx().item_name(def_id).as_str()),
456 let intrinsic = intrinsic.as_ref().map(|s| &s[..]);
458 if intrinsic == Some("transmute") {
459 if let Some(destination_ref) = destination.as_ref() {
460 let &(ref dest, target) = destination_ref;
461 self.codegen_transmute(&bx, &args[0], dest);
462 funclet_br(self, bx, target);
464 // If we are trying to transmute to an uninhabited type,
465 // it is likely there is no allotted destination. In fact,
466 // transmuting to an uninhabited type is UB, which means
467 // we can do what we like. Here, we declare that transmuting
468 // into an uninhabited type is impossible, so anything following
469 // it must be unreachable.
470 assert_eq!(bx.cx().layout_of(sig.output()).abi, layout::Abi::Uninhabited);
476 let extra_args = &args[sig.inputs().len()..];
477 let extra_args = extra_args.iter().map(|op_arg| {
478 let op_ty = op_arg.ty(self.mir, bx.tcx());
479 self.monomorphize(&op_ty)
480 }).collect::<Vec<_>>();
482 let fn_ty = match def {
483 Some(ty::InstanceDef::Virtual(..)) => {
484 FnType::new_vtable(bx.cx(), sig, &extra_args)
486 Some(ty::InstanceDef::DropGlue(_, None)) => {
487 // empty drop glue - a nop.
488 let &(_, target) = destination.as_ref().unwrap();
489 funclet_br(self, bx, target);
492 _ => FnType::new(bx.cx(), sig, &extra_args)
495 // emit a panic instead of instantiating an uninhabited type
496 if (intrinsic == Some("init") || intrinsic == Some("uninit")) &&
497 fn_ty.ret.layout.abi.is_uninhabited()
499 let loc = bx.sess().source_map().lookup_char_pos(span.lo());
500 let filename = Symbol::intern(&loc.file.name.to_string()).as_str();
501 let filename = bx.cx.c_str_slice(filename);
502 let line = bx.cx.c_u32(loc.line as u32);
503 let col = bx.cx.c_u32(loc.col.to_usize() as u32 + 1);
504 let align = tcx.data_layout.aggregate_align
505 .max(tcx.data_layout.i32_align)
506 .max(tcx.data_layout.pointer_align);
509 "Attempted to instantiate uninhabited type {} using mem::{}",
511 if intrinsic == Some("init") { "zeroed" } else { "uninitialized" }
513 let msg_str = Symbol::intern(&str).as_str();
514 let msg_str = bx.cx.c_str_slice(msg_str);
515 let msg_file_line_col = bx.cx.c_struct(
516 &[msg_str, filename, line, col],
519 let msg_file_line_col = consts::addr_of(bx.cx,
524 // Obtain the panic entry point.
526 common::langcall(bx.tcx(), Some(span), "", lang_items::PanicFnLangItem);
527 let instance = ty::Instance::mono(bx.tcx(), def_id);
528 let fn_ty = FnType::of_instance(bx.cx, &instance);
529 let llfn = callee::get_fn(bx.cx, instance);
531 // Codegen the actual panic invoke/call.
537 &[msg_file_line_col],
538 destination.as_ref().map(|(_, bb)| (ReturnDest::Nothing, *bb)),
544 // The arguments we'll be passing. Plus one to account for outptr, if used.
545 let arg_count = fn_ty.args.len() + fn_ty.ret.is_indirect() as usize;
546 let mut llargs = Vec::with_capacity(arg_count);
548 // Prepare the return value destination
549 let ret_dest = if let Some((ref dest, _)) = *destination {
550 let is_intrinsic = intrinsic.is_some();
551 self.make_return_dest(&bx, dest, &fn_ty.ret, &mut llargs,
557 if intrinsic.is_some() && intrinsic != Some("drop_in_place") {
558 use intrinsic::codegen_intrinsic_call;
560 let dest = match ret_dest {
561 _ if fn_ty.ret.is_indirect() => llargs[0],
562 ReturnDest::Nothing => {
563 bx.cx().c_undef(bx.cx().ptr_to(fn_ty.ret.memory_ty(bx.cx())))
565 ReturnDest::IndirectOperand(dst, _) |
566 ReturnDest::Store(dst) => dst.llval,
567 ReturnDest::DirectOperand(_) =>
568 bug!("Cannot use direct operand with an intrinsic call")
571 let args: Vec<_> = args.iter().enumerate().map(|(i, arg)| {
572 // The indices passed to simd_shuffle* in the
573 // third argument must be constant. This is
574 // checked by const-qualification, which also
575 // promotes any complex rvalues to constants.
576 if i == 2 && intrinsic.unwrap().starts_with("simd_shuffle") {
578 // The shuffle array argument is usually not an explicit constant,
579 // but specified directly in the code. This means it gets promoted
580 // and we can then extract the value by evaluating the promoted.
581 mir::Operand::Copy(mir::Place::Promoted(box(index, ty))) |
582 mir::Operand::Move(mir::Place::Promoted(box(index, ty))) => {
583 let param_env = ty::ParamEnv::reveal_all();
584 let cid = mir::interpret::GlobalId {
585 instance: self.instance,
586 promoted: Some(index),
588 let c = bx.tcx().const_eval(param_env.and(cid));
589 let (llval, ty) = self.simd_shuffle_indices(
591 terminator.source_info.span,
596 val: Immediate(llval),
597 layout: bx.cx().layout_of(ty),
601 mir::Operand::Copy(_) |
602 mir::Operand::Move(_) => {
603 span_bug!(span, "shuffle indices must be constant");
605 mir::Operand::Constant(ref constant) => {
606 let c = self.eval_mir_constant(&bx, constant);
607 let (llval, ty) = self.simd_shuffle_indices(
614 val: Immediate(llval),
615 layout: bx.cx().layout_of(ty)
621 self.codegen_operand(&bx, arg)
625 let callee_ty = instance.as_ref().unwrap().ty(bx.cx().tcx);
626 codegen_intrinsic_call(&bx, callee_ty, &fn_ty, &args, dest,
627 terminator.source_info.span);
629 if let ReturnDest::IndirectOperand(dst, _) = ret_dest {
630 self.store_return(&bx, ret_dest, &fn_ty.ret, dst.llval);
633 if let Some((_, target)) = *destination {
634 funclet_br(self, bx, target);
642 // Split the rust-call tupled arguments off.
643 let (first_args, untuple) = if abi == Abi::RustCall && !args.is_empty() {
644 let (tup, args) = args.split_last().unwrap();
650 'make_args: for (i, arg) in first_args.iter().enumerate() {
651 let mut op = self.codegen_operand(&bx, arg);
653 if let (0, Some(ty::InstanceDef::Virtual(_, idx))) = (i, def) {
654 if let Pair(..) = op.val {
655 // In the case of Rc<Self>, we need to explicitly pass a
656 // *mut RcBox<Self> with a Scalar (not ScalarPair) ABI. This is a hack
657 // that is understood elsewhere in the compiler as a method on
659 // To get a `*mut RcBox<Self>`, we just keep unwrapping newtypes until
660 // we get a value of a built-in pointer type
661 'descend_newtypes: while !op.layout.ty.is_unsafe_ptr()
662 && !op.layout.ty.is_region_ptr()
664 'iter_fields: for i in 0..op.layout.fields.count() {
665 let field = op.extract_field(&bx, i);
666 if !field.layout.is_zst() {
667 // we found the one non-zero-sized field that is allowed
668 // now find *its* non-zero-sized field, or stop if it's a
671 continue 'descend_newtypes
675 span_bug!(span, "receiver has no non-zero-sized fields {:?}", op);
678 // now that we have `*dyn Trait` or `&dyn Trait`, split it up into its
679 // data pointer and vtable. Look up the method in the vtable, and pass
680 // the data pointer as the first argument
682 Pair(data_ptr, meta) => {
683 llfn = Some(meth::VirtualIndex::from_index(idx)
684 .get_fn(&bx, meta, &fn_ty));
685 llargs.push(data_ptr);
688 other => bug!("expected a Pair, got {:?}", other)
690 } else if let Ref(data_ptr, Some(meta), _) = op.val {
691 // by-value dynamic dispatch
692 llfn = Some(meth::VirtualIndex::from_index(idx)
693 .get_fn(&bx, meta, &fn_ty));
694 llargs.push(data_ptr);
697 span_bug!(span, "can't codegen a virtual call on {:?}", op);
701 // The callee needs to own the argument memory if we pass it
702 // by-ref, so make a local copy of non-immediate constants.
703 match (arg, op.val) {
704 (&mir::Operand::Copy(_), Ref(_, None, _)) |
705 (&mir::Operand::Constant(_), Ref(_, None, _)) => {
706 let tmp = PlaceRef::alloca(&bx, op.layout, "const");
707 op.val.store(&bx, tmp);
708 op.val = Ref(tmp.llval, None, tmp.align);
713 self.codegen_argument(&bx, op, &mut llargs, &fn_ty.args[i]);
715 if let Some(tup) = untuple {
716 self.codegen_arguments_untupled(&bx, tup, &mut llargs,
717 &fn_ty.args[first_args.len()..])
720 let fn_ptr = match (llfn, instance) {
721 (Some(llfn), _) => llfn,
722 (None, Some(instance)) => callee::get_fn(bx.cx(), instance),
723 _ => span_bug!(span, "no llfn for call"),
726 do_call(self, bx, fn_ty, fn_ptr, &llargs,
727 destination.as_ref().map(|&(_, target)| (ret_dest, target)),
730 mir::TerminatorKind::GeneratorDrop |
731 mir::TerminatorKind::Yield { .. } => bug!("generator ops in codegen"),
732 mir::TerminatorKind::FalseEdges { .. } |
733 mir::TerminatorKind::FalseUnwind { .. } => bug!("borrowck false edges in codegen"),
737 fn codegen_argument(&mut self,
738 bx: &Builder<'a, 'll, 'tcx>,
739 op: OperandRef<'tcx, &'ll Value>,
740 llargs: &mut Vec<&'ll Value>,
741 arg: &ArgType<'tcx, Ty<'tcx>>) {
742 // Fill padding with undef value, where applicable.
743 if let Some(ty) = arg.pad {
744 llargs.push(bx.cx().c_undef(ty.llvm_type(bx.cx())));
751 if let PassMode::Pair(..) = arg.mode {
758 _ => bug!("codegen_argument: {:?} invalid for pair argument", op)
760 } else if arg.is_unsized_indirect() {
762 Ref(a, Some(b), _) => {
767 _ => bug!("codegen_argument: {:?} invalid for unsized indirect argument", op)
771 // Force by-ref if we have to load through a cast pointer.
772 let (mut llval, align, by_ref) = match op.val {
773 Immediate(_) | Pair(..) => {
775 PassMode::Indirect(..) | PassMode::Cast(_) => {
776 let scratch = PlaceRef::alloca(bx, arg.layout, "arg");
777 op.val.store(bx, scratch);
778 (scratch.llval, scratch.align, true)
781 (op.immediate_or_packed_pair(bx), arg.layout.align, false)
785 Ref(llval, _, align) => {
786 if arg.is_indirect() && align.abi() < arg.layout.align.abi() {
787 // `foo(packed.large_field)`. We can't pass the (unaligned) field directly. I
788 // think that ATM (Rust 1.16) we only pass temporaries, but we shouldn't
789 // have scary latent bugs around.
791 let scratch = PlaceRef::alloca(bx, arg.layout, "arg");
792 base::memcpy_ty(bx, scratch.llval, scratch.align, llval, align,
793 op.layout, MemFlags::empty());
794 (scratch.llval, scratch.align, true)
801 if by_ref && !arg.is_indirect() {
802 // Have to load the argument, maybe while casting it.
803 if let PassMode::Cast(ty) = arg.mode {
804 llval = bx.load(bx.pointercast(llval, bx.cx().ptr_to(ty.llvm_type(bx.cx()))),
805 align.min(arg.layout.align));
807 // We can't use `PlaceRef::load` here because the argument
808 // may have a type we don't treat as immediate, but the ABI
809 // used for this call is passing it by-value. In that case,
810 // the load would just produce `OperandValue::Ref` instead
811 // of the `OperandValue::Immediate` we need for the call.
812 llval = bx.load(llval, align);
813 if let layout::Abi::Scalar(ref scalar) = arg.layout.abi {
814 if scalar.is_bool() {
815 bx.range_metadata(llval, 0..2);
818 // We store bools as i8 so we need to truncate to i1.
819 llval = base::to_immediate(bx, llval, arg.layout);
826 fn codegen_arguments_untupled(&mut self,
827 bx: &Builder<'a, 'll, 'tcx>,
828 operand: &mir::Operand<'tcx>,
829 llargs: &mut Vec<&'ll Value>,
830 args: &[ArgType<'tcx, Ty<'tcx>>]) {
831 let tuple = self.codegen_operand(bx, operand);
833 // Handle both by-ref and immediate tuples.
834 if let Ref(llval, None, align) = tuple.val {
835 let tuple_ptr = PlaceRef::new_sized(llval, tuple.layout, align);
836 for i in 0..tuple.layout.fields.count() {
837 let field_ptr = tuple_ptr.project_field(bx, i);
838 self.codegen_argument(bx, field_ptr.load(bx), llargs, &args[i]);
840 } else if let Ref(_, Some(_), _) = tuple.val {
841 bug!("closure arguments must be sized")
843 // If the tuple is immediate, the elements are as well.
844 for i in 0..tuple.layout.fields.count() {
845 let op = tuple.extract_field(bx, i);
846 self.codegen_argument(bx, op, llargs, &args[i]);
851 fn get_personality_slot(
853 bx: &Builder<'a, 'll, 'tcx>
854 ) -> PlaceRef<'tcx, &'ll Value> {
856 if let Some(slot) = self.personality_slot {
859 let layout = cx.layout_of(cx.tcx.intern_tup(&[
860 cx.tcx.mk_mut_ptr(cx.tcx.types.u8),
863 let slot = PlaceRef::alloca(bx, layout, "personalityslot");
864 self.personality_slot = Some(slot);
869 /// Return the landingpad wrapper around the given basic block
871 /// No-op in MSVC SEH scheme.
872 fn landing_pad_to(&mut self, target_bb: mir::BasicBlock) -> &'ll BasicBlock {
873 if let Some(block) = self.landing_pads[target_bb] {
877 let block = self.blocks[target_bb];
878 let landing_pad = self.landing_pad_uncached(block);
879 self.landing_pads[target_bb] = Some(landing_pad);
883 fn landing_pad_uncached(&mut self, target_bb: &'ll BasicBlock) -> &'ll BasicBlock {
884 if base::wants_msvc_seh(self.cx.sess()) {
885 span_bug!(self.mir.span, "landing pad was not inserted?")
888 let bx = self.new_block("cleanup");
890 let llpersonality = self.cx.eh_personality();
891 let llretty = self.landing_pad_type();
892 let lp = bx.landing_pad(llretty, llpersonality, 1);
895 let slot = self.get_personality_slot(&bx);
896 slot.storage_live(&bx);
897 Pair(bx.extract_value(lp, 0), bx.extract_value(lp, 1)).store(&bx, slot);
903 fn landing_pad_type(&self) -> &'ll Type {
905 cx.struct_( &[cx.i8p(), cx.i32()], false)
908 fn unreachable_block(&mut self) -> &'ll BasicBlock {
909 self.unreachable_block.unwrap_or_else(|| {
910 let bl = self.new_block("unreachable");
912 self.unreachable_block = Some(bl.llbb());
917 pub fn new_block(&self, name: &str) -> Builder<'a, 'll, 'tcx> {
918 Builder::new_block(self.cx, self.llfn, name)
921 pub fn build_block(&self, bb: mir::BasicBlock) -> Builder<'a, 'll, 'tcx> {
922 let bx = Builder::with_cx(self.cx);
923 bx.position_at_end(self.blocks[bb]);
927 fn make_return_dest(&mut self, bx: &Builder<'a, 'll, 'tcx>,
928 dest: &mir::Place<'tcx>, fn_ret: &ArgType<'tcx, Ty<'tcx>>,
929 llargs: &mut Vec<&'ll Value>, is_intrinsic: bool)
930 -> ReturnDest<'tcx, &'ll Value> {
931 // If the return is ignored, we can just return a do-nothing ReturnDest
932 if fn_ret.is_ignore() {
933 return ReturnDest::Nothing;
935 let dest = if let mir::Place::Local(index) = *dest {
936 match self.locals[index] {
937 LocalRef::Place(dest) => dest,
938 LocalRef::UnsizedPlace(_) => bug!("return type must be sized"),
939 LocalRef::Operand(None) => {
940 // Handle temporary places, specifically Operand ones, as
941 // they don't have allocas
942 return if fn_ret.is_indirect() {
943 // Odd, but possible, case, we have an operand temporary,
944 // but the calling convention has an indirect return.
945 let tmp = PlaceRef::alloca(bx, fn_ret.layout, "tmp_ret");
946 tmp.storage_live(bx);
947 llargs.push(tmp.llval);
948 ReturnDest::IndirectOperand(tmp, index)
949 } else if is_intrinsic {
950 // Currently, intrinsics always need a location to store
951 // the result. so we create a temporary alloca for the
953 let tmp = PlaceRef::alloca(bx, fn_ret.layout, "tmp_ret");
954 tmp.storage_live(bx);
955 ReturnDest::IndirectOperand(tmp, index)
957 ReturnDest::DirectOperand(index)
960 LocalRef::Operand(Some(_)) => {
961 bug!("place local already assigned to");
965 self.codegen_place(bx, dest)
967 if fn_ret.is_indirect() {
968 if dest.align.abi() < dest.layout.align.abi() {
969 // Currently, MIR code generation does not create calls
970 // that store directly to fields of packed structs (in
971 // fact, the calls it creates write only to temps),
973 // If someone changes that, please update this code path
974 // to create a temporary.
975 span_bug!(self.mir.span, "can't directly store to unaligned value");
977 llargs.push(dest.llval);
980 ReturnDest::Store(dest)
984 fn codegen_transmute(&mut self, bx: &Builder<'a, 'll, 'tcx>,
985 src: &mir::Operand<'tcx>,
986 dst: &mir::Place<'tcx>) {
987 if let mir::Place::Local(index) = *dst {
988 match self.locals[index] {
989 LocalRef::Place(place) => self.codegen_transmute_into(bx, src, place),
990 LocalRef::UnsizedPlace(_) => bug!("transmute must not involve unsized locals"),
991 LocalRef::Operand(None) => {
992 let dst_layout = bx.cx().layout_of(self.monomorphized_place_ty(dst));
993 assert!(!dst_layout.ty.has_erasable_regions());
994 let place = PlaceRef::alloca(bx, dst_layout, "transmute_temp");
995 place.storage_live(bx);
996 self.codegen_transmute_into(bx, src, place);
997 let op = place.load(bx);
998 place.storage_dead(bx);
999 self.locals[index] = LocalRef::Operand(Some(op));
1001 LocalRef::Operand(Some(op)) => {
1002 assert!(op.layout.is_zst(),
1003 "assigning to initialized SSAtemp");
1007 let dst = self.codegen_place(bx, dst);
1008 self.codegen_transmute_into(bx, src, dst);
1012 fn codegen_transmute_into(&mut self, bx: &Builder<'a, 'll, 'tcx>,
1013 src: &mir::Operand<'tcx>,
1014 dst: PlaceRef<'tcx, &'ll Value>) {
1015 let src = self.codegen_operand(bx, src);
1016 let llty = src.layout.llvm_type(bx.cx());
1017 let cast_ptr = bx.pointercast(dst.llval, bx.cx().ptr_to(llty));
1018 let align = src.layout.align.min(dst.layout.align);
1019 src.val.store(bx, PlaceRef::new_sized(cast_ptr, src.layout, align));
1023 // Stores the return value of a function call into it's final location.
1024 fn store_return(&mut self,
1025 bx: &Builder<'a, 'll, 'tcx>,
1026 dest: ReturnDest<'tcx, &'ll Value>,
1027 ret_ty: &ArgType<'tcx, Ty<'tcx>>,
1028 llval: &'ll Value) {
1029 use self::ReturnDest::*;
1033 Store(dst) => ret_ty.store(bx, llval, dst),
1034 IndirectOperand(tmp, index) => {
1035 let op = tmp.load(bx);
1036 tmp.storage_dead(bx);
1037 self.locals[index] = LocalRef::Operand(Some(op));
1039 DirectOperand(index) => {
1040 // If there is a cast, we have to store and reload.
1041 let op = if let PassMode::Cast(_) = ret_ty.mode {
1042 let tmp = PlaceRef::alloca(bx, ret_ty.layout, "tmp_ret");
1043 tmp.storage_live(bx);
1044 ret_ty.store(bx, llval, tmp);
1045 let op = tmp.load(bx);
1046 tmp.storage_dead(bx);
1049 OperandRef::from_immediate_or_packed_pair(bx, llval, ret_ty.layout)
1051 self.locals[index] = LocalRef::Operand(Some(op));
1057 enum ReturnDest<'tcx, V> {
1058 // Do nothing, the return value is indirect or ignored
1060 // Store the return value to the pointer
1061 Store(PlaceRef<'tcx, V>),
1062 // Stores an indirect return value to an operand local place
1063 IndirectOperand(PlaceRef<'tcx, V>, mir::Local),
1064 // Stores a direct return value to an operand local place
1065 DirectOperand(mir::Local)